+ * Implementations of this interface must be thread-safe. Access to shared
+ * data must be synchronized as methods of this interface may be executed
+ * from multiple threads.
+ *
+ * @since 4.0
+ */
+public interface ConnectionReuseStrategy {
+
+ /**
+ * Decides whether a connection can be kept open after a request.
+ * If this method returns false, the caller MUST
+ * close the connection to correctly comply with the HTTP protocol.
+ * If it returns true, the caller SHOULD attempt to
+ * keep the connection open for reuse with another request.
+ *
+ * One can use the HTTP context to retrieve additional objects that
+ * may be relevant for the keep-alive strategy: the actual HTTP
+ * connection, the original HTTP request, target host if known,
+ * number of times the connection has been reused already and so on.
+ *
+ * If the connection is already closed, false is returned.
+ * The stale connection check MUST NOT be triggered by a
+ * connection reuse strategy.
+ *
+ * @param response
+ * The last response received over that connection.
+ * @param context the context in which the connection is being
+ * used.
+ *
+ * @return true if the connection is allowed to be reused, or
+ * false if it MUST NOT be reused
+ */
+ boolean keepAlive(HttpResponse response, HttpContext context);
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/Consts.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/Consts.java
new file mode 100644
index 000000000..81e2a7592
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/Consts.java
@@ -0,0 +1,51 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib;
+
+import java.nio.charset.Charset;
+
+/**
+ * Commons constants.
+ *
+ * @since 4.2
+ */
+public final class Consts {
+
+ public static final int CR = 13; //
+ public static final int LF = 10; //
+ public static final int SP = 32; //
+ public static final int HT = 9; //
+
+ public static final Charset UTF_8 = Charset.forName("UTF-8");
+ public static final Charset ASCII = Charset.forName("US-ASCII");
+ public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
+
+ private Consts() {
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/ContentTooLongException.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/ContentTooLongException.java
new file mode 100644
index 000000000..64f83b3af
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/ContentTooLongException.java
@@ -0,0 +1,50 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib;
+
+import java.io.IOException;
+
+/**
+ * Signals that HTTP entity content is too long.
+ *
+ * @since 4.2
+ */
+public class ContentTooLongException extends IOException {
+
+ private static final long serialVersionUID = -924287689552495383L;
+
+ /**
+ * Creates a new ContentTooLongException with the specified detail message.
+ *
+ * @param message exception message
+ */
+ public ContentTooLongException(final String message) {
+ super(message);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/FormattedHeader.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/FormattedHeader.java
new file mode 100644
index 000000000..cd3f4126d
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/FormattedHeader.java
@@ -0,0 +1,60 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib;
+
+import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
+
+/**
+ * An HTTP header which is already formatted.
+ * For example when headers are received, the original formatting
+ * can be preserved. This allows for the header to be sent without
+ * another formatting step.
+ *
+ * @since 4.0
+ */
+public interface FormattedHeader extends Header {
+
+ /**
+ * Obtains the buffer with the formatted header.
+ * The returned buffer MUST NOT be modified.
+ *
+ * @return the formatted header, in a buffer that must not be modified
+ */
+ CharArrayBuffer getBuffer();
+
+ /**
+ * Obtains the start of the header value in the {@link #getBuffer buffer}.
+ * By accessing the value in the buffer, creation of a temporary string
+ * can be avoided.
+ *
+ * @return index of the first character of the header value
+ * in the buffer returned by {@link #getBuffer getBuffer}.
+ */
+ int getValuePos();
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/Header.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/Header.java
new file mode 100644
index 000000000..50ce75a92
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/Header.java
@@ -0,0 +1,74 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib;
+
+/**
+ * Represents an HTTP header field.
+ *
+ *
The HTTP header fields follow the same generic format as
+ * that given in Section 3.1 of RFC 822. Each header field consists
+ * of a name followed by a colon (":") and the field value. Field names
+ * are case-insensitive. The field value MAY be preceded by any amount
+ * of LWS, though a single SP is preferred.
+ *
+ *
+ * message-header = field-name ":" [ field-value ]
+ * field-name = token
+ * field-value = *( field-content | LWS )
+ * field-content = <the OCTETs making up the field-value
+ * and consisting of either *TEXT or combinations
+ * of token, separators, and quoted-string>
+ *
+ *
+ * @since 4.0
+ */
+public interface Header {
+
+ /**
+ * Get the name of the Header.
+ *
+ * @return the name of the Header, never {@code null}
+ */
+ String getName();
+
+ /**
+ * Get the value of the Header.
+ *
+ * @return the value of the Header, may be {@code null}
+ */
+ String getValue();
+
+ /**
+ * Parses the value.
+ *
+ * @return an array of {@link HeaderElement} entries, may be empty, but is never {@code null}
+ * @throws ParseException
+ */
+ HeaderElement[] getElements() throws ParseException;
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/HeaderElement.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/HeaderElement.java
new file mode 100644
index 000000000..f6fcf8f04
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/HeaderElement.java
@@ -0,0 +1,108 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib;
+
+/**
+ * One element of an HTTP {@link Header header} value consisting of
+ * a name / value pair and a number of optional name / value parameters.
+ *
+ * Some HTTP headers (such as the set-cookie header) have values that
+ * can be decomposed into multiple elements. Such headers must be in the
+ * following form:
+ *
+ *
+ * header = [ element ] *( "," [ element ] )
+ * element = name [ "=" [ value ] ] *( ";" [ param ] )
+ * param = name [ "=" [ value ] ]
+ *
+ * name = token
+ * value = ( token | quoted-string )
+ *
+ * token = 1*<any char except "=", ",", ";", <"> and
+ * white space>
+ * quoted-string = <"> *( text | quoted-char ) <">
+ * text = any char except <">
+ * quoted-char = "\" char
+ *
+ *
+ * Any amount of white space is allowed between any part of the
+ * header, element or param and is ignored. A missing value in any
+ * element or param will be stored as the empty {@link String};
+ * if the "=" is also missing null will be stored instead.
+ *
+ * @since 4.0
+ */
+public interface HeaderElement {
+
+ /**
+ * Returns header element name.
+ *
+ * @return header element name
+ */
+ String getName();
+
+ /**
+ * Returns header element value.
+ *
+ * @return header element value
+ */
+ String getValue();
+
+ /**
+ * Returns an array of name / value pairs.
+ *
+ * @return array of name / value pairs
+ */
+ NameValuePair[] getParameters();
+
+ /**
+ * Returns the first parameter with the given name.
+ *
+ * @param name parameter name
+ *
+ * @return name / value pair
+ */
+ NameValuePair getParameterByName(String name);
+
+ /**
+ * Returns the total count of parameters.
+ *
+ * @return parameter count
+ */
+ int getParameterCount();
+
+ /**
+ * Returns parameter with the given index.
+ *
+ * @param index index
+ * @return name / value pair
+ */
+ NameValuePair getParameter(int index);
+
+}
+
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/HeaderElementIterator.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/HeaderElementIterator.java
new file mode 100644
index 000000000..c0ef11346
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/HeaderElementIterator.java
@@ -0,0 +1,57 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib;
+
+import java.util.Iterator;
+
+/**
+ * A type-safe iterator for {@link HeaderElement} objects.
+ *
+ * @since 4.0
+ */
+public interface HeaderElementIterator extends Iterator
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class HttpPost extends HttpEntityEnclosingRequestBase {
+
+ public final static String METHOD_NAME = "POST";
+
+ public HttpPost() {
+ super();
+ }
+
+ public HttpPost(final URI uri) {
+ super();
+ setURI(uri);
+ }
+
+ /**
+ * @throws IllegalArgumentException if the uri is invalid.
+ */
+ public HttpPost(final String uri) {
+ super();
+ setURI(URI.create(uri));
+ }
+
+ @Override
+ public String getMethod() {
+ return METHOD_NAME;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/HttpPut.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/HttpPut.java
new file mode 100644
index 000000000..4aab04b23
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/HttpPut.java
@@ -0,0 +1,76 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.methods;
+
+import java.net.URI;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+
+/**
+ * HTTP PUT method.
+ *
+ * The HTTP PUT method is defined in section 9.6 of
+ * RFC2616:
+ *
+ * The PUT method requests that the enclosed entity be stored under the
+ * supplied Request-URI. If the Request-URI refers to an already
+ * existing resource, the enclosed entity SHOULD be considered as a
+ * modified version of the one residing on the origin server.
+ *
+ *
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class HttpPut extends HttpEntityEnclosingRequestBase {
+
+ public final static String METHOD_NAME = "PUT";
+
+ public HttpPut() {
+ super();
+ }
+
+ public HttpPut(final URI uri) {
+ super();
+ setURI(uri);
+ }
+
+ /**
+ * @throws IllegalArgumentException if the uri is invalid.
+ */
+ public HttpPut(final String uri) {
+ super();
+ setURI(URI.create(uri));
+ }
+
+ @Override
+ public String getMethod() {
+ return METHOD_NAME;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/HttpRequestBase.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/HttpRequestBase.java
new file mode 100644
index 000000000..da3b01ef5
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/HttpRequestBase.java
@@ -0,0 +1,124 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.methods;
+
+import java.net.URI;
+
+import ch.boye.httpclientandroidlib.ProtocolVersion;
+import ch.boye.httpclientandroidlib.RequestLine;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.client.config.RequestConfig;
+import ch.boye.httpclientandroidlib.message.BasicRequestLine;
+import ch.boye.httpclientandroidlib.params.HttpProtocolParams;
+
+/**
+ * Base implementation of {@link HttpUriRequest}.
+ *
+ * @since 4.0
+ */
+@SuppressWarnings("deprecation")
+@NotThreadSafe
+public abstract class HttpRequestBase extends AbstractExecutionAwareRequest
+ implements HttpUriRequest, Configurable {
+
+ private ProtocolVersion version;
+ private URI uri;
+ private RequestConfig config;
+
+ public abstract String getMethod();
+
+ /**
+ * @since 4.3
+ */
+ public void setProtocolVersion(final ProtocolVersion version) {
+ this.version = version;
+ }
+
+ public ProtocolVersion getProtocolVersion() {
+ return version != null ? version : HttpProtocolParams.getVersion(getParams());
+ }
+
+ /**
+ * Returns the original request URI.
+ *
+ * Please note URI remains unchanged in the course of request execution and
+ * is not updated if the request is redirected to another location.
+ */
+ public URI getURI() {
+ return this.uri;
+ }
+
+ public RequestLine getRequestLine() {
+ final String method = getMethod();
+ final ProtocolVersion ver = getProtocolVersion();
+ final URI uri = getURI();
+ String uritext = null;
+ if (uri != null) {
+ uritext = uri.toASCIIString();
+ }
+ if (uritext == null || uritext.length() == 0) {
+ uritext = "/";
+ }
+ return new BasicRequestLine(method, uritext, ver);
+ }
+
+
+ public RequestConfig getConfig() {
+ return config;
+ }
+
+ public void setConfig(final RequestConfig config) {
+ this.config = config;
+ }
+
+ public void setURI(final URI uri) {
+ this.uri = uri;
+ }
+
+ /**
+ * @since 4.2
+ */
+ public void started() {
+ }
+
+ /**
+ * A convenience method to simplify migration from HttpClient 3.1 API. This method is
+ * equivalent to {@link #reset()}.
+ *
+ * @since 4.2
+ */
+ public void releaseConnection() {
+ reset();
+ }
+
+ @Override
+ public String toString() {
+ return getMethod() + " " + getURI() + " " + getProtocolVersion();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/HttpRequestWrapper.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/HttpRequestWrapper.java
new file mode 100644
index 000000000..72b7e2c55
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/HttpRequestWrapper.java
@@ -0,0 +1,171 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.methods;
+
+import java.net.URI;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.ProtocolVersion;
+import ch.boye.httpclientandroidlib.RequestLine;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.message.AbstractHttpMessage;
+import ch.boye.httpclientandroidlib.message.BasicRequestLine;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+
+/**
+ * A wrapper class for {@link HttpRequest} that can be used to change properties of the current
+ * request without modifying the original object.
+ *
+ * @since 4.3
+ */
+@SuppressWarnings("deprecation")
+@NotThreadSafe
+public class HttpRequestWrapper extends AbstractHttpMessage implements HttpUriRequest {
+
+ private final HttpRequest original;
+ private final String method;
+ private ProtocolVersion version;
+ private URI uri;
+
+ private HttpRequestWrapper(final HttpRequest request) {
+ super();
+ this.original = request;
+ this.version = this.original.getRequestLine().getProtocolVersion();
+ this.method = this.original.getRequestLine().getMethod();
+ if (request instanceof HttpUriRequest) {
+ this.uri = ((HttpUriRequest) request).getURI();
+ } else {
+ this.uri = null;
+ }
+ setHeaders(request.getAllHeaders());
+ }
+
+ public ProtocolVersion getProtocolVersion() {
+ return this.version != null ? this.version : this.original.getProtocolVersion();
+ }
+
+ public void setProtocolVersion(final ProtocolVersion version) {
+ this.version = version;
+ }
+
+ public URI getURI() {
+ return this.uri;
+ }
+
+ public void setURI(final URI uri) {
+ this.uri = uri;
+ }
+
+ public String getMethod() {
+ return method;
+ }
+
+ public void abort() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean isAborted() {
+ return false;
+ }
+
+ public RequestLine getRequestLine() {
+ String requestUri = null;
+ if (this.uri != null) {
+ requestUri = this.uri.toASCIIString();
+ } else {
+ requestUri = this.original.getRequestLine().getUri();
+ }
+ if (requestUri == null || requestUri.length() == 0) {
+ requestUri = "/";
+ }
+ return new BasicRequestLine(this.method, requestUri, getProtocolVersion());
+ }
+
+ public HttpRequest getOriginal() {
+ return this.original;
+ }
+
+ @Override
+ public String toString() {
+ return getRequestLine() + " " + this.headergroup;
+ }
+
+ static class HttpEntityEnclosingRequestWrapper extends HttpRequestWrapper
+ implements HttpEntityEnclosingRequest {
+
+ private HttpEntity entity;
+
+ public HttpEntityEnclosingRequestWrapper(final HttpEntityEnclosingRequest request) {
+ super(request);
+ this.entity = request.getEntity();
+ }
+
+ public HttpEntity getEntity() {
+ return this.entity;
+ }
+
+ public void setEntity(final HttpEntity entity) {
+ this.entity = entity;
+ }
+
+ public boolean expectContinue() {
+ final Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE);
+ return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue());
+ }
+
+ }
+
+ public static HttpRequestWrapper wrap(final HttpRequest request) {
+ if (request == null) {
+ return null;
+ }
+ if (request instanceof HttpEntityEnclosingRequest) {
+ return new HttpEntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request);
+ } else {
+ return new HttpRequestWrapper(request);
+ }
+ }
+
+ /**
+ * @deprecated (4.3) use
+ * {@link ch.boye.httpclientandroidlib.client.config.RequestConfig}.
+ */
+ @Override
+ @Deprecated
+ public HttpParams getParams() {
+ if (this.params == null) {
+ this.params = original.getParams().copy();
+ }
+ return this.params;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/HttpTrace.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/HttpTrace.java
new file mode 100644
index 000000000..1118ea181
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/HttpTrace.java
@@ -0,0 +1,79 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.methods;
+
+import java.net.URI;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+
+/**
+ * HTTP TRACE method.
+ *
+ * The HTTP TRACE method is defined in section 9.6 of
+ * RFC2616:
+ *
+ * The TRACE method is used to invoke a remote, application-layer loop-
+ * back of the request message. The final recipient of the request
+ * SHOULD reflect the message received back to the client as the
+ * entity-body of a 200 (OK) response. The final recipient is either the
+ * origin server or the first proxy or gateway to receive a Max-Forwards
+ * value of zero (0) in the request (see section 14.31). A TRACE request
+ * MUST NOT include an entity.
+ *
+ *
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class HttpTrace extends HttpRequestBase {
+
+ public final static String METHOD_NAME = "TRACE";
+
+ public HttpTrace() {
+ super();
+ }
+
+ public HttpTrace(final URI uri) {
+ super();
+ setURI(uri);
+ }
+
+ /**
+ * @throws IllegalArgumentException if the uri is invalid.
+ */
+ public HttpTrace(final String uri) {
+ super();
+ setURI(URI.create(uri));
+ }
+
+ @Override
+ public String getMethod() {
+ return METHOD_NAME;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/HttpUriRequest.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/HttpUriRequest.java
new file mode 100644
index 000000000..8ab14ef85
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/HttpUriRequest.java
@@ -0,0 +1,84 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.methods;
+
+import java.net.URI;
+
+import ch.boye.httpclientandroidlib.HttpRequest;
+
+/**
+ * Extended version of the {@link HttpRequest} interface that provides
+ * convenience methods to access request properties such as request URI
+ * and method type.
+ *
+ * @since 4.0
+ */
+public interface HttpUriRequest extends HttpRequest {
+
+ /**
+ * Returns the HTTP method this request uses, such as GET,
+ * PUT, POST, or other.
+ */
+ String getMethod();
+
+ /**
+ * Returns the URI this request uses, such as
+ * http://example.org/path/to/file.
+ *
+ * Note that the URI may be absolute URI (as above) or may be a relative URI.
+ *
+ * Implementations are encouraged to return
+ * the URI that was initially requested.
+ *
+ *
+ * To find the final URI after any redirects have been processed,
+ * please see the section entitled
+ * HTTP execution context
+ * in the
+ * HttpClient Tutorial
+ *
+ */
+ URI getURI();
+
+ /**
+ * Aborts execution of the request.
+ *
+ * @throws UnsupportedOperationException if the abort operation
+ * is not supported / cannot be implemented.
+ */
+ void abort() throws UnsupportedOperationException;
+
+ /**
+ * Tests if the request execution has been aborted.
+ *
+ * @return true if the request execution has been aborted,
+ * false otherwise.
+ */
+ boolean isAborted();
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/RequestBuilder.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/RequestBuilder.java
new file mode 100644
index 000000000..3a45dcd2f
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/RequestBuilder.java
@@ -0,0 +1,351 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.methods;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HeaderIterator;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.NameValuePair;
+import ch.boye.httpclientandroidlib.ProtocolVersion;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.client.config.RequestConfig;
+import ch.boye.httpclientandroidlib.client.entity.UrlEncodedFormEntity;
+import ch.boye.httpclientandroidlib.client.utils.URIBuilder;
+import ch.boye.httpclientandroidlib.message.BasicHeader;
+import ch.boye.httpclientandroidlib.message.BasicNameValuePair;
+import ch.boye.httpclientandroidlib.message.HeaderGroup;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Builder for {@link HttpUriRequest} instances.
+ *
+ * Please note that this class treats parameters differently depending on composition
+ * of the request: if the request has a content entity explicitly set with
+ * {@link #setEntity(ch.boye.httpclientandroidlib.HttpEntity)} or it is not an entity enclosing method
+ * (such as POST or PUT), parameters will be added to the query component of the request URI.
+ * Otherwise, parameters will be added as a URL encoded {@link UrlEncodedFormEntity entity}.
+ *
+ * @since 4.3
+ */
+@NotThreadSafe
+public class RequestBuilder {
+
+ private String method;
+ private ProtocolVersion version;
+ private URI uri;
+ private HeaderGroup headergroup;
+ private HttpEntity entity;
+ private LinkedList parameters;
+ private RequestConfig config;
+
+ RequestBuilder(final String method) {
+ super();
+ this.method = method;
+ }
+
+ RequestBuilder() {
+ this(null);
+ }
+
+ public static RequestBuilder create(final String method) {
+ Args.notBlank(method, "HTTP method");
+ return new RequestBuilder(method);
+ }
+
+ public static RequestBuilder get() {
+ return new RequestBuilder(HttpGet.METHOD_NAME);
+ }
+
+ public static RequestBuilder head() {
+ return new RequestBuilder(HttpHead.METHOD_NAME);
+ }
+
+ public static RequestBuilder post() {
+ return new RequestBuilder(HttpPost.METHOD_NAME);
+ }
+
+ public static RequestBuilder put() {
+ return new RequestBuilder(HttpPut.METHOD_NAME);
+ }
+
+ public static RequestBuilder delete() {
+ return new RequestBuilder(HttpDelete.METHOD_NAME);
+ }
+
+ public static RequestBuilder trace() {
+ return new RequestBuilder(HttpTrace.METHOD_NAME);
+ }
+
+ public static RequestBuilder options() {
+ return new RequestBuilder(HttpOptions.METHOD_NAME);
+ }
+
+ public static RequestBuilder copy(final HttpRequest request) {
+ Args.notNull(request, "HTTP request");
+ return new RequestBuilder().doCopy(request);
+ }
+
+ private RequestBuilder doCopy(final HttpRequest request) {
+ if (request == null) {
+ return this;
+ }
+ method = request.getRequestLine().getMethod();
+ version = request.getRequestLine().getProtocolVersion();
+ if (request instanceof HttpUriRequest) {
+ uri = ((HttpUriRequest) request).getURI();
+ } else {
+ uri = URI.create(request.getRequestLine().getUri());
+ }
+ if (headergroup == null) {
+ headergroup = new HeaderGroup();
+ }
+ headergroup.clear();
+ headergroup.setHeaders(request.getAllHeaders());
+ if (request instanceof HttpEntityEnclosingRequest) {
+ entity = ((HttpEntityEnclosingRequest) request).getEntity();
+ } else {
+ entity = null;
+ }
+ if (request instanceof Configurable) {
+ this.config = ((Configurable) request).getConfig();
+ } else {
+ this.config = null;
+ }
+ this.parameters = null;
+ return this;
+ }
+
+ public String getMethod() {
+ return method;
+ }
+
+ public ProtocolVersion getVersion() {
+ return version;
+ }
+
+ public RequestBuilder setVersion(final ProtocolVersion version) {
+ this.version = version;
+ return this;
+ }
+
+ public URI getUri() {
+ return uri;
+ }
+
+ public RequestBuilder setUri(final URI uri) {
+ this.uri = uri;
+ return this;
+ }
+
+ public RequestBuilder setUri(final String uri) {
+ this.uri = uri != null ? URI.create(uri) : null;
+ return this;
+ }
+
+ public Header getFirstHeader(final String name) {
+ return headergroup != null ? headergroup.getFirstHeader(name) : null;
+ }
+
+ public Header getLastHeader(final String name) {
+ return headergroup != null ? headergroup.getLastHeader(name) : null;
+ }
+
+ public Header[] getHeaders(final String name) {
+ return headergroup != null ? headergroup.getHeaders(name) : null;
+ }
+
+ public RequestBuilder addHeader(final Header header) {
+ if (headergroup == null) {
+ headergroup = new HeaderGroup();
+ }
+ headergroup.addHeader(header);
+ return this;
+ }
+
+ public RequestBuilder addHeader(final String name, final String value) {
+ if (headergroup == null) {
+ headergroup = new HeaderGroup();
+ }
+ this.headergroup.addHeader(new BasicHeader(name, value));
+ return this;
+ }
+
+ public RequestBuilder removeHeader(final Header header) {
+ if (headergroup == null) {
+ headergroup = new HeaderGroup();
+ }
+ headergroup.removeHeader(header);
+ return this;
+ }
+
+ public RequestBuilder removeHeaders(final String name) {
+ if (name == null || headergroup == null) {
+ return this;
+ }
+ for (final HeaderIterator i = headergroup.iterator(); i.hasNext(); ) {
+ final Header header = i.nextHeader();
+ if (name.equalsIgnoreCase(header.getName())) {
+ i.remove();
+ }
+ }
+ return this;
+ }
+
+ public RequestBuilder setHeader(final Header header) {
+ if (headergroup == null) {
+ headergroup = new HeaderGroup();
+ }
+ this.headergroup.updateHeader(header);
+ return this;
+ }
+
+ public RequestBuilder setHeader(final String name, final String value) {
+ if (headergroup == null) {
+ headergroup = new HeaderGroup();
+ }
+ this.headergroup.updateHeader(new BasicHeader(name, value));
+ return this;
+ }
+
+ public HttpEntity getEntity() {
+ return entity;
+ }
+
+ public RequestBuilder setEntity(final HttpEntity entity) {
+ this.entity = entity;
+ return this;
+ }
+
+ public List getParameters() {
+ return parameters != null ? new ArrayList(parameters) :
+ new ArrayList();
+ }
+
+ public RequestBuilder addParameter(final NameValuePair nvp) {
+ Args.notNull(nvp, "Name value pair");
+ if (parameters == null) {
+ parameters = new LinkedList();
+ }
+ parameters.add(nvp);
+ return this;
+ }
+
+ public RequestBuilder addParameter(final String name, final String value) {
+ return addParameter(new BasicNameValuePair(name, value));
+ }
+
+ public RequestBuilder addParameters(final NameValuePair... nvps) {
+ for (final NameValuePair nvp: nvps) {
+ addParameter(nvp);
+ }
+ return this;
+ }
+
+ public RequestConfig getConfig() {
+ return config;
+ }
+
+ public RequestBuilder setConfig(final RequestConfig config) {
+ this.config = config;
+ return this;
+ }
+
+ public HttpUriRequest build() {
+ final HttpRequestBase result;
+ URI uri = this.uri != null ? this.uri : URI.create("/");
+ HttpEntity entity = this.entity;
+ if (parameters != null && !parameters.isEmpty()) {
+ if (entity == null && (HttpPost.METHOD_NAME.equalsIgnoreCase(method)
+ || HttpPut.METHOD_NAME.equalsIgnoreCase(method))) {
+ entity = new UrlEncodedFormEntity(parameters, HTTP.DEF_CONTENT_CHARSET);
+ } else {
+ try {
+ uri = new URIBuilder(uri).addParameters(parameters).build();
+ } catch (final URISyntaxException ex) {
+ // should never happen
+ }
+ }
+ }
+ if (entity == null) {
+ result = new InternalRequest(method);
+ } else {
+ final InternalEntityEclosingRequest request = new InternalEntityEclosingRequest(method);
+ request.setEntity(entity);
+ result = request;
+ }
+ result.setProtocolVersion(this.version);
+ result.setURI(uri);
+ if (this.headergroup != null) {
+ result.setHeaders(this.headergroup.getAllHeaders());
+ }
+ result.setConfig(this.config);
+ return result;
+ }
+
+ static class InternalRequest extends HttpRequestBase {
+
+ private final String method;
+
+ InternalRequest(final String method) {
+ super();
+ this.method = method;
+ }
+
+ @Override
+ public String getMethod() {
+ return this.method;
+ }
+
+ }
+
+ static class InternalEntityEclosingRequest extends HttpEntityEnclosingRequestBase {
+
+ private final String method;
+
+ InternalEntityEclosingRequest(final String method) {
+ super();
+ this.method = method;
+ }
+
+ @Override
+ public String getMethod() {
+ return this.method;
+ }
+
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/package-info.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/package-info.java
new file mode 100644
index 000000000..d8266b2e3
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/methods/package-info.java
@@ -0,0 +1,31 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+/**
+ * Standard HTTP method implementations.
+ */
+package ch.boye.httpclientandroidlib.client.methods;
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/package-info.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/package-info.java
new file mode 100644
index 000000000..2d49a2b99
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/package-info.java
@@ -0,0 +1,31 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+/**
+ * Client HTTP communication APIs.
+ */
+package ch.boye.httpclientandroidlib.client;
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/AllClientPNames.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/AllClientPNames.java
new file mode 100644
index 000000000..aaf591571
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/AllClientPNames.java
@@ -0,0 +1,63 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.client.params;
+
+import ch.boye.httpclientandroidlib.auth.params.AuthPNames;
+import ch.boye.httpclientandroidlib.conn.params.ConnConnectionPNames;
+import ch.boye.httpclientandroidlib.conn.params.ConnManagerPNames;
+import ch.boye.httpclientandroidlib.conn.params.ConnRoutePNames;
+import ch.boye.httpclientandroidlib.cookie.params.CookieSpecPNames;
+import ch.boye.httpclientandroidlib.params.CoreConnectionPNames;
+import ch.boye.httpclientandroidlib.params.CoreProtocolPNames;
+
+/**
+ * Collected parameter names for the HttpClient module.
+ * This interface combines the parameter definitions of the HttpClient
+ * module and all dependency modules or informational units.
+ * It does not define additional parameter names, but references
+ * other interfaces defining parameter names.
+ *
+ * This interface is meant as a navigation aid for developers.
+ * When referring to parameter names, you should use the interfaces
+ * in which the respective constants are actually defined.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use
+ * {@link ch.boye.httpclientandroidlib.client.config.RequestConfig},
+ * {@link ch.boye.httpclientandroidlib.config.ConnectionConfig},
+ * {@link ch.boye.httpclientandroidlib.config.SocketConfig}
+ */
+@Deprecated
+public interface AllClientPNames extends
+ CoreConnectionPNames, CoreProtocolPNames,
+ ClientPNames, AuthPNames, CookieSpecPNames,
+ ConnConnectionPNames, ConnManagerPNames, ConnRoutePNames {
+
+ // no additional definitions
+}
+
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/AuthPolicy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/AuthPolicy.java
new file mode 100644
index 000000000..b677ee02f
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/AuthPolicy.java
@@ -0,0 +1,79 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.params;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+
+/**
+ * Standard authentication schemes supported by HttpClient.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link ch.boye.httpclientandroidlib.client.config.AuthSchemes}.
+ */
+@Deprecated
+@Immutable
+public final class AuthPolicy {
+
+ private AuthPolicy() {
+ super();
+ }
+
+ /**
+ * The NTLM scheme is a proprietary Microsoft Windows Authentication
+ * protocol (considered to be the most secure among currently supported
+ * authentication schemes).
+ */
+ public static final String NTLM = "NTLM";
+
+ /**
+ * Digest authentication scheme as defined in RFC2617.
+ */
+ public static final String DIGEST = "Digest";
+
+ /**
+ * Basic authentication scheme as defined in RFC2617 (considered inherently
+ * insecure, but most widely supported)
+ */
+ public static final String BASIC = "Basic";
+
+ /**
+ * SPNEGO Authentication scheme.
+ *
+ * @since 4.1
+ */
+ public static final String SPNEGO = "negotiate";
+
+ /**
+ * Kerberos Authentication scheme.
+ *
+ * @since 4.2
+ */
+ public static final String KERBEROS = "Kerberos";
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/ClientPNames.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/ClientPNames.java
new file mode 100644
index 000000000..796ee40fb
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/ClientPNames.java
@@ -0,0 +1,133 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.client.params;
+
+/**
+ * Parameter names for HTTP client parameters.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link ch.boye.httpclientandroidlib.client.config.RequestConfig}.
+ */
+@Deprecated
+public interface ClientPNames {
+
+ public static final String CONNECTION_MANAGER_FACTORY_CLASS_NAME = "http.connection-manager.factory-class-name";
+
+ /**
+ * Defines whether redirects should be handled automatically
+ *
+ * This parameter expects a value of type {@link Boolean}.
+ *
+ */
+ public static final String HANDLE_REDIRECTS = "http.protocol.handle-redirects";
+
+ /**
+ * Defines whether relative redirects should be rejected. HTTP specification
+ * requires the location value be an absolute URI.
+ *
+ * This parameter expects a value of type {@link Boolean}.
+ *
+ */
+ public static final String REJECT_RELATIVE_REDIRECT = "http.protocol.reject-relative-redirect";
+
+ /**
+ * Defines the maximum number of redirects to be followed.
+ * The limit on number of redirects is intended to prevent infinite loops.
+ *
+ * This parameter expects a value of type {@link Integer}.
+ *
+ */
+ public static final String MAX_REDIRECTS = "http.protocol.max-redirects";
+
+ /**
+ * Defines whether circular redirects (redirects to the same location) should be allowed.
+ * The HTTP spec is not sufficiently clear whether circular redirects are permitted,
+ * therefore optionally they can be enabled
+ *
+ * This parameter expects a value of type {@link Boolean}.
+ *
+ */
+ public static final String ALLOW_CIRCULAR_REDIRECTS = "http.protocol.allow-circular-redirects";
+
+ /**
+ * Defines whether authentication should be handled automatically.
+ *
+ * This parameter expects a value of type {@link Boolean}.
+ *
+ */
+ public static final String HANDLE_AUTHENTICATION = "http.protocol.handle-authentication";
+
+ /**
+ * Defines the name of the cookie specification to be used for HTTP state management.
+ *
+ * This parameter expects a value of type {@link String}.
+ *
+ */
+ public static final String COOKIE_POLICY = "http.protocol.cookie-policy";
+
+ /**
+ * Defines the virtual host to be used in the Host
+ * request header instead of the physical host.
+ *
+ * This parameter expects a value of type {@link ch.boye.httpclientandroidlib.HttpHost}.
+ *
+ * If a port is not provided, it will be derived from the request URL.
+ */
+ public static final String VIRTUAL_HOST = "http.virtual-host";
+
+ /**
+ * Defines the request headers to be sent per default with each request.
+ *
+ * This parameter expects a value of type {@link java.util.Collection}. The
+ * collection is expected to contain {@link ch.boye.httpclientandroidlib.Header}s.
+ *
+ */
+ public static final String DEFAULT_HEADERS = "http.default-headers";
+
+ /**
+ * Defines the default host. The default value will be used if the target host is
+ * not explicitly specified in the request URI.
+ *
+ * This parameter expects a value of type {@link ch.boye.httpclientandroidlib.HttpHost}.
+ *
+ */
+ public static final String DEFAULT_HOST = "http.default-host";
+
+ /**
+ * Defines the timeout in milliseconds used when retrieving an instance of
+ * {@link ch.boye.httpclientandroidlib.conn.ManagedClientConnection} from the
+ * {@link ch.boye.httpclientandroidlib.conn.ClientConnectionManager}.
+ *
+ * This parameter expects a value of type {@link Long}.
+ *
+ * @since 4.2
+ */
+ public static final String CONN_MANAGER_TIMEOUT = "http.conn-manager.timeout";
+
+}
+
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/ClientParamBean.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/ClientParamBean.java
new file mode 100644
index 000000000..315129d23
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/ClientParamBean.java
@@ -0,0 +1,106 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.params;
+
+import java.util.Collection;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.params.HttpAbstractParamBean;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+
+/**
+ * This is a Java Bean class that can be used to wrap an instance of
+ * {@link HttpParams} and manipulate HTTP client parameters using
+ * Java Beans conventions.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link ch.boye.httpclientandroidlib.client.config.RequestConfig}.
+ */
+@Deprecated
+@NotThreadSafe
+public class ClientParamBean extends HttpAbstractParamBean {
+
+ public ClientParamBean (final HttpParams params) {
+ super(params);
+ }
+
+ /**
+ * @deprecated (4.2) do not use.
+ */
+ @Deprecated
+ public void setConnectionManagerFactoryClassName (final String factory) {
+ params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, factory);
+ }
+
+ public void setHandleRedirects (final boolean handle) {
+ params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, handle);
+ }
+
+ public void setRejectRelativeRedirect (final boolean reject) {
+ params.setBooleanParameter(ClientPNames.REJECT_RELATIVE_REDIRECT, reject);
+ }
+
+ public void setMaxRedirects (final int maxRedirects) {
+ params.setIntParameter(ClientPNames.MAX_REDIRECTS, maxRedirects);
+ }
+
+ public void setAllowCircularRedirects (final boolean allow) {
+ params.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, allow);
+ }
+
+ public void setHandleAuthentication (final boolean handle) {
+ params.setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, handle);
+ }
+
+ public void setCookiePolicy (final String policy) {
+ params.setParameter(ClientPNames.COOKIE_POLICY, policy);
+ }
+
+ public void setVirtualHost (final HttpHost host) {
+ params.setParameter(ClientPNames.VIRTUAL_HOST, host);
+ }
+
+ public void setDefaultHeaders (final Collection headers) {
+ params.setParameter(ClientPNames.DEFAULT_HEADERS, headers);
+ }
+
+ public void setDefaultHost (final HttpHost host) {
+ params.setParameter(ClientPNames.DEFAULT_HOST, host);
+ }
+
+ /**
+ * @since 4.2
+ */
+ public void setConnectionManagerTimeout(final long timeout) {
+ params.setLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, timeout);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/CookiePolicy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/CookiePolicy.java
new file mode 100644
index 000000000..5c6353b80
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/CookiePolicy.java
@@ -0,0 +1,80 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.params;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+
+/**
+ * Standard cookie specifications supported by HttpClient.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link ch.boye.httpclientandroidlib.client.config.CookieSpecs}.
+ */
+@Deprecated
+@Immutable
+public final class CookiePolicy {
+
+ /**
+ * The policy that provides high degree of compatibilty
+ * with common cookie management of popular HTTP agents.
+ */
+ public static final String BROWSER_COMPATIBILITY = "compatibility";
+
+ /**
+ * The Netscape cookie draft compliant policy.
+ */
+ public static final String NETSCAPE = "netscape";
+
+ /**
+ * The RFC 2109 compliant policy.
+ */
+ public static final String RFC_2109 = "rfc2109";
+
+ /**
+ * The RFC 2965 compliant policy.
+ */
+ public static final String RFC_2965 = "rfc2965";
+
+ /**
+ * The default 'best match' policy.
+ */
+ public static final String BEST_MATCH = "best-match";
+
+ /**
+ * The policy that ignores cookies.
+ *
+ * @since 4.1-beta1
+ */
+ public static final String IGNORE_COOKIES = "ignoreCookies";
+
+ private CookiePolicy() {
+ super();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/HttpClientParamConfig.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/HttpClientParamConfig.java
new file mode 100644
index 000000000..515d92ca5
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/HttpClientParamConfig.java
@@ -0,0 +1,88 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.params;
+
+import java.net.InetAddress;
+import java.util.Collection;
+
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.auth.params.AuthPNames;
+import ch.boye.httpclientandroidlib.client.config.RequestConfig;
+import ch.boye.httpclientandroidlib.conn.params.ConnRoutePNames;
+import ch.boye.httpclientandroidlib.params.CoreConnectionPNames;
+import ch.boye.httpclientandroidlib.params.CoreProtocolPNames;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+
+/**
+ * @deprecated (4.3) provided for compatibility with {@link HttpParams}. Do not use.
+ *
+ * @since 4.3
+ */
+@Deprecated
+public final class HttpClientParamConfig {
+
+ private HttpClientParamConfig() {
+ }
+
+ @SuppressWarnings("unchecked")
+ public static RequestConfig getRequestConfig(final HttpParams params) {
+ return RequestConfig.custom()
+ .setSocketTimeout(params.getIntParameter(
+ CoreConnectionPNames.SO_TIMEOUT, 0))
+ .setStaleConnectionCheckEnabled(params.getBooleanParameter(
+ CoreConnectionPNames.STALE_CONNECTION_CHECK, true))
+ .setConnectTimeout(params.getIntParameter(
+ CoreConnectionPNames.CONNECTION_TIMEOUT, 0))
+ .setExpectContinueEnabled(params.getBooleanParameter(
+ CoreProtocolPNames.USE_EXPECT_CONTINUE, false))
+ .setProxy((HttpHost) params.getParameter(
+ ConnRoutePNames.DEFAULT_PROXY))
+ .setLocalAddress((InetAddress) params.getParameter(
+ ConnRoutePNames.LOCAL_ADDRESS))
+ .setProxyPreferredAuthSchemes((Collection) params.getParameter(
+ AuthPNames.PROXY_AUTH_PREF))
+ .setTargetPreferredAuthSchemes((Collection) params.getParameter(
+ AuthPNames.TARGET_AUTH_PREF))
+ .setAuthenticationEnabled(params.getBooleanParameter(
+ ClientPNames.HANDLE_AUTHENTICATION, true))
+ .setCircularRedirectsAllowed(params.getBooleanParameter(
+ ClientPNames.ALLOW_CIRCULAR_REDIRECTS, false))
+ .setConnectionRequestTimeout((int) params.getLongParameter(
+ ClientPNames.CONN_MANAGER_TIMEOUT, 0))
+ .setCookieSpec((String) params.getParameter(
+ ClientPNames.COOKIE_POLICY))
+ .setMaxRedirects(params.getIntParameter(
+ ClientPNames.MAX_REDIRECTS, 50))
+ .setRedirectsEnabled(params.getBooleanParameter(
+ ClientPNames.HANDLE_REDIRECTS, true))
+ .setRelativeRedirectsAllowed(!params.getBooleanParameter(
+ ClientPNames.REJECT_RELATIVE_REDIRECT, false))
+ .build();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/HttpClientParams.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/HttpClientParams.java
new file mode 100644
index 000000000..b2b2a573e
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/HttpClientParams.java
@@ -0,0 +1,116 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.client.params;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.params.HttpConnectionParams;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * An adaptor for manipulating HTTP client parameters in {@link HttpParams}.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link ch.boye.httpclientandroidlib.client.config.RequestConfig}
+ */
+@Deprecated
+@Immutable
+public class HttpClientParams {
+
+ private HttpClientParams() {
+ super();
+ }
+
+ public static boolean isRedirecting(final HttpParams params) {
+ Args.notNull(params, "HTTP parameters");
+ return params.getBooleanParameter
+ (ClientPNames.HANDLE_REDIRECTS, true);
+ }
+
+ public static void setRedirecting(final HttpParams params, final boolean value) {
+ Args.notNull(params, "HTTP parameters");
+ params.setBooleanParameter
+ (ClientPNames.HANDLE_REDIRECTS, value);
+ }
+
+ public static boolean isAuthenticating(final HttpParams params) {
+ Args.notNull(params, "HTTP parameters");
+ return params.getBooleanParameter
+ (ClientPNames.HANDLE_AUTHENTICATION, true);
+ }
+
+ public static void setAuthenticating(final HttpParams params, final boolean value) {
+ Args.notNull(params, "HTTP parameters");
+ params.setBooleanParameter
+ (ClientPNames.HANDLE_AUTHENTICATION, value);
+ }
+
+ public static String getCookiePolicy(final HttpParams params) {
+ Args.notNull(params, "HTTP parameters");
+ final String cookiePolicy = (String)
+ params.getParameter(ClientPNames.COOKIE_POLICY);
+ if (cookiePolicy == null) {
+ return CookiePolicy.BEST_MATCH;
+ }
+ return cookiePolicy;
+ }
+
+ public static void setCookiePolicy(final HttpParams params, final String cookiePolicy) {
+ Args.notNull(params, "HTTP parameters");
+ params.setParameter(ClientPNames.COOKIE_POLICY, cookiePolicy);
+ }
+
+ /**
+ * Set the parameter {@code ClientPNames.CONN_MANAGER_TIMEOUT}.
+ *
+ * @since 4.2
+ */
+ public static void setConnectionManagerTimeout(final HttpParams params, final long timeout) {
+ Args.notNull(params, "HTTP parameters");
+ params.setLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, timeout);
+ }
+
+ /**
+ * Get the connectiion manager timeout value.
+ * This is defined by the parameter {@code ClientPNames.CONN_MANAGER_TIMEOUT}.
+ * Failing that it uses the parameter {@code CoreConnectionPNames.CONNECTION_TIMEOUT}
+ * which defaults to 0 if not defined.
+ *
+ * @since 4.2
+ * @return the timeout value
+ */
+ public static long getConnectionManagerTimeout(final HttpParams params) {
+ Args.notNull(params, "HTTP parameters");
+ final Long timeout = (Long) params.getParameter(ClientPNames.CONN_MANAGER_TIMEOUT);
+ if (timeout != null) {
+ return timeout.longValue();
+ }
+ return HttpConnectionParams.getConnectionTimeout(params);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/package-info.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/package-info.java
new file mode 100644
index 000000000..3450f368e
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/params/package-info.java
@@ -0,0 +1,32 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+/**
+ * Deprecated.
+ * @deprecated (4.3).
+ */
+package ch.boye.httpclientandroidlib.client.params;
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/ClientContext.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/ClientContext.java
new file mode 100644
index 000000000..1409362f0
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/ClientContext.java
@@ -0,0 +1,132 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.protocol;
+
+/**
+ * {@link ch.boye.httpclientandroidlib.protocol.HttpContext} attribute names for
+ * client side HTTP protocol processing.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link HttpClientContext}.
+ */
+@Deprecated
+public interface ClientContext {
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.conn.routing.RouteInfo}
+ * object that represents the actual connection route.
+ *
+ * @since 4.3
+ */
+ public static final String ROUTE = "http.route";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.conn.scheme.Scheme}
+ * object that represents the actual protocol scheme registry.
+ */
+ @Deprecated
+ public static final String SCHEME_REGISTRY = "http.scheme-registry";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.config.Lookup} object that represents
+ * the actual {@link ch.boye.httpclientandroidlib.cookie.CookieSpecRegistry} registry.
+ */
+ public static final String COOKIESPEC_REGISTRY = "http.cookiespec-registry";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.cookie.CookieSpec}
+ * object that represents the actual cookie specification.
+ */
+ public static final String COOKIE_SPEC = "http.cookie-spec";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.cookie.CookieOrigin}
+ * object that represents the actual details of the origin server.
+ */
+ public static final String COOKIE_ORIGIN = "http.cookie-origin";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.client.CookieStore}
+ * object that represents the actual cookie store.
+ */
+ public static final String COOKIE_STORE = "http.cookie-store";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.client.CredentialsProvider}
+ * object that represents the actual credentials provider.
+ */
+ public static final String CREDS_PROVIDER = "http.auth.credentials-provider";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.client.AuthCache} object
+ * that represents the auth scheme cache.
+ */
+ public static final String AUTH_CACHE = "http.auth.auth-cache";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.auth.AuthState}
+ * object that represents the actual target authentication state.
+ */
+ public static final String TARGET_AUTH_STATE = "http.auth.target-scope";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.auth.AuthState}
+ * object that represents the actual proxy authentication state.
+ */
+ public static final String PROXY_AUTH_STATE = "http.auth.proxy-scope";
+
+ /**
+ * @deprecated (4.1) do not use
+ */
+ @Deprecated
+ public static final String AUTH_SCHEME_PREF = "http.auth.scheme-pref";
+
+ /**
+ * Attribute name of a {@link java.lang.Object} object that represents
+ * the actual user identity such as user {@link java.security.Principal}.
+ */
+ public static final String USER_TOKEN = "http.user-token";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.config.Lookup} object that represents
+ * the actual {@link ch.boye.httpclientandroidlib.auth.AuthSchemeRegistry} registry.
+ */
+ public static final String AUTHSCHEME_REGISTRY = "http.authscheme-registry";
+
+ public static final String SOCKET_FACTORY_REGISTRY = "http.socket-factory-registry";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.client.config.RequestConfig} object that
+ * represents the actual request configuration.
+ *
+ * @since 4.3
+ */
+ public static final String REQUEST_CONFIG = "http.request-config";
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/ClientContextConfigurer.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/ClientContextConfigurer.java
new file mode 100644
index 000000000..29628a83d
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/ClientContextConfigurer.java
@@ -0,0 +1,72 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.protocol;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.auth.AuthSchemeRegistry;
+import ch.boye.httpclientandroidlib.client.CookieStore;
+import ch.boye.httpclientandroidlib.client.CredentialsProvider;
+import ch.boye.httpclientandroidlib.cookie.CookieSpecRegistry;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Configuration facade for {@link HttpContext} instances.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link HttpClientContext}
+ */
+@NotThreadSafe
+@Deprecated
+public class ClientContextConfigurer implements ClientContext {
+
+ private final HttpContext context;
+
+ public ClientContextConfigurer (final HttpContext context) {
+ Args.notNull(context, "HTTP context");
+ this.context = context;
+ }
+
+ public void setCookieSpecRegistry(final CookieSpecRegistry registry) {
+ this.context.setAttribute(COOKIESPEC_REGISTRY, registry);
+ }
+
+ public void setAuthSchemeRegistry(final AuthSchemeRegistry registry) {
+ this.context.setAttribute(AUTHSCHEME_REGISTRY, registry);
+ }
+
+ public void setCookieStore(final CookieStore store) {
+ this.context.setAttribute(COOKIE_STORE, store);
+ }
+
+ public void setCredentialsProvider(final CredentialsProvider provider) {
+ this.context.setAttribute(CREDS_PROVIDER, provider);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/HttpClientContext.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/HttpClientContext.java
new file mode 100644
index 000000000..7b73e8d64
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/HttpClientContext.java
@@ -0,0 +1,249 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.protocol;
+
+import java.net.URI;
+import java.util.List;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.auth.AuthSchemeProvider;
+import ch.boye.httpclientandroidlib.auth.AuthState;
+import ch.boye.httpclientandroidlib.client.AuthCache;
+import ch.boye.httpclientandroidlib.client.CookieStore;
+import ch.boye.httpclientandroidlib.client.CredentialsProvider;
+import ch.boye.httpclientandroidlib.client.config.RequestConfig;
+import ch.boye.httpclientandroidlib.config.Lookup;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.conn.routing.RouteInfo;
+import ch.boye.httpclientandroidlib.cookie.CookieOrigin;
+import ch.boye.httpclientandroidlib.cookie.CookieSpec;
+import ch.boye.httpclientandroidlib.cookie.CookieSpecProvider;
+import ch.boye.httpclientandroidlib.protocol.BasicHttpContext;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.protocol.HttpCoreContext;
+
+/**
+ * Adaptor class that provides convenience type safe setters and getters
+ * for common {@link HttpContext} attributes used in the course
+ * of HTTP request execution.
+ *
+ * @since 4.3
+ */
+@NotThreadSafe
+public class HttpClientContext extends HttpCoreContext {
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.conn.routing.RouteInfo}
+ * object that represents the actual connection route.
+ */
+ public static final String HTTP_ROUTE = "http.route";
+
+ /**
+ * Attribute name of a {@link List} object that represents a collection of all
+ * redirect locations received in the process of request execution.
+ */
+ public static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.config.Lookup} object that represents
+ * the actual {@link CookieSpecProvider} registry.
+ */
+ public static final String COOKIESPEC_REGISTRY = "http.cookiespec-registry";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.cookie.CookieSpec}
+ * object that represents the actual cookie specification.
+ */
+ public static final String COOKIE_SPEC = "http.cookie-spec";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.cookie.CookieOrigin}
+ * object that represents the actual details of the origin server.
+ */
+ public static final String COOKIE_ORIGIN = "http.cookie-origin";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.client.CookieStore}
+ * object that represents the actual cookie store.
+ */
+ public static final String COOKIE_STORE = "http.cookie-store";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.client.CredentialsProvider}
+ * object that represents the actual credentials provider.
+ */
+ public static final String CREDS_PROVIDER = "http.auth.credentials-provider";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.client.AuthCache} object
+ * that represents the auth scheme cache.
+ */
+ public static final String AUTH_CACHE = "http.auth.auth-cache";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.auth.AuthState}
+ * object that represents the actual target authentication state.
+ */
+ public static final String TARGET_AUTH_STATE = "http.auth.target-scope";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.auth.AuthState}
+ * object that represents the actual proxy authentication state.
+ */
+ public static final String PROXY_AUTH_STATE = "http.auth.proxy-scope";
+
+ /**
+ * Attribute name of a {@link java.lang.Object} object that represents
+ * the actual user identity such as user {@link java.security.Principal}.
+ */
+ public static final String USER_TOKEN = "http.user-token";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.config.Lookup} object that represents
+ * the actual {@link AuthSchemeProvider} registry.
+ */
+ public static final String AUTHSCHEME_REGISTRY = "http.authscheme-registry";
+
+ /**
+ * Attribute name of a {@link ch.boye.httpclientandroidlib.client.config.RequestConfig} object that
+ * represents the actual request configuration.
+ */
+ public static final String REQUEST_CONFIG = "http.request-config";
+
+ public static HttpClientContext adapt(final HttpContext context) {
+ if (context instanceof HttpClientContext) {
+ return (HttpClientContext) context;
+ } else {
+ return new HttpClientContext(context);
+ }
+ }
+
+ public static HttpClientContext create() {
+ return new HttpClientContext(new BasicHttpContext());
+ }
+
+ public HttpClientContext(final HttpContext context) {
+ super(context);
+ }
+
+ public HttpClientContext() {
+ super();
+ }
+
+ public RouteInfo getHttpRoute() {
+ return getAttribute(HTTP_ROUTE, HttpRoute.class);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List getRedirectLocations() {
+ return getAttribute(REDIRECT_LOCATIONS, List.class);
+ }
+
+ public CookieStore getCookieStore() {
+ return getAttribute(COOKIE_STORE, CookieStore.class);
+ }
+
+ public void setCookieStore(final CookieStore cookieStore) {
+ setAttribute(COOKIE_STORE, cookieStore);
+ }
+
+ public CookieSpec getCookieSpec() {
+ return getAttribute(COOKIE_SPEC, CookieSpec.class);
+ }
+
+ public CookieOrigin getCookieOrigin() {
+ return getAttribute(COOKIE_ORIGIN, CookieOrigin.class);
+ }
+
+ @SuppressWarnings("unchecked")
+ private Lookup getLookup(final String name, final Class clazz) {
+ return getAttribute(name, Lookup.class);
+ }
+
+ public Lookup getCookieSpecRegistry() {
+ return getLookup(COOKIESPEC_REGISTRY, CookieSpecProvider.class);
+ }
+
+ public void setCookieSpecRegistry(final Lookup lookup) {
+ setAttribute(COOKIESPEC_REGISTRY, lookup);
+ }
+
+ public Lookup getAuthSchemeRegistry() {
+ return getLookup(AUTHSCHEME_REGISTRY, AuthSchemeProvider.class);
+ }
+
+ public void setAuthSchemeRegistry(final Lookup lookup) {
+ setAttribute(AUTHSCHEME_REGISTRY, lookup);
+ }
+
+ public CredentialsProvider getCredentialsProvider() {
+ return getAttribute(CREDS_PROVIDER, CredentialsProvider.class);
+ }
+
+ public void setCredentialsProvider(final CredentialsProvider credentialsProvider) {
+ setAttribute(CREDS_PROVIDER, credentialsProvider);
+ }
+
+ public AuthCache getAuthCache() {
+ return getAttribute(AUTH_CACHE, AuthCache.class);
+ }
+
+ public void setAuthCache(final AuthCache authCache) {
+ setAttribute(AUTH_CACHE, authCache);
+ }
+
+ public AuthState getTargetAuthState() {
+ return getAttribute(TARGET_AUTH_STATE, AuthState.class);
+ }
+
+ public AuthState getProxyAuthState() {
+ return getAttribute(PROXY_AUTH_STATE, AuthState.class);
+ }
+
+ public T getUserToken(final Class clazz) {
+ return getAttribute(USER_TOKEN, clazz);
+ }
+
+ public Object getUserToken() {
+ return getAttribute(USER_TOKEN);
+ }
+
+ public void setUserToken(final Object obj) {
+ setAttribute(USER_TOKEN, obj);
+ }
+
+ public RequestConfig getRequestConfig() {
+ final RequestConfig config = getAttribute(REQUEST_CONFIG, RequestConfig.class);
+ return config != null ? config : RequestConfig.DEFAULT;
+ }
+
+ public void setRequestConfig(final RequestConfig config) {
+ setAttribute(REQUEST_CONFIG, config);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestAcceptEncoding.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestAcceptEncoding.java
new file mode 100644
index 000000000..1c0d642d3
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestAcceptEncoding.java
@@ -0,0 +1,62 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.client.protocol;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpRequestInterceptor;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+/**
+ * Class responsible for handling Content Encoding requests in HTTP.
+ *
+ * Instances of this class are stateless, therefore they're thread-safe and immutable.
+ *
+ * @see "http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5"
+ *
+ * @since 4.1
+ */
+@Immutable
+public class RequestAcceptEncoding implements HttpRequestInterceptor {
+
+ /**
+ * Adds the header {@code "Accept-Encoding: gzip,deflate"} to the request.
+ */
+ public void process(
+ final HttpRequest request,
+ final HttpContext context) throws HttpException, IOException {
+
+ /* Signal support for Accept-Encoding transfer encodings. */
+ if (!request.containsHeader("Accept-Encoding")) {
+ request.addHeader("Accept-Encoding", "gzip,deflate");
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestAddCookies.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestAddCookies.java
new file mode 100644
index 000000000..ad2768043
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestAddCookies.java
@@ -0,0 +1,204 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.protocol;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpRequestInterceptor;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.CookieStore;
+import ch.boye.httpclientandroidlib.client.config.CookieSpecs;
+import ch.boye.httpclientandroidlib.client.config.RequestConfig;
+import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest;
+import ch.boye.httpclientandroidlib.config.Lookup;
+import ch.boye.httpclientandroidlib.conn.routing.RouteInfo;
+import ch.boye.httpclientandroidlib.cookie.Cookie;
+import ch.boye.httpclientandroidlib.cookie.CookieOrigin;
+import ch.boye.httpclientandroidlib.cookie.CookieSpec;
+import ch.boye.httpclientandroidlib.cookie.CookieSpecProvider;
+import ch.boye.httpclientandroidlib.cookie.SetCookie2;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.TextUtils;
+
+/**
+ * Request interceptor that matches cookies available in the current
+ * {@link CookieStore} to the request being executed and generates
+ * corresponding Cookie request headers.
+ *
+ * @since 4.0
+ */
+@Immutable
+public class RequestAddCookies implements HttpRequestInterceptor {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ public RequestAddCookies() {
+ super();
+ }
+
+ public void process(final HttpRequest request, final HttpContext context)
+ throws HttpException, IOException {
+ Args.notNull(request, "HTTP request");
+ Args.notNull(context, "HTTP context");
+
+ final String method = request.getRequestLine().getMethod();
+ if (method.equalsIgnoreCase("CONNECT")) {
+ return;
+ }
+
+ final HttpClientContext clientContext = HttpClientContext.adapt(context);
+
+ // Obtain cookie store
+ final CookieStore cookieStore = clientContext.getCookieStore();
+ if (cookieStore == null) {
+ this.log.debug("Cookie store not specified in HTTP context");
+ return;
+ }
+
+ // Obtain the registry of cookie specs
+ final Lookup registry = clientContext.getCookieSpecRegistry();
+ if (registry == null) {
+ this.log.debug("CookieSpec registry not specified in HTTP context");
+ return;
+ }
+
+ // Obtain the target host, possibly virtual (required)
+ final HttpHost targetHost = clientContext.getTargetHost();
+ if (targetHost == null) {
+ this.log.debug("Target host not set in the context");
+ return;
+ }
+
+ // Obtain the route (required)
+ final RouteInfo route = clientContext.getHttpRoute();
+ if (route == null) {
+ this.log.debug("Connection route not set in the context");
+ return;
+ }
+
+ final RequestConfig config = clientContext.getRequestConfig();
+ String policy = config.getCookieSpec();
+ if (policy == null) {
+ policy = CookieSpecs.BEST_MATCH;
+ }
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("CookieSpec selected: " + policy);
+ }
+
+ URI requestURI = null;
+ if (request instanceof HttpUriRequest) {
+ requestURI = ((HttpUriRequest) request).getURI();
+ } else {
+ try {
+ requestURI = new URI(request.getRequestLine().getUri());
+ } catch (final URISyntaxException ignore) {
+ }
+ }
+ final String path = requestURI != null ? requestURI.getPath() : null;
+ final String hostName = targetHost.getHostName();
+ int port = targetHost.getPort();
+ if (port < 0) {
+ port = route.getTargetHost().getPort();
+ }
+
+ final CookieOrigin cookieOrigin = new CookieOrigin(
+ hostName,
+ port >= 0 ? port : 0,
+ !TextUtils.isEmpty(path) ? path : "/",
+ route.isSecure());
+
+ // Get an instance of the selected cookie policy
+ final CookieSpecProvider provider = registry.lookup(policy);
+ if (provider == null) {
+ throw new HttpException("Unsupported cookie policy: " + policy);
+ }
+ final CookieSpec cookieSpec = provider.create(clientContext);
+ // Get all cookies available in the HTTP state
+ final List cookies = new ArrayList(cookieStore.getCookies());
+ // Find cookies matching the given origin
+ final List matchedCookies = new ArrayList();
+ final Date now = new Date();
+ for (final Cookie cookie : cookies) {
+ if (!cookie.isExpired(now)) {
+ if (cookieSpec.match(cookie, cookieOrigin)) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Cookie " + cookie + " match " + cookieOrigin);
+ }
+ matchedCookies.add(cookie);
+ }
+ } else {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Cookie " + cookie + " expired");
+ }
+ }
+ }
+ // Generate Cookie request headers
+ if (!matchedCookies.isEmpty()) {
+ final List headers = cookieSpec.formatCookies(matchedCookies);
+ for (final Header header : headers) {
+ request.addHeader(header);
+ }
+ }
+
+ final int ver = cookieSpec.getVersion();
+ if (ver > 0) {
+ boolean needVersionHeader = false;
+ for (final Cookie cookie : matchedCookies) {
+ if (ver != cookie.getVersion() || !(cookie instanceof SetCookie2)) {
+ needVersionHeader = true;
+ }
+ }
+
+ if (needVersionHeader) {
+ final Header header = cookieSpec.getVersionHeader();
+ if (header != null) {
+ // Advertise cookie version support
+ request.addHeader(header);
+ }
+ }
+ }
+
+ // Stick the CookieSpec and CookieOrigin instances to the HTTP context
+ // so they could be obtained by the response interceptor
+ context.setAttribute(HttpClientContext.COOKIE_SPEC, cookieSpec);
+ context.setAttribute(HttpClientContext.COOKIE_ORIGIN, cookieOrigin);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestAuthCache.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestAuthCache.java
new file mode 100644
index 000000000..08102cfc8
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestAuthCache.java
@@ -0,0 +1,147 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.protocol;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpRequestInterceptor;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.auth.AuthProtocolState;
+import ch.boye.httpclientandroidlib.auth.AuthScheme;
+import ch.boye.httpclientandroidlib.auth.AuthScope;
+import ch.boye.httpclientandroidlib.auth.AuthState;
+import ch.boye.httpclientandroidlib.auth.Credentials;
+import ch.boye.httpclientandroidlib.client.AuthCache;
+import ch.boye.httpclientandroidlib.client.CredentialsProvider;
+import ch.boye.httpclientandroidlib.conn.routing.RouteInfo;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Request interceptor that can preemptively authenticate against known hosts,
+ * if there is a cached {@link AuthScheme} instance in the local
+ * {@link AuthCache} associated with the given target or proxy host.
+ *
+ * @since 4.1
+ */
+@Immutable
+public class RequestAuthCache implements HttpRequestInterceptor {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ public RequestAuthCache() {
+ super();
+ }
+
+ public void process(final HttpRequest request, final HttpContext context)
+ throws HttpException, IOException {
+ Args.notNull(request, "HTTP request");
+ Args.notNull(context, "HTTP context");
+
+ final HttpClientContext clientContext = HttpClientContext.adapt(context);
+
+ final AuthCache authCache = clientContext.getAuthCache();
+ if (authCache == null) {
+ this.log.debug("Auth cache not set in the context");
+ return;
+ }
+
+ final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
+ if (credsProvider == null) {
+ this.log.debug("Credentials provider not set in the context");
+ return;
+ }
+
+ final RouteInfo route = clientContext.getHttpRoute();
+ if (route == null) {
+ this.log.debug("Route info not set in the context");
+ return;
+ }
+
+ HttpHost target = clientContext.getTargetHost();
+ if (target == null) {
+ this.log.debug("Target host not set in the context");
+ return;
+ }
+
+ if (target.getPort() < 0) {
+ target = new HttpHost(
+ target.getHostName(),
+ route.getTargetHost().getPort(),
+ target.getSchemeName());
+ }
+
+ final AuthState targetState = clientContext.getTargetAuthState();
+ if (targetState != null && targetState.getState() == AuthProtocolState.UNCHALLENGED) {
+ final AuthScheme authScheme = authCache.get(target);
+ if (authScheme != null) {
+ doPreemptiveAuth(target, authScheme, targetState, credsProvider);
+ }
+ }
+
+ final HttpHost proxy = route.getProxyHost();
+ final AuthState proxyState = clientContext.getProxyAuthState();
+ if (proxy != null && proxyState != null && proxyState.getState() == AuthProtocolState.UNCHALLENGED) {
+ final AuthScheme authScheme = authCache.get(proxy);
+ if (authScheme != null) {
+ doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider);
+ }
+ }
+ }
+
+ private void doPreemptiveAuth(
+ final HttpHost host,
+ final AuthScheme authScheme,
+ final AuthState authState,
+ final CredentialsProvider credsProvider) {
+ final String schemeName = authScheme.getSchemeName();
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Re-using cached '" + schemeName + "' auth scheme for " + host);
+ }
+
+ final AuthScope authScope = new AuthScope(host, AuthScope.ANY_REALM, schemeName);
+ final Credentials creds = credsProvider.getCredentials(authScope);
+
+ if (creds != null) {
+ if ("BASIC".equalsIgnoreCase(authScheme.getSchemeName())) {
+ authState.setState(AuthProtocolState.CHALLENGED);
+ } else {
+ authState.setState(AuthProtocolState.SUCCESS);
+ }
+ authState.update(authScheme, creds);
+ } else {
+ this.log.debug("No credentials for preemptive authentication");
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestAuthenticationBase.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestAuthenticationBase.java
new file mode 100644
index 000000000..19e07054b
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestAuthenticationBase.java
@@ -0,0 +1,126 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.protocol;
+
+import java.util.Queue;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpRequestInterceptor;
+import ch.boye.httpclientandroidlib.auth.AuthOption;
+import ch.boye.httpclientandroidlib.auth.AuthScheme;
+import ch.boye.httpclientandroidlib.auth.AuthState;
+import ch.boye.httpclientandroidlib.auth.AuthenticationException;
+import ch.boye.httpclientandroidlib.auth.ContextAwareAuthScheme;
+import ch.boye.httpclientandroidlib.auth.Credentials;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Asserts;
+
+@Deprecated
+abstract class RequestAuthenticationBase implements HttpRequestInterceptor {
+
+ final HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ public RequestAuthenticationBase() {
+ super();
+ }
+
+ void process(
+ final AuthState authState,
+ final HttpRequest request,
+ final HttpContext context) {
+ AuthScheme authScheme = authState.getAuthScheme();
+ Credentials creds = authState.getCredentials();
+ switch (authState.getState()) {
+ case FAILURE:
+ return;
+ case SUCCESS:
+ ensureAuthScheme(authScheme);
+ if (authScheme.isConnectionBased()) {
+ return;
+ }
+ break;
+ case CHALLENGED:
+ final Queue authOptions = authState.getAuthOptions();
+ if (authOptions != null) {
+ while (!authOptions.isEmpty()) {
+ final AuthOption authOption = authOptions.remove();
+ authScheme = authOption.getAuthScheme();
+ creds = authOption.getCredentials();
+ authState.update(authScheme, creds);
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Generating response to an authentication challenge using "
+ + authScheme.getSchemeName() + " scheme");
+ }
+ try {
+ final Header header = authenticate(authScheme, creds, request, context);
+ request.addHeader(header);
+ break;
+ } catch (final AuthenticationException ex) {
+ if (this.log.isWarnEnabled()) {
+ this.log.warn(authScheme + " authentication error: " + ex.getMessage());
+ }
+ }
+ }
+ return;
+ } else {
+ ensureAuthScheme(authScheme);
+ }
+ }
+ if (authScheme != null) {
+ try {
+ final Header header = authenticate(authScheme, creds, request, context);
+ request.addHeader(header);
+ } catch (final AuthenticationException ex) {
+ if (this.log.isErrorEnabled()) {
+ this.log.error(authScheme + " authentication error: " + ex.getMessage());
+ }
+ }
+ }
+ }
+
+ private void ensureAuthScheme(final AuthScheme authScheme) {
+ Asserts.notNull(authScheme, "Auth scheme");
+ }
+
+ private Header authenticate(
+ final AuthScheme authScheme,
+ final Credentials creds,
+ final HttpRequest request,
+ final HttpContext context) throws AuthenticationException {
+ Asserts.notNull(authScheme, "Auth scheme");
+ if (authScheme instanceof ContextAwareAuthScheme) {
+ return ((ContextAwareAuthScheme) authScheme).authenticate(creds, request, context);
+ } else {
+ return authScheme.authenticate(creds, request);
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestClientConnControl.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestClientConnControl.java
new file mode 100644
index 000000000..714b2859b
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestClientConnControl.java
@@ -0,0 +1,92 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.protocol;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpRequestInterceptor;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.conn.routing.RouteInfo;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * This protocol interceptor is responsible for adding Connection
+ * or Proxy-Connection headers to the outgoing requests, which
+ * is essential for managing persistence of HTTP/1.0 connections.
+ *
+ * @since 4.0
+ */
+@Immutable
+public class RequestClientConnControl implements HttpRequestInterceptor {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ private static final String PROXY_CONN_DIRECTIVE = "Proxy-Connection";
+
+ public RequestClientConnControl() {
+ super();
+ }
+
+ public void process(final HttpRequest request, final HttpContext context)
+ throws HttpException, IOException {
+ Args.notNull(request, "HTTP request");
+
+ final String method = request.getRequestLine().getMethod();
+ if (method.equalsIgnoreCase("CONNECT")) {
+ request.setHeader(PROXY_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
+ return;
+ }
+
+ final HttpClientContext clientContext = HttpClientContext.adapt(context);
+
+ // Obtain the client connection (required)
+ final RouteInfo route = clientContext.getHttpRoute();
+ if (route == null) {
+ this.log.debug("Connection route not set in the context");
+ return;
+ }
+
+ if (route.getHopCount() == 1 || route.isTunnelled()) {
+ if (!request.containsHeader(HTTP.CONN_DIRECTIVE)) {
+ request.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
+ }
+ }
+ if (route.getHopCount() == 2 && !route.isTunnelled()) {
+ if (!request.containsHeader(PROXY_CONN_DIRECTIVE)) {
+ request.addHeader(PROXY_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
+ }
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestDefaultHeaders.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestDefaultHeaders.java
new file mode 100644
index 000000000..c4414f1f4
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestDefaultHeaders.java
@@ -0,0 +1,89 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.protocol;
+
+import java.io.IOException;
+import java.util.Collection;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpRequestInterceptor;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.params.ClientPNames;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Request interceptor that adds default request headers.
+ *
+ * @since 4.0
+ */
+@SuppressWarnings("deprecation")
+@Immutable
+public class RequestDefaultHeaders implements HttpRequestInterceptor {
+
+ private final Collection extends Header> defaultHeaders;
+
+ /**
+ * @since 4.3
+ */
+ public RequestDefaultHeaders(final Collection extends Header> defaultHeaders) {
+ super();
+ this.defaultHeaders = defaultHeaders;
+ }
+
+ public RequestDefaultHeaders() {
+ this(null);
+ }
+
+ public void process(final HttpRequest request, final HttpContext context)
+ throws HttpException, IOException {
+ Args.notNull(request, "HTTP request");
+
+ final String method = request.getRequestLine().getMethod();
+ if (method.equalsIgnoreCase("CONNECT")) {
+ return;
+ }
+
+ // Add default headers
+ @SuppressWarnings("unchecked")
+ Collection extends Header> defHeaders = (Collection extends Header>)
+ request.getParams().getParameter(ClientPNames.DEFAULT_HEADERS);
+ if (defHeaders == null) {
+ defHeaders = this.defaultHeaders;
+ }
+
+ if (defHeaders != null) {
+ for (final Header defHeader : defHeaders) {
+ request.addHeader(defHeader);
+ }
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestExpectContinue.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestExpectContinue.java
new file mode 100644
index 000000000..237004f0f
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestExpectContinue.java
@@ -0,0 +1,82 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.protocol;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpRequestInterceptor;
+import ch.boye.httpclientandroidlib.HttpVersion;
+import ch.boye.httpclientandroidlib.ProtocolVersion;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.config.RequestConfig;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * RequestExpectContinue is responsible for enabling the 'expect-continue'
+ * handshake by adding Expect header.
+ *
+ * This interceptor takes into account {@link RequestConfig#isExpectContinueEnabled()}
+ * setting.
+ *
+ * @since 4.3
+ */
+@Immutable
+public class RequestExpectContinue implements HttpRequestInterceptor {
+
+ public RequestExpectContinue() {
+ super();
+ }
+
+ public void process(final HttpRequest request, final HttpContext context)
+ throws HttpException, IOException {
+ Args.notNull(request, "HTTP request");
+
+ if (!request.containsHeader(HTTP.EXPECT_DIRECTIVE)) {
+ if (request instanceof HttpEntityEnclosingRequest) {
+ final ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
+ final HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
+ // Do not send the expect header if request body is known to be empty
+ if (entity != null
+ && entity.getContentLength() != 0 && !ver.lessEquals(HttpVersion.HTTP_1_0)) {
+ final HttpClientContext clientContext = HttpClientContext.adapt(context);
+ final RequestConfig config = clientContext.getRequestConfig();
+ if (config.isExpectContinueEnabled()) {
+ request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE);
+ }
+ }
+ }
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestProxyAuthentication.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestProxyAuthentication.java
new file mode 100644
index 000000000..e67468ff8
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestProxyAuthentication.java
@@ -0,0 +1,92 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.protocol;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.auth.AUTH;
+import ch.boye.httpclientandroidlib.auth.AuthState;
+import ch.boye.httpclientandroidlib.conn.HttpRoutedConnection;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.protocol.ExecutionContext;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Generates authentication header for the proxy host, if required,
+ * based on the actual state of the HTTP authentication context.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link ch.boye.httpclientandroidlib.impl.auth.HttpAuthenticator}.
+ */
+@Deprecated
+@Immutable
+public class RequestProxyAuthentication extends RequestAuthenticationBase {
+
+ public RequestProxyAuthentication() {
+ super();
+ }
+
+ public void process(final HttpRequest request, final HttpContext context)
+ throws HttpException, IOException {
+ Args.notNull(request, "HTTP request");
+ Args.notNull(context, "HTTP context");
+
+ if (request.containsHeader(AUTH.PROXY_AUTH_RESP)) {
+ return;
+ }
+
+ final HttpRoutedConnection conn = (HttpRoutedConnection) context.getAttribute(
+ ExecutionContext.HTTP_CONNECTION);
+ if (conn == null) {
+ this.log.debug("HTTP connection not set in the context");
+ return;
+ }
+ final HttpRoute route = conn.getRoute();
+ if (route.isTunnelled()) {
+ return;
+ }
+
+ // Obtain authentication state
+ final AuthState authState = (AuthState) context.getAttribute(
+ ClientContext.PROXY_AUTH_STATE);
+ if (authState == null) {
+ this.log.debug("Proxy auth state not set in the context");
+ return;
+ }
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Proxy auth state: " + authState.getState());
+ }
+ process(authState, request, context);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestTargetAuthentication.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestTargetAuthentication.java
new file mode 100644
index 000000000..dd5c52597
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/RequestTargetAuthentication.java
@@ -0,0 +1,83 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.protocol;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.auth.AUTH;
+import ch.boye.httpclientandroidlib.auth.AuthState;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Generates authentication header for the target host, if required,
+ * based on the actual state of the HTTP authentication context.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link ch.boye.httpclientandroidlib.impl.auth.HttpAuthenticator}.
+ */
+@Deprecated
+@Immutable
+public class RequestTargetAuthentication extends RequestAuthenticationBase {
+
+ public RequestTargetAuthentication() {
+ super();
+ }
+
+ public void process(final HttpRequest request, final HttpContext context)
+ throws HttpException, IOException {
+ Args.notNull(request, "HTTP request");
+ Args.notNull(context, "HTTP context");
+
+ final String method = request.getRequestLine().getMethod();
+ if (method.equalsIgnoreCase("CONNECT")) {
+ return;
+ }
+
+ if (request.containsHeader(AUTH.WWW_AUTH_RESP)) {
+ return;
+ }
+
+ // Obtain authentication state
+ final AuthState authState = (AuthState) context.getAttribute(
+ ClientContext.TARGET_AUTH_STATE);
+ if (authState == null) {
+ this.log.debug("Target auth state not set in the context");
+ return;
+ }
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Target auth state: " + authState.getState());
+ }
+ process(authState, request, context);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/ResponseAuthCache.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/ResponseAuthCache.java
new file mode 100644
index 000000000..fc51012f6
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/ResponseAuthCache.java
@@ -0,0 +1,151 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.protocol;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpResponseInterceptor;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.auth.AuthScheme;
+import ch.boye.httpclientandroidlib.auth.AuthState;
+import ch.boye.httpclientandroidlib.client.AuthCache;
+import ch.boye.httpclientandroidlib.client.params.AuthPolicy;
+import ch.boye.httpclientandroidlib.conn.scheme.Scheme;
+import ch.boye.httpclientandroidlib.conn.scheme.SchemeRegistry;
+import ch.boye.httpclientandroidlib.impl.client.BasicAuthCache;
+import ch.boye.httpclientandroidlib.protocol.ExecutionContext;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Response interceptor that adds successfully completed {@link AuthScheme}s
+ * to the local {@link AuthCache} instance. Cached {@link AuthScheme}s can be
+ * re-used when executing requests against known hosts, thus avoiding
+ * additional authentication round-trips.
+ *
+ * @since 4.1
+ *
+ * @deprecated (4.2) use {@link ch.boye.httpclientandroidlib.client.AuthenticationStrategy}
+ */
+@Immutable
+@Deprecated
+public class ResponseAuthCache implements HttpResponseInterceptor {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ public ResponseAuthCache() {
+ super();
+ }
+
+ public void process(final HttpResponse response, final HttpContext context)
+ throws HttpException, IOException {
+ Args.notNull(response, "HTTP request");
+ Args.notNull(context, "HTTP context");
+ AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);
+
+ HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
+ final AuthState targetState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
+ if (target != null && targetState != null) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Target auth state: " + targetState.getState());
+ }
+ if (isCachable(targetState)) {
+ final SchemeRegistry schemeRegistry = (SchemeRegistry) context.getAttribute(
+ ClientContext.SCHEME_REGISTRY);
+ if (target.getPort() < 0) {
+ final Scheme scheme = schemeRegistry.getScheme(target);
+ target = new HttpHost(target.getHostName(),
+ scheme.resolvePort(target.getPort()), target.getSchemeName());
+ }
+ if (authCache == null) {
+ authCache = new BasicAuthCache();
+ context.setAttribute(ClientContext.AUTH_CACHE, authCache);
+ }
+ switch (targetState.getState()) {
+ case CHALLENGED:
+ cache(authCache, target, targetState.getAuthScheme());
+ break;
+ case FAILURE:
+ uncache(authCache, target, targetState.getAuthScheme());
+ }
+ }
+ }
+
+ final HttpHost proxy = (HttpHost) context.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
+ final AuthState proxyState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE);
+ if (proxy != null && proxyState != null) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Proxy auth state: " + proxyState.getState());
+ }
+ if (isCachable(proxyState)) {
+ if (authCache == null) {
+ authCache = new BasicAuthCache();
+ context.setAttribute(ClientContext.AUTH_CACHE, authCache);
+ }
+ switch (proxyState.getState()) {
+ case CHALLENGED:
+ cache(authCache, proxy, proxyState.getAuthScheme());
+ break;
+ case FAILURE:
+ uncache(authCache, proxy, proxyState.getAuthScheme());
+ }
+ }
+ }
+ }
+
+ private boolean isCachable(final AuthState authState) {
+ final AuthScheme authScheme = authState.getAuthScheme();
+ if (authScheme == null || !authScheme.isComplete()) {
+ return false;
+ }
+ final String schemeName = authScheme.getSchemeName();
+ return schemeName.equalsIgnoreCase(AuthPolicy.BASIC) ||
+ schemeName.equalsIgnoreCase(AuthPolicy.DIGEST);
+ }
+
+ private void cache(final AuthCache authCache, final HttpHost host, final AuthScheme authScheme) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Caching '" + authScheme.getSchemeName() +
+ "' auth scheme for " + host);
+ }
+ authCache.put(host, authScheme);
+ }
+
+ private void uncache(final AuthCache authCache, final HttpHost host, final AuthScheme authScheme) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Removing from cache '" + authScheme.getSchemeName() +
+ "' auth scheme for " + host);
+ }
+ authCache.remove(host);
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/ResponseContentEncoding.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/ResponseContentEncoding.java
new file mode 100644
index 000000000..df3ee4457
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/ResponseContentEncoding.java
@@ -0,0 +1,110 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.client.protocol;
+
+import java.io.IOException;
+import java.util.Locale;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HeaderElement;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpResponseInterceptor;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.entity.DeflateDecompressingEntity;
+import ch.boye.httpclientandroidlib.client.entity.GzipDecompressingEntity;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+/**
+ * {@link HttpResponseInterceptor} responsible for processing Content-Encoding
+ * responses.
+ *
+ * Instances of this class are stateless and immutable, therefore threadsafe.
+ *
+ * @since 4.1
+ *
+ */
+@Immutable
+public class ResponseContentEncoding implements HttpResponseInterceptor {
+
+ public static final String UNCOMPRESSED = "http.client.response.uncompressed";
+
+ /**
+ * Handles the following {@code Content-Encoding}s by
+ * using the appropriate decompressor to wrap the response Entity:
+ *
+ *
gzip - see {@link GzipDecompressingEntity}
+ *
deflate - see {@link DeflateDecompressingEntity}
+ *
identity - no action needed
+ *
+ *
+ * @param response the response which contains the entity
+ * @param context not currently used
+ *
+ * @throws HttpException if the {@code Content-Encoding} is none of the above
+ */
+ public void process(
+ final HttpResponse response,
+ final HttpContext context) throws HttpException, IOException {
+ final HttpEntity entity = response.getEntity();
+
+ // entity can be null in case of 304 Not Modified, 204 No Content or similar
+ // check for zero length entity.
+ if (entity != null && entity.getContentLength() != 0) {
+ final Header ceheader = entity.getContentEncoding();
+ if (ceheader != null) {
+ final HeaderElement[] codecs = ceheader.getElements();
+ boolean uncompressed = false;
+ for (final HeaderElement codec : codecs) {
+ final String codecname = codec.getName().toLowerCase(Locale.ENGLISH);
+ if ("gzip".equals(codecname) || "x-gzip".equals(codecname)) {
+ response.setEntity(new GzipDecompressingEntity(response.getEntity()));
+ uncompressed = true;
+ break;
+ } else if ("deflate".equals(codecname)) {
+ response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
+ uncompressed = true;
+ break;
+ } else if ("identity".equals(codecname)) {
+
+ /* Don't need to transform the content - no-op */
+ return;
+ } else {
+ throw new HttpException("Unsupported Content-Coding: " + codec.getName());
+ }
+ }
+ if (uncompressed) {
+ response.removeHeaders("Content-Length");
+ response.removeHeaders("Content-Encoding");
+ response.removeHeaders("Content-MD5");
+ }
+ }
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/ResponseProcessCookies.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/ResponseProcessCookies.java
new file mode 100644
index 000000000..06827bfdc
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/ResponseProcessCookies.java
@@ -0,0 +1,156 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.protocol;
+
+import java.io.IOException;
+import java.util.List;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HeaderIterator;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpResponseInterceptor;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.CookieStore;
+import ch.boye.httpclientandroidlib.cookie.Cookie;
+import ch.boye.httpclientandroidlib.cookie.CookieOrigin;
+import ch.boye.httpclientandroidlib.cookie.CookieSpec;
+import ch.boye.httpclientandroidlib.cookie.MalformedCookieException;
+import ch.boye.httpclientandroidlib.cookie.SM;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Response interceptor that populates the current {@link CookieStore} with data
+ * contained in response cookies received in the given the HTTP response.
+ *
+ * @since 4.0
+ */
+@Immutable
+public class ResponseProcessCookies implements HttpResponseInterceptor {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ public ResponseProcessCookies() {
+ super();
+ }
+
+ public void process(final HttpResponse response, final HttpContext context)
+ throws HttpException, IOException {
+ Args.notNull(response, "HTTP request");
+ Args.notNull(context, "HTTP context");
+
+ final HttpClientContext clientContext = HttpClientContext.adapt(context);
+
+ // Obtain actual CookieSpec instance
+ final CookieSpec cookieSpec = clientContext.getCookieSpec();
+ if (cookieSpec == null) {
+ this.log.debug("Cookie spec not specified in HTTP context");
+ return;
+ }
+ // Obtain cookie store
+ final CookieStore cookieStore = clientContext.getCookieStore();
+ if (cookieStore == null) {
+ this.log.debug("Cookie store not specified in HTTP context");
+ return;
+ }
+ // Obtain actual CookieOrigin instance
+ final CookieOrigin cookieOrigin = clientContext.getCookieOrigin();
+ if (cookieOrigin == null) {
+ this.log.debug("Cookie origin not specified in HTTP context");
+ return;
+ }
+ HeaderIterator it = response.headerIterator(SM.SET_COOKIE);
+ processCookies(it, cookieSpec, cookieOrigin, cookieStore);
+
+ // see if the cookie spec supports cookie versioning.
+ if (cookieSpec.getVersion() > 0) {
+ // process set-cookie2 headers.
+ // Cookie2 will replace equivalent Cookie instances
+ it = response.headerIterator(SM.SET_COOKIE2);
+ processCookies(it, cookieSpec, cookieOrigin, cookieStore);
+ }
+ }
+
+ private void processCookies(
+ final HeaderIterator iterator,
+ final CookieSpec cookieSpec,
+ final CookieOrigin cookieOrigin,
+ final CookieStore cookieStore) {
+ while (iterator.hasNext()) {
+ final Header header = iterator.nextHeader();
+ try {
+ final List cookies = cookieSpec.parse(header, cookieOrigin);
+ for (final Cookie cookie : cookies) {
+ try {
+ cookieSpec.validate(cookie, cookieOrigin);
+ cookieStore.addCookie(cookie);
+
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Cookie accepted [" + formatCooke(cookie) + "]");
+ }
+ } catch (final MalformedCookieException ex) {
+ if (this.log.isWarnEnabled()) {
+ this.log.warn("Cookie rejected [" + formatCooke(cookie) + "] "
+ + ex.getMessage());
+ }
+ }
+ }
+ } catch (final MalformedCookieException ex) {
+ if (this.log.isWarnEnabled()) {
+ this.log.warn("Invalid cookie header: \""
+ + header + "\". " + ex.getMessage());
+ }
+ }
+ }
+ }
+
+ private static String formatCooke(final Cookie cookie) {
+ final StringBuilder buf = new StringBuilder();
+ buf.append(cookie.getName());
+ buf.append("=\"");
+ String v = cookie.getValue();
+ if (v.length() > 100) {
+ v = v.substring(0, 100) + "...";
+ }
+ buf.append(v);
+ buf.append("\"");
+ buf.append(", version:");
+ buf.append(Integer.toString(cookie.getVersion()));
+ buf.append(", domain:");
+ buf.append(cookie.getDomain());
+ buf.append(", path:");
+ buf.append(cookie.getPath());
+ buf.append(", expiry:");
+ buf.append(cookie.getExpiryDate());
+ return buf.toString();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/package-info.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/package-info.java
new file mode 100644
index 000000000..a585e614d
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/protocol/package-info.java
@@ -0,0 +1,31 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+/**
+ * Client specific HTTP protocol handlers.
+ */
+package ch.boye.httpclientandroidlib.client.protocol;
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/utils/CloneUtils.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/utils/CloneUtils.java
new file mode 100644
index 000000000..67f70ee07
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/utils/CloneUtils.java
@@ -0,0 +1,86 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.client.utils;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+
+/**
+ * A collection of utilities to workaround limitations of Java clone framework.
+ *
+ * @since 4.0
+ */
+@Immutable
+public class CloneUtils {
+
+ /**
+ * @since 4.3
+ */
+ public static T cloneObject(final T obj) throws CloneNotSupportedException {
+ if (obj == null) {
+ return null;
+ }
+ if (obj instanceof Cloneable) {
+ final Class> clazz = obj.getClass ();
+ final Method m;
+ try {
+ m = clazz.getMethod("clone", (Class[]) null);
+ } catch (final NoSuchMethodException ex) {
+ throw new NoSuchMethodError(ex.getMessage());
+ }
+ try {
+ @SuppressWarnings("unchecked") // OK because clone() preserves the class
+ final T result = (T) m.invoke(obj, (Object []) null);
+ return result;
+ } catch (final InvocationTargetException ex) {
+ final Throwable cause = ex.getCause();
+ if (cause instanceof CloneNotSupportedException) {
+ throw ((CloneNotSupportedException) cause);
+ } else {
+ throw new Error("Unexpected exception", cause);
+ }
+ } catch (final IllegalAccessException ex) {
+ throw new IllegalAccessError(ex.getMessage());
+ }
+ } else {
+ throw new CloneNotSupportedException();
+ }
+ }
+
+ public static Object clone(final Object obj) throws CloneNotSupportedException {
+ return cloneObject(obj);
+ }
+
+ /**
+ * This class should not be instantiated.
+ */
+ private CloneUtils() {
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/utils/DateUtils.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/utils/DateUtils.java
new file mode 100644
index 000000000..e337923d3
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/utils/DateUtils.java
@@ -0,0 +1,250 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.client.utils;
+
+import java.lang.ref.SoftReference;
+import java.text.ParsePosition;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.TimeZone;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * A utility class for parsing and formatting HTTP dates as used in cookies and
+ * other headers. This class handles dates as defined by RFC 2616 section
+ * 3.3.1 as well as some other common non-standard formats.
+ *
+ * @since 4.3
+ */
+@Immutable
+public final class DateUtils {
+
+ /**
+ * Date format pattern used to parse HTTP date headers in RFC 1123 format.
+ */
+ public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
+
+ /**
+ * Date format pattern used to parse HTTP date headers in RFC 1036 format.
+ */
+ public static final String PATTERN_RFC1036 = "EEE, dd-MMM-yy HH:mm:ss zzz";
+
+ /**
+ * Date format pattern used to parse HTTP date headers in ANSI C
+ * asctime() format.
+ */
+ public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";
+
+ private static final String[] DEFAULT_PATTERNS = new String[] {
+ PATTERN_RFC1123,
+ PATTERN_RFC1036,
+ PATTERN_ASCTIME
+ };
+
+ private static final Date DEFAULT_TWO_DIGIT_YEAR_START;
+
+ public static final TimeZone GMT = TimeZone.getTimeZone("GMT");
+
+ static {
+ final Calendar calendar = Calendar.getInstance();
+ calendar.setTimeZone(GMT);
+ calendar.set(2000, Calendar.JANUARY, 1, 0, 0, 0);
+ calendar.set(Calendar.MILLISECOND, 0);
+ DEFAULT_TWO_DIGIT_YEAR_START = calendar.getTime();
+ }
+
+ /**
+ * Parses a date value. The formats used for parsing the date value are retrieved from
+ * the default http params.
+ *
+ * @param dateValue the date value to parse
+ *
+ * @return the parsed date or null if input could not be parsed
+ */
+ public static Date parseDate(final String dateValue) {
+ return parseDate(dateValue, null, null);
+ }
+
+ /**
+ * Parses the date value using the given date formats.
+ *
+ * @param dateValue the date value to parse
+ * @param dateFormats the date formats to use
+ *
+ * @return the parsed date or null if input could not be parsed
+ */
+ public static Date parseDate(final String dateValue, final String[] dateFormats) {
+ return parseDate(dateValue, dateFormats, null);
+ }
+
+ /**
+ * Parses the date value using the given date formats.
+ *
+ * @param dateValue the date value to parse
+ * @param dateFormats the date formats to use
+ * @param startDate During parsing, two digit years will be placed in the range
+ * startDate to startDate + 100 years. This value may
+ * be null. When null is given as a parameter, year
+ * 2000 will be used.
+ *
+ * @return the parsed date or null if input could not be parsed
+ */
+ public static Date parseDate(
+ final String dateValue,
+ final String[] dateFormats,
+ final Date startDate) {
+ Args.notNull(dateValue, "Date value");
+ final String[] localDateFormats = dateFormats != null ? dateFormats : DEFAULT_PATTERNS;
+ final Date localStartDate = startDate != null ? startDate : DEFAULT_TWO_DIGIT_YEAR_START;
+ String v = dateValue;
+ // trim single quotes around date if present
+ // see issue #5279
+ if (v.length() > 1 && v.startsWith("'") && v.endsWith("'")) {
+ v = v.substring (1, v.length() - 1);
+ }
+
+ for (final String dateFormat : localDateFormats) {
+ final SimpleDateFormat dateParser = DateFormatHolder.formatFor(dateFormat);
+ dateParser.set2DigitYearStart(localStartDate);
+ final ParsePosition pos = new ParsePosition(0);
+ final Date result = dateParser.parse(v, pos);
+ if (pos.getIndex() != 0) {
+ return result;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Formats the given date according to the RFC 1123 pattern.
+ *
+ * @param date The date to format.
+ * @return An RFC 1123 formatted date string.
+ *
+ * @see #PATTERN_RFC1123
+ */
+ public static String formatDate(final Date date) {
+ return formatDate(date, PATTERN_RFC1123);
+ }
+
+ /**
+ * Formats the given date according to the specified pattern. The pattern
+ * must conform to that used by the {@link SimpleDateFormat simple date
+ * format} class.
+ *
+ * @param date The date to format.
+ * @param pattern The pattern to use for formatting the date.
+ * @return A formatted date string.
+ *
+ * @throws IllegalArgumentException If the given date pattern is invalid.
+ *
+ * @see SimpleDateFormat
+ */
+ public static String formatDate(final Date date, final String pattern) {
+ Args.notNull(date, "Date");
+ Args.notNull(pattern, "Pattern");
+ final SimpleDateFormat formatter = DateFormatHolder.formatFor(pattern);
+ return formatter.format(date);
+ }
+
+ /**
+ * Clears thread-local variable containing {@link java.text.DateFormat} cache.
+ *
+ * @since 4.3
+ */
+ public static void clearThreadLocal() {
+ DateFormatHolder.clearThreadLocal();
+ }
+
+ /** This class should not be instantiated. */
+ private DateUtils() {
+ }
+
+ /**
+ * A factory for {@link SimpleDateFormat}s. The instances are stored in a
+ * threadlocal way because SimpleDateFormat is not threadsafe as noted in
+ * {@link SimpleDateFormat its javadoc}.
+ *
+ */
+ final static class DateFormatHolder {
+
+ private static final ThreadLocal>>
+ THREADLOCAL_FORMATS = new ThreadLocal>>() {
+
+ @Override
+ protected SoftReference
+ *
+ *
+ *
+ * @since 4.0
+ */
+@ThreadSafe
+public class SSLConnectionSocketFactory implements LayeredConnectionSocketFactory {
+
+ public static final String TLS = "TLS";
+ public static final String SSL = "SSL";
+ public static final String SSLV2 = "SSLv2";
+
+ public static final X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER
+ = new AllowAllHostnameVerifier();
+
+ public static final X509HostnameVerifier BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
+ = new BrowserCompatHostnameVerifier();
+
+ public static final X509HostnameVerifier STRICT_HOSTNAME_VERIFIER
+ = new StrictHostnameVerifier();
+
+ /**
+ * Obtains default SSL socket factory with an SSL context based on the standard JSSE
+ * trust material (cacerts file in the security properties directory).
+ * System properties are not taken into consideration.
+ *
+ * @return default SSL socket factory
+ */
+ public static SSLConnectionSocketFactory getSocketFactory() throws SSLInitializationException {
+ return new SSLConnectionSocketFactory(
+ SSLContexts.createDefault(),
+ BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
+ }
+
+ private static String[] split(final String s) {
+ if (TextUtils.isBlank(s)) {
+ return null;
+ }
+ return s.split(" *, *");
+ }
+
+ /**
+ * Obtains default SSL socket factory with an SSL context based on system properties
+ * as described in
+ *
+ * "JavaTM Secure Socket Extension (JSSE) Reference Guide for the JavaTM 2 Platform
+ * Standard Edition 5
+ *
+ * @return default system SSL socket factory
+ */
+ public static SSLConnectionSocketFactory getSystemSocketFactory() throws SSLInitializationException {
+ return new SSLConnectionSocketFactory(
+ (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory.getDefault(),
+ split(System.getProperty("https.protocols")),
+ split(System.getProperty("https.cipherSuites")),
+ BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
+ }
+
+ private final javax.net.ssl.SSLSocketFactory socketfactory;
+ private final X509HostnameVerifier hostnameVerifier;
+ private final String[] supportedProtocols;
+ private final String[] supportedCipherSuites;
+
+ public SSLConnectionSocketFactory(final SSLContext sslContext) {
+ this(sslContext, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
+ }
+
+ public SSLConnectionSocketFactory(
+ final SSLContext sslContext, final X509HostnameVerifier hostnameVerifier) {
+ this(Args.notNull(sslContext, "SSL context").getSocketFactory(),
+ null, null, hostnameVerifier);
+ }
+
+ public SSLConnectionSocketFactory(
+ final SSLContext sslContext,
+ final String[] supportedProtocols,
+ final String[] supportedCipherSuites,
+ final X509HostnameVerifier hostnameVerifier) {
+ this(Args.notNull(sslContext, "SSL context").getSocketFactory(),
+ supportedProtocols, supportedCipherSuites, hostnameVerifier);
+ }
+
+ public SSLConnectionSocketFactory(
+ final javax.net.ssl.SSLSocketFactory socketfactory,
+ final X509HostnameVerifier hostnameVerifier) {
+ this(socketfactory, null, null, hostnameVerifier);
+ }
+
+ public SSLConnectionSocketFactory(
+ final javax.net.ssl.SSLSocketFactory socketfactory,
+ final String[] supportedProtocols,
+ final String[] supportedCipherSuites,
+ final X509HostnameVerifier hostnameVerifier) {
+ this.socketfactory = Args.notNull(socketfactory, "SSL socket factory");
+ this.supportedProtocols = supportedProtocols;
+ this.supportedCipherSuites = supportedCipherSuites;
+ this.hostnameVerifier = hostnameVerifier != null ? hostnameVerifier : BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
+ }
+
+ /**
+ * Performs any custom initialization for a newly created SSLSocket
+ * (before the SSL handshake happens).
+ *
+ * The default implementation is a no-op, but could be overridden to, e.g.,
+ * call {@link javax.net.ssl.SSLSocket#setEnabledCipherSuites(String[])}.
+ */
+ protected void prepareSocket(final SSLSocket socket) throws IOException {
+ }
+
+ public Socket createSocket(final HttpContext context) throws IOException {
+ return SocketFactory.getDefault().createSocket();
+ }
+
+ public Socket connectSocket(
+ final int connectTimeout,
+ final Socket socket,
+ final HttpHost host,
+ final InetSocketAddress remoteAddress,
+ final InetSocketAddress localAddress,
+ final HttpContext context) throws IOException {
+ Args.notNull(host, "HTTP host");
+ Args.notNull(remoteAddress, "Remote address");
+ final Socket sock = socket != null ? socket : createSocket(context);
+ if (localAddress != null) {
+ sock.bind(localAddress);
+ }
+ try {
+ sock.connect(remoteAddress, connectTimeout);
+ } catch (final IOException ex) {
+ try {
+ sock.close();
+ } catch (final IOException ignore) {
+ }
+ throw ex;
+ }
+ // Setup SSL layering if necessary
+ if (sock instanceof SSLSocket) {
+ final SSLSocket sslsock = (SSLSocket) sock;
+ sslsock.startHandshake();
+ verifyHostname(sslsock, host.getHostName());
+ return sock;
+ } else {
+ return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
+ }
+ }
+
+ public Socket createLayeredSocket(
+ final Socket socket,
+ final String target,
+ final int port,
+ final HttpContext context) throws IOException {
+ final SSLSocket sslsock = (SSLSocket) this.socketfactory.createSocket(
+ socket,
+ target,
+ port,
+ true);
+ if (supportedProtocols != null) {
+ sslsock.setEnabledProtocols(supportedProtocols);
+ }
+ if (supportedCipherSuites != null) {
+ sslsock.setEnabledCipherSuites(supportedCipherSuites);
+ }
+ prepareSocket(sslsock);
+ sslsock.startHandshake();
+ verifyHostname(sslsock, target);
+ return sslsock;
+ }
+
+ X509HostnameVerifier getHostnameVerifier() {
+ return this.hostnameVerifier;
+ }
+
+ private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
+ try {
+ this.hostnameVerifier.verify(hostname, sslsock);
+ // verifyHostName() didn't blowup - good!
+ } catch (final IOException iox) {
+ // close the socket before re-throwing the exception
+ try { sslsock.close(); } catch (final Exception x) { /*ignore*/ }
+ throw iox;
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/SSLContextBuilder.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/SSLContextBuilder.java
new file mode 100644
index 000000000..89751a166
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/SSLContextBuilder.java
@@ -0,0 +1,259 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.conn.ssl;
+
+import java.net.Socket;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.Principal;
+import java.security.PrivateKey;
+import java.security.SecureRandom;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509KeyManager;
+import javax.net.ssl.X509TrustManager;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+
+/**
+ * Builder for {@link SSLContext} instances.
+ *
+ * @since 4.3
+ */
+@NotThreadSafe
+public class SSLContextBuilder {
+
+ static final String TLS = "TLS";
+ static final String SSL = "SSL";
+
+ private String protocol;
+ private Set keymanagers;
+ private Set trustmanagers;
+ private SecureRandom secureRandom;
+
+ public SSLContextBuilder() {
+ super();
+ this.keymanagers = new HashSet();
+ this.trustmanagers = new HashSet();
+ }
+
+ public SSLContextBuilder useTLS() {
+ this.protocol = TLS;
+ return this;
+ }
+
+ public SSLContextBuilder useSSL() {
+ this.protocol = SSL;
+ return this;
+ }
+
+ public SSLContextBuilder useProtocol(final String protocol) {
+ this.protocol = protocol;
+ return this;
+ }
+
+ public SSLContextBuilder setSecureRandom(final SecureRandom secureRandom) {
+ this.secureRandom = secureRandom;
+ return this;
+ }
+
+ public SSLContextBuilder loadTrustMaterial(
+ final KeyStore truststore,
+ final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException {
+ final TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
+ TrustManagerFactory.getDefaultAlgorithm());
+ tmfactory.init(truststore);
+ final TrustManager[] tms = tmfactory.getTrustManagers();
+ if (tms != null) {
+ if (trustStrategy != null) {
+ for (int i = 0; i < tms.length; i++) {
+ final TrustManager tm = tms[i];
+ if (tm instanceof X509TrustManager) {
+ tms[i] = new TrustManagerDelegate(
+ (X509TrustManager) tm, trustStrategy);
+ }
+ }
+ }
+ for (final TrustManager tm : tms) {
+ this.trustmanagers.add(tm);
+ }
+ }
+ return this;
+ }
+
+ public SSLContextBuilder loadTrustMaterial(
+ final KeyStore truststore) throws NoSuchAlgorithmException, KeyStoreException {
+ return loadTrustMaterial(truststore, null);
+ }
+
+ public SSLContextBuilder loadKeyMaterial(
+ final KeyStore keystore,
+ final char[] keyPassword)
+ throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
+ loadKeyMaterial(keystore, keyPassword, null);
+ return this;
+ }
+
+ public SSLContextBuilder loadKeyMaterial(
+ final KeyStore keystore,
+ final char[] keyPassword,
+ final PrivateKeyStrategy aliasStrategy)
+ throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
+ final KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
+ KeyManagerFactory.getDefaultAlgorithm());
+ kmfactory.init(keystore, keyPassword);
+ final KeyManager[] kms = kmfactory.getKeyManagers();
+ if (kms != null) {
+ if (aliasStrategy != null) {
+ for (int i = 0; i < kms.length; i++) {
+ final KeyManager km = kms[i];
+ if (km instanceof X509KeyManager) {
+ kms[i] = new KeyManagerDelegate(
+ (X509KeyManager) km, aliasStrategy);
+ }
+ }
+ }
+ for (final KeyManager km : kms) {
+ keymanagers.add(km);
+ }
+ }
+ return this;
+ }
+
+ public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException {
+ final SSLContext sslcontext = SSLContext.getInstance(
+ this.protocol != null ? this.protocol : TLS);
+ sslcontext.init(
+ !keymanagers.isEmpty() ? keymanagers.toArray(new KeyManager[keymanagers.size()]) : null,
+ !trustmanagers.isEmpty() ? trustmanagers.toArray(new TrustManager[trustmanagers.size()]) : null,
+ secureRandom);
+ return sslcontext;
+ }
+
+ static class TrustManagerDelegate implements X509TrustManager {
+
+ private final X509TrustManager trustManager;
+ private final TrustStrategy trustStrategy;
+
+ TrustManagerDelegate(final X509TrustManager trustManager, final TrustStrategy trustStrategy) {
+ super();
+ this.trustManager = trustManager;
+ this.trustStrategy = trustStrategy;
+ }
+
+ public void checkClientTrusted(
+ final X509Certificate[] chain, final String authType) throws CertificateException {
+ this.trustManager.checkClientTrusted(chain, authType);
+ }
+
+ public void checkServerTrusted(
+ final X509Certificate[] chain, final String authType) throws CertificateException {
+ if (!this.trustStrategy.isTrusted(chain, authType)) {
+ this.trustManager.checkServerTrusted(chain, authType);
+ }
+ }
+
+ public X509Certificate[] getAcceptedIssuers() {
+ return this.trustManager.getAcceptedIssuers();
+ }
+
+ }
+
+ static class KeyManagerDelegate implements X509KeyManager {
+
+ private final X509KeyManager keyManager;
+ private final PrivateKeyStrategy aliasStrategy;
+
+ KeyManagerDelegate(final X509KeyManager keyManager, final PrivateKeyStrategy aliasStrategy) {
+ super();
+ this.keyManager = keyManager;
+ this.aliasStrategy = aliasStrategy;
+ }
+
+ public String[] getClientAliases(
+ final String keyType, final Principal[] issuers) {
+ return this.keyManager.getClientAliases(keyType, issuers);
+ }
+
+ public String chooseClientAlias(
+ final String[] keyTypes, final Principal[] issuers, final Socket socket) {
+ final Map validAliases = new HashMap();
+ for (final String keyType: keyTypes) {
+ final String[] aliases = this.keyManager.getClientAliases(keyType, issuers);
+ if (aliases != null) {
+ for (final String alias: aliases) {
+ validAliases.put(alias,
+ new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias)));
+ }
+ }
+ }
+ return this.aliasStrategy.chooseAlias(validAliases, socket);
+ }
+
+ public String[] getServerAliases(
+ final String keyType, final Principal[] issuers) {
+ return this.keyManager.getServerAliases(keyType, issuers);
+ }
+
+ public String chooseServerAlias(
+ final String keyType, final Principal[] issuers, final Socket socket) {
+ final Map validAliases = new HashMap();
+ final String[] aliases = this.keyManager.getServerAliases(keyType, issuers);
+ if (aliases != null) {
+ for (final String alias: aliases) {
+ validAliases.put(alias,
+ new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias)));
+ }
+ }
+ return this.aliasStrategy.chooseAlias(validAliases, socket);
+ }
+
+ public X509Certificate[] getCertificateChain(final String alias) {
+ return this.keyManager.getCertificateChain(alias);
+ }
+
+ public PrivateKey getPrivateKey(final String alias) {
+ return this.keyManager.getPrivateKey(alias);
+ }
+
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/SSLContexts.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/SSLContexts.java
new file mode 100644
index 000000000..a87a50168
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/SSLContexts.java
@@ -0,0 +1,90 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.conn.ssl;
+
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+
+import javax.net.ssl.SSLContext;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+
+/**
+ * {@link SSLContext} factory methods.
+ *
+ * @since 4.3
+ */
+@Immutable
+public class SSLContexts {
+
+ /**
+ * Creates default factory based on the standard JSSE trust material
+ * (cacerts file in the security properties directory). System properties
+ * are not taken into consideration.
+ *
+ * @return the default SSL socket factory
+ */
+ public static SSLContext createDefault() throws SSLInitializationException {
+ try {
+ final SSLContext sslcontext = SSLContext.getInstance(SSLContextBuilder.TLS);
+ sslcontext.init(null, null, null);
+ return sslcontext;
+ } catch (final NoSuchAlgorithmException ex) {
+ throw new SSLInitializationException(ex.getMessage(), ex);
+ } catch (final KeyManagementException ex) {
+ throw new SSLInitializationException(ex.getMessage(), ex);
+ }
+ }
+
+ /**
+ * Creates default SSL context based on system properties. This method obtains
+ * default SSL context by calling SSLContext.getInstance("Default").
+ * Please note that Default algorithm is supported as of Java 6.
+ * This method will fall back onto {@link #createDefault()} when
+ * Default algorithm is not available.
+ *
+ * @return default system SSL context
+ */
+ public static SSLContext createSystemDefault() throws SSLInitializationException {
+ try {
+ return SSLContext.getInstance("Default");
+ } catch (final NoSuchAlgorithmException ex) {
+ return createDefault();
+ }
+ }
+
+ /**
+ * Creates custom SSL context.
+ *
+ * @return default system SSL context
+ */
+ public static SSLContextBuilder custom() {
+ return new SSLContextBuilder();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/SSLInitializationException.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/SSLInitializationException.java
new file mode 100644
index 000000000..98cb5f9c3
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/SSLInitializationException.java
@@ -0,0 +1,37 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.conn.ssl;
+
+public class SSLInitializationException extends IllegalStateException {
+
+ private static final long serialVersionUID = -8243587425648536702L;
+
+ public SSLInitializationException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/SSLSocketFactory.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/SSLSocketFactory.java
new file mode 100644
index 000000000..5c514d780
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/SSLSocketFactory.java
@@ -0,0 +1,570 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.conn.ssl;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.net.UnknownHostException;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.UnrecoverableKeyException;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocket;
+
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.conn.ConnectTimeoutException;
+import ch.boye.httpclientandroidlib.conn.HttpInetSocketAddress;
+import ch.boye.httpclientandroidlib.conn.scheme.HostNameResolver;
+import ch.boye.httpclientandroidlib.conn.scheme.LayeredSchemeSocketFactory;
+import ch.boye.httpclientandroidlib.conn.scheme.LayeredSocketFactory;
+import ch.boye.httpclientandroidlib.conn.scheme.SchemeLayeredSocketFactory;
+import ch.boye.httpclientandroidlib.conn.socket.LayeredConnectionSocketFactory;
+import ch.boye.httpclientandroidlib.params.HttpConnectionParams;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.Asserts;
+import ch.boye.httpclientandroidlib.util.TextUtils;
+
+/**
+ * Layered socket factory for TLS/SSL connections.
+ *
+ * SSLSocketFactory can be used to validate the identity of the HTTPS server against a list of
+ * trusted certificates and to authenticate to the HTTPS server using a private key.
+ *
+ * SSLSocketFactory will enable server authentication when supplied with
+ * a {@link KeyStore trust-store} file containing one or several trusted certificates. The client
+ * secure socket will reject the connection during the SSL session handshake if the target HTTPS
+ * server attempts to authenticate itself with a non-trusted certificate.
+ *
+ * Use JDK keytool utility to import a trusted certificate and generate a trust-store file:
+ *
+ * keytool -import -alias "my server cert" -file server.crt -keystore my.truststore
+ *
+ *
+ * In special cases the standard trust verification process can be bypassed by using a custom
+ * {@link TrustStrategy}. This interface is primarily intended for allowing self-signed
+ * certificates to be accepted as trusted without having to add them to the trust-store file.
+ *
+ * SSLSocketFactory will enable client authentication when supplied with
+ * a {@link KeyStore key-store} file containing a private key/public certificate
+ * pair. The client secure socket will use the private key to authenticate
+ * itself to the target HTTPS server during the SSL session handshake if
+ * requested to do so by the server.
+ * The target HTTPS server will in its turn verify the certificate presented
+ * by the client in order to establish client's authenticity.
+ *
+ * Use the following sequence of actions to generate a key-store file
+ *
+ *
+ *
+ *
+ * Use JDK keytool utility to generate a new key
+ *
+ * For simplicity use the same password for the key as that of the key-store
+ *
+ *
+ *
+ *
+ * Issue a certificate signing request (CSR)
+ *
keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore
+ *
+ *
+ *
+ *
+ * Send the certificate request to the trusted Certificate Authority for signature.
+ * One may choose to act as her own CA and sign the certificate request using a PKI
+ * tool, such as OpenSSL.
+ *
+ *
+ *
+ *
+ * Import the trusted CA root certificate
+ *
keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore
+ *
+ *
+ *
+ *
+ * Import the PKCS#7 file containg the complete certificate chain
+ *
keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore
+ *
+ *
+ *
+ *
+ * Verify the content the resultant keystore file
+ *
keytool -list -v -keystore my.keystore
+ *
+ *
+ *
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link SSLConnectionSocketFactory}.
+ */
+@ThreadSafe
+@Deprecated
+public class SSLSocketFactory implements LayeredConnectionSocketFactory, SchemeLayeredSocketFactory,
+ LayeredSchemeSocketFactory, LayeredSocketFactory {
+
+ public static final String TLS = "TLS";
+ public static final String SSL = "SSL";
+ public static final String SSLV2 = "SSLv2";
+
+ public static final X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER
+ = new AllowAllHostnameVerifier();
+
+ public static final X509HostnameVerifier BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
+ = new BrowserCompatHostnameVerifier();
+
+ public static final X509HostnameVerifier STRICT_HOSTNAME_VERIFIER
+ = new StrictHostnameVerifier();
+
+ /**
+ * Obtains default SSL socket factory with an SSL context based on the standard JSSE
+ * trust material (cacerts file in the security properties directory).
+ * System properties are not taken into consideration.
+ *
+ * @return default SSL socket factory
+ */
+ public static SSLSocketFactory getSocketFactory() throws SSLInitializationException {
+ return new SSLSocketFactory(
+ SSLContexts.createDefault(),
+ BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
+ }
+
+ private static String[] split(final String s) {
+ if (TextUtils.isBlank(s)) {
+ return null;
+ }
+ return s.split(" *, *");
+ }
+
+ /**
+ * Obtains default SSL socket factory with an SSL context based on system properties
+ * as described in
+ *
+ * "JavaTM Secure Socket Extension (JSSE) Reference Guide for the JavaTM 2 Platform
+ * Standard Edition 5
+ *
+ * @return default system SSL socket factory
+ */
+ public static SSLSocketFactory getSystemSocketFactory() throws SSLInitializationException {
+ return new SSLSocketFactory(
+ (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory.getDefault(),
+ split(System.getProperty("https.protocols")),
+ split(System.getProperty("https.cipherSuites")),
+ BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
+ }
+
+ private final javax.net.ssl.SSLSocketFactory socketfactory;
+ private final HostNameResolver nameResolver;
+ // TODO: make final
+ private volatile X509HostnameVerifier hostnameVerifier;
+ private final String[] supportedProtocols;
+ private final String[] supportedCipherSuites;
+
+ public SSLSocketFactory(
+ final String algorithm,
+ final KeyStore keystore,
+ final String keyPassword,
+ final KeyStore truststore,
+ final SecureRandom random,
+ final HostNameResolver nameResolver)
+ throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
+ this(SSLContexts.custom()
+ .useProtocol(algorithm)
+ .setSecureRandom(random)
+ .loadKeyMaterial(keystore, keyPassword != null ? keyPassword.toCharArray() : null)
+ .loadTrustMaterial(truststore)
+ .build(),
+ nameResolver);
+ }
+
+ /**
+ * @since 4.1
+ */
+ public SSLSocketFactory(
+ final String algorithm,
+ final KeyStore keystore,
+ final String keyPassword,
+ final KeyStore truststore,
+ final SecureRandom random,
+ final TrustStrategy trustStrategy,
+ final X509HostnameVerifier hostnameVerifier)
+ throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
+ this(SSLContexts.custom()
+ .useProtocol(algorithm)
+ .setSecureRandom(random)
+ .loadKeyMaterial(keystore, keyPassword != null ? keyPassword.toCharArray() : null)
+ .loadTrustMaterial(truststore, trustStrategy)
+ .build(),
+ hostnameVerifier);
+ }
+
+ /**
+ * @since 4.1
+ */
+ public SSLSocketFactory(
+ final String algorithm,
+ final KeyStore keystore,
+ final String keyPassword,
+ final KeyStore truststore,
+ final SecureRandom random,
+ final X509HostnameVerifier hostnameVerifier)
+ throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
+ this(SSLContexts.custom()
+ .useProtocol(algorithm)
+ .setSecureRandom(random)
+ .loadKeyMaterial(keystore, keyPassword != null ? keyPassword.toCharArray() : null)
+ .loadTrustMaterial(truststore)
+ .build(),
+ hostnameVerifier);
+ }
+
+ public SSLSocketFactory(
+ final KeyStore keystore,
+ final String keystorePassword,
+ final KeyStore truststore)
+ throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
+ this(SSLContexts.custom()
+ .loadKeyMaterial(keystore, keystorePassword != null ? keystorePassword.toCharArray() : null)
+ .loadTrustMaterial(truststore)
+ .build(),
+ BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
+ }
+
+ public SSLSocketFactory(
+ final KeyStore keystore,
+ final String keystorePassword)
+ throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException{
+ this(SSLContexts.custom()
+ .loadKeyMaterial(keystore, keystorePassword != null ? keystorePassword.toCharArray() : null)
+ .build(),
+ BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
+ }
+
+ public SSLSocketFactory(
+ final KeyStore truststore)
+ throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
+ this(SSLContexts.custom()
+ .loadTrustMaterial(truststore)
+ .build(),
+ BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
+ }
+
+ /**
+ * @since 4.1
+ */
+ public SSLSocketFactory(
+ final TrustStrategy trustStrategy,
+ final X509HostnameVerifier hostnameVerifier)
+ throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
+ this(SSLContexts.custom()
+ .loadTrustMaterial(null, trustStrategy)
+ .build(),
+ hostnameVerifier);
+ }
+
+ /**
+ * @since 4.1
+ */
+ public SSLSocketFactory(
+ final TrustStrategy trustStrategy)
+ throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
+ this(SSLContexts.custom()
+ .loadTrustMaterial(null, trustStrategy)
+ .build(),
+ BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
+ }
+
+ public SSLSocketFactory(final SSLContext sslContext) {
+ this(sslContext, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
+ }
+
+ public SSLSocketFactory(
+ final SSLContext sslContext, final HostNameResolver nameResolver) {
+ super();
+ this.socketfactory = sslContext.getSocketFactory();
+ this.hostnameVerifier = BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
+ this.nameResolver = nameResolver;
+ this.supportedProtocols = null;
+ this.supportedCipherSuites = null;
+ }
+
+ /**
+ * @since 4.1
+ */
+ public SSLSocketFactory(
+ final SSLContext sslContext, final X509HostnameVerifier hostnameVerifier) {
+ this(Args.notNull(sslContext, "SSL context").getSocketFactory(),
+ null, null, hostnameVerifier);
+ }
+
+ /**
+ * @since 4.3
+ */
+ public SSLSocketFactory(
+ final SSLContext sslContext,
+ final String[] supportedProtocols,
+ final String[] supportedCipherSuites,
+ final X509HostnameVerifier hostnameVerifier) {
+ this(Args.notNull(sslContext, "SSL context").getSocketFactory(),
+ supportedProtocols, supportedCipherSuites, hostnameVerifier);
+ }
+
+ /**
+ * @since 4.2
+ */
+ public SSLSocketFactory(
+ final javax.net.ssl.SSLSocketFactory socketfactory,
+ final X509HostnameVerifier hostnameVerifier) {
+ this(socketfactory, null, null, hostnameVerifier);
+ }
+
+ /**
+ * @since 4.3
+ */
+ public SSLSocketFactory(
+ final javax.net.ssl.SSLSocketFactory socketfactory,
+ final String[] supportedProtocols,
+ final String[] supportedCipherSuites,
+ final X509HostnameVerifier hostnameVerifier) {
+ this.socketfactory = Args.notNull(socketfactory, "SSL socket factory");
+ this.supportedProtocols = supportedProtocols;
+ this.supportedCipherSuites = supportedCipherSuites;
+ this.hostnameVerifier = hostnameVerifier != null ? hostnameVerifier : BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
+ this.nameResolver = null;
+ }
+
+ /**
+ * @param params Optional parameters. Parameters passed to this method will have no effect.
+ * This method will create a unconnected instance of {@link Socket} class.
+ * @since 4.1
+ */
+ public Socket createSocket(final HttpParams params) throws IOException {
+ return createSocket((HttpContext) null);
+ }
+
+ public Socket createSocket() throws IOException {
+ return createSocket((HttpContext) null);
+ }
+
+ /**
+ * @since 4.1
+ */
+ public Socket connectSocket(
+ final Socket socket,
+ final InetSocketAddress remoteAddress,
+ final InetSocketAddress localAddress,
+ final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
+ Args.notNull(remoteAddress, "Remote address");
+ Args.notNull(params, "HTTP parameters");
+ final HttpHost host;
+ if (remoteAddress instanceof HttpInetSocketAddress) {
+ host = ((HttpInetSocketAddress) remoteAddress).getHttpHost();
+ } else {
+ host = new HttpHost(remoteAddress.getHostName(), remoteAddress.getPort(), "https");
+ }
+ final int socketTimeout = HttpConnectionParams.getSoTimeout(params);
+ final int connectTimeout = HttpConnectionParams.getConnectionTimeout(params);
+ socket.setSoTimeout(socketTimeout);
+ return connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, null);
+ }
+
+ /**
+ * Checks whether a socket connection is secure.
+ * This factory creates TLS/SSL socket connections
+ * which, by default, are considered secure.
+ *
+ * Derived classes may override this method to perform
+ * runtime checks, for example based on the cypher suite.
+ *
+ * @param sock the connected socket
+ *
+ * @return true
+ *
+ * @throws IllegalArgumentException if the argument is invalid
+ */
+ public boolean isSecure(final Socket sock) throws IllegalArgumentException {
+ Args.notNull(sock, "Socket");
+ Asserts.check(sock instanceof SSLSocket, "Socket not created by this factory");
+ Asserts.check(!sock.isClosed(), "Socket is closed");
+ return true;
+ }
+
+ /**
+ * @since 4.2
+ */
+ public Socket createLayeredSocket(
+ final Socket socket,
+ final String host,
+ final int port,
+ final HttpParams params) throws IOException, UnknownHostException {
+ return createLayeredSocket(socket, host, port, (HttpContext) null);
+ }
+
+ public Socket createLayeredSocket(
+ final Socket socket,
+ final String host,
+ final int port,
+ final boolean autoClose) throws IOException, UnknownHostException {
+ return createLayeredSocket(socket, host, port, (HttpContext) null);
+ }
+
+ public void setHostnameVerifier(final X509HostnameVerifier hostnameVerifier) {
+ Args.notNull(hostnameVerifier, "Hostname verifier");
+ this.hostnameVerifier = hostnameVerifier;
+ }
+
+ public X509HostnameVerifier getHostnameVerifier() {
+ return this.hostnameVerifier;
+ }
+
+ public Socket connectSocket(
+ final Socket socket,
+ final String host, final int port,
+ final InetAddress local, final int localPort,
+ final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
+ final InetAddress remote;
+ if (this.nameResolver != null) {
+ remote = this.nameResolver.resolve(host);
+ } else {
+ remote = InetAddress.getByName(host);
+ }
+ InetSocketAddress localAddress = null;
+ if (local != null || localPort > 0) {
+ localAddress = new InetSocketAddress(local, localPort > 0 ? localPort : 0);
+ }
+ final InetSocketAddress remoteAddress = new HttpInetSocketAddress(
+ new HttpHost(host, port), remote, port);
+ return connectSocket(socket, remoteAddress, localAddress, params);
+ }
+
+ public Socket createSocket(
+ final Socket socket,
+ final String host, final int port,
+ final boolean autoClose) throws IOException, UnknownHostException {
+ return createLayeredSocket(socket, host, port, autoClose);
+ }
+
+ /**
+ * Performs any custom initialization for a newly created SSLSocket
+ * (before the SSL handshake happens).
+ *
+ * The default implementation is a no-op, but could be overridden to, e.g.,
+ * call {@link SSLSocket#setEnabledCipherSuites(java.lang.String[])}.
+ *
+ * @since 4.2
+ */
+ protected void prepareSocket(final SSLSocket socket) throws IOException {
+ }
+
+ private void internalPrepareSocket(final SSLSocket socket) throws IOException {
+ if (supportedProtocols != null) {
+ socket.setEnabledProtocols(supportedProtocols);
+ }
+ if (supportedCipherSuites != null) {
+ socket.setEnabledCipherSuites(supportedCipherSuites);
+ }
+ prepareSocket(socket);
+ }
+
+ public Socket createSocket(final HttpContext context) throws IOException {
+ final SSLSocket sock = (SSLSocket) this.socketfactory.createSocket();
+ internalPrepareSocket(sock);
+ return sock;
+ }
+
+ public Socket connectSocket(
+ final int connectTimeout,
+ final Socket socket,
+ final HttpHost host,
+ final InetSocketAddress remoteAddress,
+ final InetSocketAddress localAddress,
+ final HttpContext context) throws IOException {
+ Args.notNull(host, "HTTP host");
+ Args.notNull(remoteAddress, "Remote address");
+ final Socket sock = socket != null ? socket : createSocket(context);
+ if (localAddress != null) {
+ sock.bind(localAddress);
+ }
+ try {
+ sock.connect(remoteAddress, connectTimeout);
+ } catch (final IOException ex) {
+ try {
+ sock.close();
+ } catch (final IOException ignore) {
+ }
+ throw ex;
+ }
+ // Setup SSL layering if necessary
+ if (sock instanceof SSLSocket) {
+ final SSLSocket sslsock = (SSLSocket) sock;
+ sslsock.startHandshake();
+ verifyHostname(sslsock, host.getHostName());
+ return sock;
+ } else {
+ return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
+ }
+ }
+
+ public Socket createLayeredSocket(
+ final Socket socket,
+ final String target,
+ final int port,
+ final HttpContext context) throws IOException {
+ final SSLSocket sslsock = (SSLSocket) this.socketfactory.createSocket(
+ socket,
+ target,
+ port,
+ true);
+ internalPrepareSocket(sslsock);
+ sslsock.startHandshake();
+ verifyHostname(sslsock, target);
+ return sslsock;
+ }
+
+ private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
+ try {
+ this.hostnameVerifier.verify(hostname, sslsock);
+ // verifyHostName() didn't blowup - good!
+ } catch (final IOException iox) {
+ // close the socket before re-throwing the exception
+ try { sslsock.close(); } catch (final Exception x) { /*ignore*/ }
+ throw iox;
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/StrictHostnameVerifier.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/StrictHostnameVerifier.java
new file mode 100644
index 000000000..a6328a10c
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/StrictHostnameVerifier.java
@@ -0,0 +1,69 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.conn.ssl;
+
+import javax.net.ssl.SSLException;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+
+/**
+ * The Strict HostnameVerifier works the same way as Sun Java 1.4, Sun
+ * Java 5, Sun Java 6-rc. It's also pretty close to IE6. This
+ * implementation appears to be compliant with RFC 2818 for dealing with
+ * wildcards.
+ *
+ * The hostname must match either the first CN, or any of the subject-alts.
+ * A wildcard can occur in the CN, and in any of the subject-alts. The
+ * one divergence from IE6 is how we only check the first CN. IE6 allows
+ * a match against any of the CNs present. We decided to follow in
+ * Sun Java 1.4's footsteps and only check the first CN. (If you need
+ * to check all the CN's, feel free to write your own implementation!).
+ *
+ * A wildcard such as "*.foo.com" matches only subdomains in the same
+ * level, for example "a.foo.com". It does not match deeper subdomains
+ * such as "a.b.foo.com".
+ *
+ *
+ * @since 4.0
+ */
+@Immutable
+public class StrictHostnameVerifier extends AbstractVerifier {
+
+ public final void verify(
+ final String host,
+ final String[] cns,
+ final String[] subjectAlts) throws SSLException {
+ verify(host, cns, subjectAlts, true);
+ }
+
+ @Override
+ public final String toString() {
+ return "STRICT";
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/TokenParser.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/TokenParser.java
new file mode 100644
index 000000000..25bdcc5e6
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/TokenParser.java
@@ -0,0 +1,266 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.conn.ssl;
+
+import java.util.BitSet;
+
+import ch.boye.httpclientandroidlib.message.ParserCursor;
+import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
+
+/**
+ * Low level parser for header field elements. The parsing routines of this class are designed
+ * to produce near zero intermediate garbage and make no intermediate copies of input data.
+ *
+ * This class is immutable and thread safe.
+ *
+ * Temporary package-private copy of ch.boye.httpclientandroidlib.message.TokenParser
+ */
+class TokenParser {
+
+ public static BitSet INIT_BITSET(final int ... b) {
+ final BitSet bitset = new BitSet();
+ for (final int aB : b) {
+ bitset.set(aB);
+ }
+ return bitset;
+ }
+
+ /** US-ASCII CR, carriage return (13) */
+ public static final char CR = '\r';
+
+ /** US-ASCII LF, line feed (10) */
+ public static final char LF = '\n';
+
+ /** US-ASCII SP, space (32) */
+ public static final char SP = ' ';
+
+ /** US-ASCII HT, horizontal-tab (9) */
+ public static final char HT = '\t';
+
+ /** Double quote */
+ public static final char DQUOTE = '\"';
+
+ /** Backward slash / escape character */
+ public static final char ESCAPE = '\\';
+
+ public static boolean isWhitespace(final char ch) {
+ return ch == SP || ch == HT || ch == CR || ch == LF;
+ }
+
+ public static final TokenParser INSTANCE = new TokenParser();
+
+ /**
+ * Extracts from the sequence of chars a token terminated with any of the given delimiters
+ * discarding semantically insignificant whitespace characters.
+ *
+ * @param buf buffer with the sequence of chars to be parsed
+ * @param cursor defines the bounds and current position of the buffer
+ * @param delimiters set of delimiting characters. Can be null if the token
+ * is not delimited by any character.
+ */
+ public String parseToken(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters) {
+ final StringBuilder dst = new StringBuilder();
+ boolean whitespace = false;
+ while (!cursor.atEnd()) {
+ final char current = buf.charAt(cursor.getPos());
+ if (delimiters != null && delimiters.get(current)) {
+ break;
+ } else if (isWhitespace(current)) {
+ skipWhiteSpace(buf, cursor);
+ whitespace = true;
+ } else {
+ if (whitespace && dst.length() > 0) {
+ dst.append(' ');
+ }
+ copyContent(buf, cursor, delimiters, dst);
+ whitespace = false;
+ }
+ }
+ return dst.toString();
+ }
+
+ /**
+ * Extracts from the sequence of chars a value which can be enclosed in quote marks and
+ * terminated with any of the given delimiters discarding semantically insignificant
+ * whitespace characters.
+ *
+ * @param buf buffer with the sequence of chars to be parsed
+ * @param cursor defines the bounds and current position of the buffer
+ * @param delimiters set of delimiting characters. Can be null if the value
+ * is not delimited by any character.
+ */
+ public String parseValue(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters) {
+ final StringBuilder dst = new StringBuilder();
+ boolean whitespace = false;
+ while (!cursor.atEnd()) {
+ final char current = buf.charAt(cursor.getPos());
+ if (delimiters != null && delimiters.get(current)) {
+ break;
+ } else if (isWhitespace(current)) {
+ skipWhiteSpace(buf, cursor);
+ whitespace = true;
+ } else if (current == DQUOTE) {
+ if (whitespace && dst.length() > 0) {
+ dst.append(' ');
+ }
+ copyQuotedContent(buf, cursor, dst);
+ whitespace = false;
+ } else {
+ if (whitespace && dst.length() > 0) {
+ dst.append(' ');
+ }
+ copyUnquotedContent(buf, cursor, delimiters, dst);
+ whitespace = false;
+ }
+ }
+ return dst.toString();
+ }
+
+ /**
+ * Skips semantically insignificant whitespace characters and moves the cursor to the closest
+ * non-whitespace character.
+ *
+ * @param buf buffer with the sequence of chars to be parsed
+ * @param cursor defines the bounds and current position of the buffer
+ */
+ public void skipWhiteSpace(final CharArrayBuffer buf, final ParserCursor cursor) {
+ int pos = cursor.getPos();
+ final int indexFrom = cursor.getPos();
+ final int indexTo = cursor.getUpperBound();
+ for (int i = indexFrom; i < indexTo; i++) {
+ final char current = buf.charAt(i);
+ if (!isWhitespace(current)) {
+ break;
+ } else {
+ pos++;
+ }
+ }
+ cursor.updatePos(pos);
+ }
+
+ /**
+ * Transfers content into the destination buffer until a whitespace character or any of
+ * the given delimiters is encountered.
+ *
+ * @param buf buffer with the sequence of chars to be parsed
+ * @param cursor defines the bounds and current position of the buffer
+ * @param delimiters set of delimiting characters. Can be null if the value
+ * is delimited by a whitespace only.
+ * @param dst destination buffer
+ */
+ public void copyContent(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters,
+ final StringBuilder dst) {
+ int pos = cursor.getPos();
+ final int indexFrom = cursor.getPos();
+ final int indexTo = cursor.getUpperBound();
+ for (int i = indexFrom; i < indexTo; i++) {
+ final char current = buf.charAt(i);
+ if ((delimiters != null && delimiters.get(current)) || isWhitespace(current)) {
+ break;
+ } else {
+ pos++;
+ dst.append(current);
+ }
+ }
+ cursor.updatePos(pos);
+ }
+
+ /**
+ * Transfers content into the destination buffer until a whitespace character, a quote,
+ * or any of the given delimiters is encountered.
+ *
+ * @param buf buffer with the sequence of chars to be parsed
+ * @param cursor defines the bounds and current position of the buffer
+ * @param delimiters set of delimiting characters. Can be null if the value
+ * is delimited by a whitespace or a quote only.
+ * @param dst destination buffer
+ */
+ public void copyUnquotedContent(final CharArrayBuffer buf, final ParserCursor cursor,
+ final BitSet delimiters, final StringBuilder dst) {
+ int pos = cursor.getPos();
+ final int indexFrom = cursor.getPos();
+ final int indexTo = cursor.getUpperBound();
+ for (int i = indexFrom; i < indexTo; i++) {
+ final char current = buf.charAt(i);
+ if ((delimiters != null && delimiters.get(current))
+ || isWhitespace(current) || current == DQUOTE) {
+ break;
+ } else {
+ pos++;
+ dst.append(current);
+ }
+ }
+ cursor.updatePos(pos);
+ }
+
+ /**
+ * Transfers content enclosed with quote marks into the destination buffer.
+ *
+ * @param buf buffer with the sequence of chars to be parsed
+ * @param cursor defines the bounds and current position of the buffer
+ * @param dst destination buffer
+ */
+ public void copyQuotedContent(final CharArrayBuffer buf, final ParserCursor cursor,
+ final StringBuilder dst) {
+ if (cursor.atEnd()) {
+ return;
+ }
+ int pos = cursor.getPos();
+ int indexFrom = cursor.getPos();
+ final int indexTo = cursor.getUpperBound();
+ char current = buf.charAt(pos);
+ if (current != DQUOTE) {
+ return;
+ }
+ pos++;
+ indexFrom++;
+ boolean escaped = false;
+ for (int i = indexFrom; i < indexTo; i++, pos++) {
+ current = buf.charAt(i);
+ if (escaped) {
+ if (current != DQUOTE && current != ESCAPE) {
+ dst.append(ESCAPE);
+ }
+ dst.append(current);
+ escaped = false;
+ } else {
+ if (current == DQUOTE) {
+ pos++;
+ break;
+ }
+ if (current == ESCAPE) {
+ escaped = true;
+ } else if (current != CR && current != LF) {
+ dst.append(current);
+ }
+ }
+ }
+ cursor.updatePos(pos);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/TrustSelfSignedStrategy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/TrustSelfSignedStrategy.java
new file mode 100644
index 000000000..a3c23690b
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/TrustSelfSignedStrategy.java
@@ -0,0 +1,45 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.conn.ssl;
+
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+
+/**
+ * A trust strategy that accepts self-signed certificates as trusted. Verification of all other
+ * certificates is done by the trust manager configured in the SSL context.
+ *
+ * @since 4.1
+ */
+public class TrustSelfSignedStrategy implements TrustStrategy {
+
+ public boolean isTrusted(
+ final X509Certificate[] chain, final String authType) throws CertificateException {
+ return chain.length == 1;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/TrustStrategy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/TrustStrategy.java
new file mode 100644
index 000000000..7f4914503
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/TrustStrategy.java
@@ -0,0 +1,57 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.conn.ssl;
+
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+
+/**
+ * A strategy to establish trustworthiness of certificates without consulting the trust manager
+ * configured in the actual SSL context. This interface can be used to override the standard
+ * JSSE certificate verification process.
+ *
+ * @since 4.1
+ */
+public interface TrustStrategy {
+
+ /**
+ * Determines whether the certificate chain can be trusted without consulting the trust manager
+ * configured in the actual SSL context. This method can be used to override the standard JSSE
+ * certificate verification process.
+ *
+ * Please note that, if this method returns false, the trust manager configured
+ * in the actual SSL context can still clear the certificate as trusted.
+ *
+ * @param chain the peer certificate chain
+ * @param authType the authentication type based on the client certificate
+ * @return true if the certificate can be trusted without verification by
+ * the trust manager, false otherwise.
+ * @throws CertificateException thrown if the certificate is not trusted or invalid.
+ */
+ boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException;
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/X509HostnameVerifier.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/X509HostnameVerifier.java
new file mode 100644
index 000000000..cd57c623e
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/X509HostnameVerifier.java
@@ -0,0 +1,85 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.conn.ssl;
+
+import java.io.IOException;
+import java.security.cert.X509Certificate;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.SSLException;
+import javax.net.ssl.SSLSocket;
+
+/**
+ * Interface for checking if a hostname matches the names stored inside the
+ * server's X.509 certificate. This interface extends
+ * {@link javax.net.ssl.HostnameVerifier}, but it is recommended to use
+ * methods added by X509HostnameVerifier.
+ *
+ * @since 4.0
+ */
+public interface X509HostnameVerifier extends HostnameVerifier {
+
+ /**
+ * Verifies that the host name is an acceptable match with the server's
+ * authentication scheme based on the given {@link SSLSocket}.
+ *
+ * @param host the host.
+ * @param ssl the SSL socket.
+ * @throws IOException if an I/O error occurs or the verification process
+ * fails.
+ */
+ void verify(String host, SSLSocket ssl) throws IOException;
+
+ /**
+ * Verifies that the host name is an acceptable match with the server's
+ * authentication scheme based on the given {@link X509Certificate}.
+ *
+ * @param host the host.
+ * @param cert the certificate.
+ * @throws SSLException if the verification process fails.
+ */
+ void verify(String host, X509Certificate cert) throws SSLException;
+
+ /**
+ * Checks to see if the supplied hostname matches any of the supplied CNs
+ * or "DNS" Subject-Alts. Most implementations only look at the first CN,
+ * and ignore any additional CNs. Most implementations do look at all of
+ * the "DNS" Subject-Alts. The CNs or Subject-Alts may contain wildcards
+ * according to RFC 2818.
+ *
+ * @param cns CN fields, in order, as extracted from the X.509
+ * certificate.
+ * @param subjectAlts Subject-Alt fields of type 2 ("DNS"), as extracted
+ * from the X.509 certificate.
+ * @param host The hostname to verify.
+ * @throws SSLException if the verification process fails.
+ */
+ void verify(String host, String[] cns, String[] subjectAlts)
+ throws SSLException;
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/package-info.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/package-info.java
new file mode 100644
index 000000000..c05bf5be0
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/package-info.java
@@ -0,0 +1,31 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+/**
+ * Client TLS/SSL support.
+ */
+package ch.boye.httpclientandroidlib.conn.ssl;
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/util/InetAddressUtils.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/util/InetAddressUtils.java
new file mode 100644
index 000000000..ac9a8e2db
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/util/InetAddressUtils.java
@@ -0,0 +1,123 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.conn.util;
+
+import java.util.regex.Pattern;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+
+/**
+ * A collection of utilities relating to InetAddresses.
+ *
+ * @since 4.0
+ */
+@Immutable
+public class InetAddressUtils {
+
+ private InetAddressUtils() {
+ }
+
+ private static final String IPV4_BASIC_PATTERN_STRING =
+ "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}" + // initial 3 fields, 0-255 followed by .
+ "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"; // final field, 0-255
+
+ private static final Pattern IPV4_PATTERN =
+ Pattern.compile("^" + IPV4_BASIC_PATTERN_STRING + "$");
+
+ private static final Pattern IPV4_MAPPED_IPV6_PATTERN = // TODO does not allow for redundant leading zeros
+ Pattern.compile("^::[fF]{4}:" + IPV4_BASIC_PATTERN_STRING + "$");
+
+ private static final Pattern IPV6_STD_PATTERN =
+ Pattern.compile(
+ "^[0-9a-fA-F]{1,4}(:[0-9a-fA-F]{1,4}){7}$");
+
+ private static final Pattern IPV6_HEX_COMPRESSED_PATTERN =
+ Pattern.compile(
+ "^(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)" + // 0-6 hex fields
+ "::" +
+ "(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)$"); // 0-6 hex fields
+
+ /*
+ * The above pattern is not totally rigorous as it allows for more than 7 hex fields in total
+ */
+ private static final char COLON_CHAR = ':';
+
+ // Must not have more than 7 colons (i.e. 8 fields)
+ private static final int MAX_COLON_COUNT = 7;
+
+ /**
+ * Checks whether the parameter is a valid IPv4 address
+ *
+ * @param input the address string to check for validity
+ * @return true if the input parameter is a valid IPv4 address
+ */
+ public static boolean isIPv4Address(final String input) {
+ return IPV4_PATTERN.matcher(input).matches();
+ }
+
+ public static boolean isIPv4MappedIPv64Address(final String input) {
+ return IPV4_MAPPED_IPV6_PATTERN.matcher(input).matches();
+ }
+
+ /**
+ * Checks whether the parameter is a valid standard (non-compressed) IPv6 address
+ *
+ * @param input the address string to check for validity
+ * @return true if the input parameter is a valid standard (non-compressed) IPv6 address
+ */
+ public static boolean isIPv6StdAddress(final String input) {
+ return IPV6_STD_PATTERN.matcher(input).matches();
+ }
+
+ /**
+ * Checks whether the parameter is a valid compressed IPv6 address
+ *
+ * @param input the address string to check for validity
+ * @return true if the input parameter is a valid compressed IPv6 address
+ */
+ public static boolean isIPv6HexCompressedAddress(final String input) {
+ int colonCount = 0;
+ for(int i = 0; i < input.length(); i++) {
+ if (input.charAt(i) == COLON_CHAR) {
+ colonCount++;
+ }
+ }
+ return colonCount <= MAX_COLON_COUNT && IPV6_HEX_COMPRESSED_PATTERN.matcher(input).matches();
+ }
+
+ /**
+ * Checks whether the parameter is a valid IPv6 address (including compressed).
+ *
+ * @param input the address string to check for validity
+ * @return true if the input parameter is a valid standard or compressed IPv6 address
+ */
+ public static boolean isIPv6Address(final String input) {
+ return isIPv6StdAddress(input) || isIPv6HexCompressedAddress(input);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/util/package-info.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/util/package-info.java
new file mode 100644
index 000000000..6db59b736
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/util/package-info.java
@@ -0,0 +1,31 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+/**
+ * Connection utility classes.
+ */
+package ch.boye.httpclientandroidlib.conn.util;
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/ClientCookie.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/ClientCookie.java
new file mode 100644
index 000000000..1909f0999
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/ClientCookie.java
@@ -0,0 +1,62 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.cookie;
+
+/**
+ * ClientCookie extends the standard {@link Cookie} interface with
+ * additional client specific functionality such ability to retrieve
+ * original cookie attributes exactly as they were specified by the
+ * origin server. This is important for generating the Cookie
+ * header because some cookie specifications require that the
+ * Cookie header should include certain attributes only if
+ * they were specified in the Set-Cookie header.
+ *
+ *
+ * @since 4.0
+ */
+public interface ClientCookie extends Cookie {
+
+ // RFC2109 attributes
+ public static final String VERSION_ATTR = "version";
+ public static final String PATH_ATTR = "path";
+ public static final String DOMAIN_ATTR = "domain";
+ public static final String MAX_AGE_ATTR = "max-age";
+ public static final String SECURE_ATTR = "secure";
+ public static final String COMMENT_ATTR = "comment";
+ public static final String EXPIRES_ATTR = "expires";
+
+ // RFC2965 attributes
+ public static final String PORT_ATTR = "port";
+ public static final String COMMENTURL_ATTR = "commenturl";
+ public static final String DISCARD_ATTR = "discard";
+
+ String getAttribute(String name);
+
+ boolean containsAttribute(String name);
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/Cookie.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/Cookie.java
new file mode 100644
index 000000000..9953ab794
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/Cookie.java
@@ -0,0 +1,137 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.cookie;
+
+import java.util.Date;
+
+/**
+ * Cookie interface represents a token or short packet of state information
+ * (also referred to as "magic-cookie") that the HTTP agent and the target
+ * server can exchange to maintain a session. In its simples form an HTTP
+ * cookie is merely a name / value pair.
+ *
+ * @since 4.0
+ */
+public interface Cookie {
+
+ /**
+ * Returns the name.
+ *
+ * @return String name The name
+ */
+ String getName();
+
+ /**
+ * Returns the value.
+ *
+ * @return String value The current value.
+ */
+ String getValue();
+
+ /**
+ * Returns the comment describing the purpose of this cookie, or
+ * null if no such comment has been defined.
+ *
+ * @return comment
+ */
+ String getComment();
+
+ /**
+ * If a user agent (web browser) presents this cookie to a user, the
+ * cookie's purpose will be described by the information at this URL.
+ */
+ String getCommentURL();
+
+ /**
+ * Returns the expiration {@link Date} of the cookie, or null
+ * if none exists.
+ *
Note: the object returned by this method is
+ * considered immutable. Changing it (e.g. using setTime()) could result
+ * in undefined behaviour. Do so at your peril.
+ * @return Expiration {@link Date}, or null.
+ */
+ Date getExpiryDate();
+
+ /**
+ * Returns false if the cookie should be discarded at the end
+ * of the "session"; true otherwise.
+ *
+ * @return false if the cookie should be discarded at the end
+ * of the "session"; true otherwise
+ */
+ boolean isPersistent();
+
+ /**
+ * Returns domain attribute of the cookie. The value of the Domain
+ * attribute specifies the domain for which the cookie is valid.
+ *
+ * @return the value of the domain attribute.
+ */
+ String getDomain();
+
+ /**
+ * Returns the path attribute of the cookie. The value of the Path
+ * attribute specifies the subset of URLs on the origin server to which
+ * this cookie applies.
+ *
+ * @return The value of the path attribute.
+ */
+ String getPath();
+
+ /**
+ * Get the Port attribute. It restricts the ports to which a cookie
+ * may be returned in a Cookie request header.
+ */
+ int[] getPorts();
+
+ /**
+ * Indicates whether this cookie requires a secure connection.
+ *
+ * @return true if this cookie should only be sent
+ * over secure connections, false otherwise.
+ */
+ boolean isSecure();
+
+ /**
+ * Returns the version of the cookie specification to which this
+ * cookie conforms.
+ *
+ * @return the version of the cookie.
+ */
+ int getVersion();
+
+ /**
+ * Returns true if this cookie has expired.
+ * @param date Current time
+ *
+ * @return true if the cookie has expired.
+ */
+ boolean isExpired(final Date date);
+
+}
+
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieAttributeHandler.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieAttributeHandler.java
new file mode 100644
index 000000000..3d94c8a6f
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieAttributeHandler.java
@@ -0,0 +1,73 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.cookie;
+
+/**
+ * This interface represents a cookie attribute handler responsible
+ * for parsing, validating, and matching a specific cookie attribute,
+ * such as path, domain, port, etc.
+ *
+ * Different cookie specifications can provide a specific
+ * implementation for this class based on their cookie handling
+ * rules.
+ *
+ *
+ * @since 4.0
+ */
+public interface CookieAttributeHandler {
+
+ /**
+ * Parse the given cookie attribute value and update the corresponding
+ * {@link ch.boye.httpclientandroidlib.cookie.Cookie} property.
+ *
+ * @param cookie {@link ch.boye.httpclientandroidlib.cookie.Cookie} to be updated
+ * @param value cookie attribute value from the cookie response header
+ */
+ void parse(SetCookie cookie, String value)
+ throws MalformedCookieException;
+
+ /**
+ * Peforms cookie validation for the given attribute value.
+ *
+ * @param cookie {@link ch.boye.httpclientandroidlib.cookie.Cookie} to validate
+ * @param origin the cookie source to validate against
+ * @throws MalformedCookieException if cookie validation fails for this attribute
+ */
+ void validate(Cookie cookie, CookieOrigin origin)
+ throws MalformedCookieException;
+
+ /**
+ * Matches the given value (property of the destination host where request is being
+ * submitted) with the corresponding cookie attribute.
+ *
+ * @param cookie {@link ch.boye.httpclientandroidlib.cookie.Cookie} to match
+ * @param origin the cookie source to match against
+ * @return true if the match is successful; false otherwise
+ */
+ boolean match(Cookie cookie, CookieOrigin origin);
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieIdentityComparator.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieIdentityComparator.java
new file mode 100644
index 000000000..863640e69
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieIdentityComparator.java
@@ -0,0 +1,80 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.cookie;
+
+import java.io.Serializable;
+import java.util.Comparator;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+
+/**
+ * This cookie comparator can be used to compare identity of cookies.
+ *
+ * Cookies are considered identical if their names are equal and
+ * their domain attributes match ignoring case.
+ *
+ * @since 4.0
+ */
+@Immutable
+public class CookieIdentityComparator implements Serializable, Comparator {
+
+ private static final long serialVersionUID = 4466565437490631532L;
+
+ public int compare(final Cookie c1, final Cookie c2) {
+ int res = c1.getName().compareTo(c2.getName());
+ if (res == 0) {
+ // do not differentiate empty and null domains
+ String d1 = c1.getDomain();
+ if (d1 == null) {
+ d1 = "";
+ } else if (d1.indexOf('.') == -1) {
+ d1 = d1 + ".local";
+ }
+ String d2 = c2.getDomain();
+ if (d2 == null) {
+ d2 = "";
+ } else if (d2.indexOf('.') == -1) {
+ d2 = d2 + ".local";
+ }
+ res = d1.compareToIgnoreCase(d2);
+ }
+ if (res == 0) {
+ String p1 = c1.getPath();
+ if (p1 == null) {
+ p1 = "/";
+ }
+ String p2 = c2.getPath();
+ if (p2 == null) {
+ p2 = "/";
+ }
+ res = p1.compareTo(p2);
+ }
+ return res;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieOrigin.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieOrigin.java
new file mode 100644
index 000000000..aef29023d
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieOrigin.java
@@ -0,0 +1,94 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.cookie;
+
+import java.util.Locale;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * CookieOrigin class encapsulates details of an origin server that
+ * are relevant when parsing, validating or matching HTTP cookies.
+ *
+ * @since 4.0
+ */
+@Immutable
+public final class CookieOrigin {
+
+ private final String host;
+ private final int port;
+ private final String path;
+ private final boolean secure;
+
+ public CookieOrigin(final String host, final int port, final String path, final boolean secure) {
+ super();
+ Args.notBlank(host, "Host");
+ Args.notNegative(port, "Port");
+ Args.notNull(path, "Path");
+ this.host = host.toLowerCase(Locale.ENGLISH);
+ this.port = port;
+ if (path.trim().length() != 0) {
+ this.path = path;
+ } else {
+ this.path = "/";
+ }
+ this.secure = secure;
+ }
+
+ public String getHost() {
+ return this.host;
+ }
+
+ public String getPath() {
+ return this.path;
+ }
+
+ public int getPort() {
+ return this.port;
+ }
+
+ public boolean isSecure() {
+ return this.secure;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder buffer = new StringBuilder();
+ buffer.append('[');
+ if (this.secure) {
+ buffer.append("(secure)");
+ }
+ buffer.append(this.host);
+ buffer.append(':');
+ buffer.append(Integer.toString(this.port));
+ buffer.append(this.path);
+ buffer.append(']');
+ return buffer.toString();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookiePathComparator.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookiePathComparator.java
new file mode 100644
index 000000000..984bb850f
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookiePathComparator.java
@@ -0,0 +1,81 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.cookie;
+
+import java.io.Serializable;
+import java.util.Comparator;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+
+/**
+ * This cookie comparator ensures that multiple cookies satisfying
+ * a common criteria are ordered in the Cookie header such
+ * that those with more specific Path attributes precede those with
+ * less specific.
+ *
+ *
+ * This comparator assumes that Path attributes of two cookies
+ * path-match a commmon request-URI. Otherwise, the result of the
+ * comparison is undefined.
+ *
+ *
+ *
+ * @since 4.0
+ */
+@Immutable
+public class CookiePathComparator implements Serializable, Comparator {
+
+ private static final long serialVersionUID = 7523645369616405818L;
+
+ private String normalizePath(final Cookie cookie) {
+ String path = cookie.getPath();
+ if (path == null) {
+ path = "/";
+ }
+ if (!path.endsWith("/")) {
+ path = path + '/';
+ }
+ return path;
+ }
+
+ public int compare(final Cookie c1, final Cookie c2) {
+ final String path1 = normalizePath(c1);
+ final String path2 = normalizePath(c2);
+ if (path1.equals(path2)) {
+ return 0;
+ } else if (path1.startsWith(path2)) {
+ return -1;
+ } else if (path2.startsWith(path1)) {
+ return 1;
+ } else {
+ // Does not really matter
+ return 0;
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieRestrictionViolationException.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieRestrictionViolationException.java
new file mode 100644
index 000000000..1e3f2d70c
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieRestrictionViolationException.java
@@ -0,0 +1,61 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.cookie;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+
+/**
+ * Signals that a cookie violates a restriction imposed by the cookie
+ * specification.
+ *
+ * @since 4.1
+ */
+@Immutable
+public class CookieRestrictionViolationException extends MalformedCookieException {
+
+ private static final long serialVersionUID = 7371235577078589013L;
+
+ /**
+ * Creates a new CookeFormatViolationException with a null detail
+ * message.
+ */
+ public CookieRestrictionViolationException() {
+ super();
+ }
+
+ /**
+ * Creates a new CookeRestrictionViolationException with a specified
+ * message string.
+ *
+ * @param message The exception detail message
+ */
+ public CookieRestrictionViolationException(final String message) {
+ super(message);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieSpec.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieSpec.java
new file mode 100644
index 000000000..c222e5e72
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieSpec.java
@@ -0,0 +1,109 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.cookie;
+
+import java.util.List;
+
+import ch.boye.httpclientandroidlib.Header;
+
+/**
+ * Defines the cookie management specification.
+ *
Cookie management specification must define
+ *
+ *
rules of parsing "Set-Cookie" header
+ *
rules of validation of parsed cookies
+ *
formatting of "Cookie" header
+ *
+ * for a given host, port and path of origin
+ *
+ *
+ * @since 4.0
+ */
+public interface CookieSpec {
+
+ /**
+ * Returns version of the state management this cookie specification
+ * conforms to.
+ *
+ * @return version of the state management specification
+ */
+ int getVersion();
+
+ /**
+ * Parse the "Set-Cookie" Header into an array of Cookies.
+ *
+ *
This method will not perform the validation of the resultant
+ * {@link Cookie}s
+ *
+ * @see #validate
+ *
+ * @param header the Set-Cookie received from the server
+ * @param origin details of the cookie origin
+ * @return an array of Cookies parsed from the header
+ * @throws MalformedCookieException if an exception occurs during parsing
+ */
+ List parse(Header header, CookieOrigin origin) throws MalformedCookieException;
+
+ /**
+ * Validate the cookie according to validation rules defined by the
+ * cookie specification.
+ *
+ * @param cookie the Cookie to validate
+ * @param origin details of the cookie origin
+ * @throws MalformedCookieException if the cookie is invalid
+ */
+ void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException;
+
+ /**
+ * Determines if a Cookie matches the target location.
+ *
+ * @param cookie the Cookie to be matched
+ * @param origin the target to test against
+ *
+ * @return true if the cookie should be submitted with a request
+ * with given attributes, false otherwise.
+ */
+ boolean match(Cookie cookie, CookieOrigin origin);
+
+ /**
+ * Create "Cookie" headers for an array of Cookies.
+ *
+ * @param cookies the Cookies format into a Cookie header
+ * @return a Header for the given Cookies.
+ * @throws IllegalArgumentException if an input parameter is illegal
+ */
+ List formatCookies(List cookies);
+
+ /**
+ * Returns a request header identifying what version of the state management
+ * specification is understood. May be null if the cookie
+ * specification does not support Cookie2 header.
+ */
+ Header getVersionHeader();
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieSpecFactory.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieSpecFactory.java
new file mode 100644
index 000000000..fd7851626
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieSpecFactory.java
@@ -0,0 +1,51 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.cookie;
+
+import ch.boye.httpclientandroidlib.params.HttpParams;
+
+/**
+ * Factory for {@link CookieSpec} implementations.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link CookieSpecProvider}
+ */
+@Deprecated
+public interface CookieSpecFactory {
+
+ /**
+ * Creates an instance of {@link CookieSpec} using given HTTP parameters.
+ *
+ * @param params HTTP parameters.
+ *
+ * @return cookie spec.
+ */
+ CookieSpec newInstance(HttpParams params);
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieSpecProvider.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieSpecProvider.java
new file mode 100644
index 000000000..921adfba4
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieSpecProvider.java
@@ -0,0 +1,46 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.cookie;
+
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+/**
+ * Factory for {@link CookieSpec} implementations.
+ *
+ * @since 4.3
+ */
+public interface CookieSpecProvider {
+
+ /**
+ * Creates an instance of {@link CookieSpec}.
+ *
+ * @return auth scheme.
+ */
+ CookieSpec create(HttpContext context);
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieSpecRegistry.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieSpecRegistry.java
new file mode 100644
index 000000000..adbfe863a
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/CookieSpecRegistry.java
@@ -0,0 +1,167 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.cookie;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.config.Lookup;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.ExecutionContext;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Cookie specification registry that can be used to obtain the corresponding
+ * cookie specification implementation for a given type of type or version of
+ * cookie.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link ch.boye.httpclientandroidlib.config.Registry}.
+ */
+@ThreadSafe
+@Deprecated
+public final class CookieSpecRegistry implements Lookup {
+
+ private final ConcurrentHashMap registeredSpecs;
+
+ public CookieSpecRegistry() {
+ super();
+ this.registeredSpecs = new ConcurrentHashMap();
+ }
+
+ /**
+ * Registers a {@link CookieSpecFactory} with the given identifier.
+ * If a specification with the given name already exists it will be overridden.
+ * This nameis the same one used to retrieve the {@link CookieSpecFactory}
+ * from {@link #getCookieSpec(String)}.
+ *
+ * @param name the identifier for this specification
+ * @param factory the {@link CookieSpecFactory} class to register
+ *
+ * @see #getCookieSpec(String)
+ */
+ public void register(final String name, final CookieSpecFactory factory) {
+ Args.notNull(name, "Name");
+ Args.notNull(factory, "Cookie spec factory");
+ registeredSpecs.put(name.toLowerCase(Locale.ENGLISH), factory);
+ }
+
+ /**
+ * Unregisters the {@link CookieSpecFactory} with the given ID.
+ *
+ * @param id the identifier of the {@link CookieSpec cookie specification} to unregister
+ */
+ public void unregister(final String id) {
+ Args.notNull(id, "Id");
+ registeredSpecs.remove(id.toLowerCase(Locale.ENGLISH));
+ }
+
+ /**
+ * Gets the {@link CookieSpec cookie specification} with the given ID.
+ *
+ * @param name the {@link CookieSpec cookie specification} identifier
+ * @param params the {@link HttpParams HTTP parameters} for the cookie
+ * specification.
+ *
+ * @return {@link CookieSpec cookie specification}
+ *
+ * @throws IllegalStateException if a policy with the given name cannot be found
+ */
+ public CookieSpec getCookieSpec(final String name, final HttpParams params)
+ throws IllegalStateException {
+
+ Args.notNull(name, "Name");
+ final CookieSpecFactory factory = registeredSpecs.get(name.toLowerCase(Locale.ENGLISH));
+ if (factory != null) {
+ return factory.newInstance(params);
+ } else {
+ throw new IllegalStateException("Unsupported cookie spec: " + name);
+ }
+ }
+
+ /**
+ * Gets the {@link CookieSpec cookie specification} with the given name.
+ *
+ * @param name the {@link CookieSpec cookie specification} identifier
+ *
+ * @return {@link CookieSpec cookie specification}
+ *
+ * @throws IllegalStateException if a policy with the given name cannot be found
+ */
+ public CookieSpec getCookieSpec(final String name)
+ throws IllegalStateException {
+ return getCookieSpec(name, null);
+ }
+
+ /**
+ * Obtains a list containing the names of all registered {@link CookieSpec cookie
+ * specs}.
+ *
+ * Note that the DEFAULT policy (if present) is likely to be the same
+ * as one of the other policies, but does not have to be.
+ *
+ * @return list of registered cookie spec names
+ */
+ public List getSpecNames(){
+ return new ArrayList(registeredSpecs.keySet());
+ }
+
+ /**
+ * Populates the internal collection of registered {@link CookieSpec cookie
+ * specs} with the content of the map passed as a parameter.
+ *
+ * @param map cookie specs
+ */
+ public void setItems(final Map map) {
+ if (map == null) {
+ return;
+ }
+ registeredSpecs.clear();
+ registeredSpecs.putAll(map);
+ }
+
+ public CookieSpecProvider lookup(final String name) {
+ return new CookieSpecProvider() {
+
+ public CookieSpec create(final HttpContext context) {
+ final HttpRequest request = (HttpRequest) context.getAttribute(
+ ExecutionContext.HTTP_REQUEST);
+ return getCookieSpec(name, request.getParams());
+ }
+
+ };
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/MalformedCookieException.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/MalformedCookieException.java
new file mode 100644
index 000000000..dba7b9b25
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/MalformedCookieException.java
@@ -0,0 +1,71 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.cookie;
+
+import ch.boye.httpclientandroidlib.ProtocolException;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+
+/**
+ * Signals that a cookie is in some way invalid or illegal in a given
+ * context
+ *
+ *
+ * @since 4.0
+ */
+@Immutable
+public class MalformedCookieException extends ProtocolException {
+
+ private static final long serialVersionUID = -6695462944287282185L;
+
+ /**
+ * Creates a new MalformedCookieException with a null detail message.
+ */
+ public MalformedCookieException() {
+ super();
+ }
+
+ /**
+ * Creates a new MalformedCookieException with a specified message string.
+ *
+ * @param message The exception detail message
+ */
+ public MalformedCookieException(final String message) {
+ super(message);
+ }
+
+ /**
+ * Creates a new MalformedCookieException with the specified detail message and cause.
+ *
+ * @param message the exception detail message
+ * @param cause the Throwable that caused this exception, or null
+ * if the cause is unavailable, unknown, or not a Throwable
+ */
+ public MalformedCookieException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/SM.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/SM.java
new file mode 100644
index 000000000..463da4d25
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/SM.java
@@ -0,0 +1,43 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.cookie;
+
+/**
+ * Constants and static helpers related to the HTTP state management.
+ *
+ *
+ * @since 4.0
+ */
+public interface SM {
+
+ public static final String COOKIE = "Cookie";
+ public static final String COOKIE2 = "Cookie2";
+ public static final String SET_COOKIE = "Set-Cookie";
+ public static final String SET_COOKIE2 = "Set-Cookie2";
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/SetCookie.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/SetCookie.java
new file mode 100644
index 000000000..5bd5b7121
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/SetCookie.java
@@ -0,0 +1,109 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.cookie;
+
+import java.util.Date;
+
+/**
+ * This interface represents a Set-Cookie response header sent by the
+ * origin server to the HTTP agent in order to maintain a conversational state.
+ *
+ * @since 4.0
+ */
+public interface SetCookie extends Cookie {
+
+ void setValue(String value);
+
+ /**
+ * If a user agent (web browser) presents this cookie to a user, the
+ * cookie's purpose will be described using this comment.
+ *
+ * @param comment
+ *
+ * @see #getComment()
+ */
+ void setComment(String comment);
+
+ /**
+ * Sets expiration date.
+ *
Note: the object returned by this method is considered
+ * immutable. Changing it (e.g. using setTime()) could result in undefined
+ * behaviour. Do so at your peril.
+ *
+ * @param expiryDate the {@link Date} after which this cookie is no longer valid.
+ *
+ * @see Cookie#getExpiryDate
+ *
+ */
+ void setExpiryDate (Date expiryDate);
+
+ /**
+ * Sets the domain attribute.
+ *
+ * @param domain The value of the domain attribute
+ *
+ * @see Cookie#getDomain
+ */
+ void setDomain(String domain);
+
+ /**
+ * Sets the path attribute.
+ *
+ * @param path The value of the path attribute
+ *
+ * @see Cookie#getPath
+ *
+ */
+ void setPath(String path);
+
+ /**
+ * Sets the secure attribute of the cookie.
+ *
+ * When true the cookie should only be sent
+ * using a secure protocol (https). This should only be set when
+ * the cookie's originating server used a secure protocol to set the
+ * cookie's value.
+ *
+ * @param secure The value of the secure attribute
+ *
+ * @see #isSecure()
+ */
+ void setSecure (boolean secure);
+
+ /**
+ * Sets the version of the cookie specification to which this
+ * cookie conforms.
+ *
+ * @param version the version of the cookie.
+ *
+ * @see Cookie#getVersion
+ */
+ void setVersion(int version);
+
+}
+
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/SetCookie2.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/SetCookie2.java
new file mode 100644
index 000000000..bc3508059
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/SetCookie2.java
@@ -0,0 +1,60 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.cookie;
+
+/**
+ * This interface represents a Set-Cookie2 response header sent by the
+ * origin server to the HTTP agent in order to maintain a conversational state.
+ *
+ * @since 4.0
+ */
+public interface SetCookie2 extends SetCookie {
+
+ /**
+ * If a user agent (web browser) presents this cookie to a user, the
+ * cookie's purpose will be described by the information at this URL.
+ */
+ void setCommentURL(String commentURL);
+
+ /**
+ * Sets the Port attribute. It restricts the ports to which a cookie
+ * may be returned in a Cookie request header.
+ */
+ void setPorts(int[] ports);
+
+ /**
+ * Set the Discard attribute.
+ *
+ * Note: Discard attribute overrides Max-age.
+ *
+ * @see #isPersistent()
+ */
+ void setDiscard(boolean discard);
+
+}
+
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/package-info.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/package-info.java
new file mode 100644
index 000000000..80a831709
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/package-info.java
@@ -0,0 +1,31 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+/**
+ * Client HTTP state management APIs.
+ */
+package ch.boye.httpclientandroidlib.cookie;
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/params/CookieSpecPNames.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/params/CookieSpecPNames.java
new file mode 100644
index 000000000..a93a26f16
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/params/CookieSpecPNames.java
@@ -0,0 +1,65 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.cookie.params;
+
+/**
+ * Parameter names for HTTP cookie management classes.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use constructor parameters of {@link
+ * ch.boye.httpclientandroidlib.cookie.CookieSpecProvider}s.
+ */
+@Deprecated
+public interface CookieSpecPNames {
+
+ /**
+ * Defines valid date patterns to be used for parsing non-standard
+ * expires attribute. Only required for compatibility
+ * with non-compliant servers that still use expires
+ * defined in the Netscape draft instead of the standard
+ * max-age attribute.
+ *
+ * This parameter expects a value of type {@link java.util.Collection}.
+ * The collection elements must be of type {@link String} compatible
+ * with the syntax of {@link java.text.SimpleDateFormat}.
+ *
+ */
+ public static final String DATE_PATTERNS = "http.protocol.cookie-datepatterns";
+
+ /**
+ * Defines whether cookies should be forced into a single
+ * Cookie request header. Otherwise, each cookie is formatted
+ * as a separate Cookie header.
+ *
+ * This parameter expects a value of type {@link Boolean}.
+ *
+ */
+ public static final String SINGLE_COOKIE_HEADER = "http.protocol.single-cookie-header";
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/params/CookieSpecParamBean.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/params/CookieSpecParamBean.java
new file mode 100644
index 000000000..0e007a54f
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/params/CookieSpecParamBean.java
@@ -0,0 +1,62 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.cookie.params;
+
+import java.util.Collection;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.params.HttpAbstractParamBean;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+
+/**
+ * This is a Java Bean class that can be used to wrap an instance of
+ * {@link HttpParams} and manipulate HTTP cookie parameters using Java Beans
+ * conventions.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use constructor parameters of {@link
+ * ch.boye.httpclientandroidlib.cookie.CookieSpecProvider}s.
+ */
+@Deprecated
+@NotThreadSafe
+public class CookieSpecParamBean extends HttpAbstractParamBean {
+
+ public CookieSpecParamBean (final HttpParams params) {
+ super(params);
+ }
+
+ public void setDatePatterns (final Collection patterns) {
+ params.setParameter(CookieSpecPNames.DATE_PATTERNS, patterns);
+ }
+
+ public void setSingleHeader (final boolean singleHeader) {
+ params.setBooleanParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, singleHeader);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/params/package-info.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/params/package-info.java
new file mode 100644
index 000000000..9314e1e63
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/cookie/params/package-info.java
@@ -0,0 +1,32 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+/**
+ * Deprecated.
+ * @deprecated (4.3).
+ */
+package ch.boye.httpclientandroidlib.cookie.params;
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/AbstractHttpEntity.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/AbstractHttpEntity.java
new file mode 100644
index 000000000..9fc32fa29
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/AbstractHttpEntity.java
@@ -0,0 +1,191 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.message.BasicHeader;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+
+/**
+ * Abstract base class for entities.
+ * Provides the commonly used attributes for streamed and self-contained
+ * implementations of {@link HttpEntity HttpEntity}.
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public abstract class AbstractHttpEntity implements HttpEntity {
+
+ /**
+ * Buffer size for output stream processing.
+ *
+ * @since 4.3
+ */
+ protected static final int OUTPUT_BUFFER_SIZE = 4096;
+
+ protected Header contentType;
+ protected Header contentEncoding;
+ protected boolean chunked;
+
+ /**
+ * Protected default constructor.
+ * The contentType, contentEncoding and chunked attributes of the created object are set to
+ * null, null and false, respectively.
+ */
+ protected AbstractHttpEntity() {
+ super();
+ }
+
+
+ /**
+ * Obtains the Content-Type header.
+ * The default implementation returns the value of the
+ * {@link #contentType contentType} attribute.
+ *
+ * @return the Content-Type header, or null
+ */
+ public Header getContentType() {
+ return this.contentType;
+ }
+
+
+ /**
+ * Obtains the Content-Encoding header.
+ * The default implementation returns the value of the
+ * {@link #contentEncoding contentEncoding} attribute.
+ *
+ * @return the Content-Encoding header, or null
+ */
+ public Header getContentEncoding() {
+ return this.contentEncoding;
+ }
+
+ /**
+ * Obtains the 'chunked' flag.
+ * The default implementation returns the value of the
+ * {@link #chunked chunked} attribute.
+ *
+ * @return the 'chunked' flag
+ */
+ public boolean isChunked() {
+ return this.chunked;
+ }
+
+
+ /**
+ * Specifies the Content-Type header.
+ * The default implementation sets the value of the
+ * {@link #contentType contentType} attribute.
+ *
+ * @param contentType the new Content-Encoding header, or
+ * null to unset
+ */
+ public void setContentType(final Header contentType) {
+ this.contentType = contentType;
+ }
+
+ /**
+ * Specifies the Content-Type header, as a string.
+ * The default implementation calls
+ * {@link #setContentType(Header) setContentType(Header)}.
+ *
+ * @param ctString the new Content-Type header, or
+ * null to unset
+ */
+ public void setContentType(final String ctString) {
+ Header h = null;
+ if (ctString != null) {
+ h = new BasicHeader(HTTP.CONTENT_TYPE, ctString);
+ }
+ setContentType(h);
+ }
+
+
+ /**
+ * Specifies the Content-Encoding header.
+ * The default implementation sets the value of the
+ * {@link #contentEncoding contentEncoding} attribute.
+ *
+ * @param contentEncoding the new Content-Encoding header, or
+ * null to unset
+ */
+ public void setContentEncoding(final Header contentEncoding) {
+ this.contentEncoding = contentEncoding;
+ }
+
+ /**
+ * Specifies the Content-Encoding header, as a string.
+ * The default implementation calls
+ * {@link #setContentEncoding(Header) setContentEncoding(Header)}.
+ *
+ * @param ceString the new Content-Encoding header, or
+ * null to unset
+ */
+ public void setContentEncoding(final String ceString) {
+ Header h = null;
+ if (ceString != null) {
+ h = new BasicHeader(HTTP.CONTENT_ENCODING, ceString);
+ }
+ setContentEncoding(h);
+ }
+
+
+ /**
+ * Specifies the 'chunked' flag.
+ *
+ * Note that the chunked setting is a hint only.
+ * If using HTTP/1.0, chunking is never performed.
+ * Otherwise, even if chunked is false, HttpClient must
+ * use chunk coding if the entity content length is
+ * unknown (-1).
+ *
+ * The default implementation sets the value of the
+ * {@link #chunked chunked} attribute.
+ *
+ * @param b the new 'chunked' flag
+ */
+ public void setChunked(final boolean b) {
+ this.chunked = b;
+ }
+
+
+ /**
+ * The default implementation does not consume anything.
+ *
+ * @deprecated (4.1) Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that;
+ * otherwise call {@link #writeTo(java.io.OutputStream)} which is required to free the resources.
+ */
+ @Deprecated
+ public void consumeContent() throws IOException {
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/BasicHttpEntity.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/BasicHttpEntity.java
new file mode 100644
index 000000000..74a281b2a
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/BasicHttpEntity.java
@@ -0,0 +1,125 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.Asserts;
+
+/**
+ * A generic streamed, non-repeatable entity that obtains its content
+ * from an {@link InputStream}.
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class BasicHttpEntity extends AbstractHttpEntity {
+
+ private InputStream content;
+ private long length;
+
+ /**
+ * Creates a new basic entity.
+ * The content is initially missing, the content length
+ * is set to a negative number.
+ */
+ public BasicHttpEntity() {
+ super();
+ this.length = -1;
+ }
+
+ public long getContentLength() {
+ return this.length;
+ }
+
+ /**
+ * Obtains the content, once only.
+ *
+ * @return the content, if this is the first call to this method
+ * since {@link #setContent setContent} has been called
+ *
+ * @throws IllegalStateException
+ * if the content has not been provided
+ */
+ public InputStream getContent() throws IllegalStateException {
+ Asserts.check(this.content != null, "Content has not been provided");
+ return this.content;
+ }
+
+ /**
+ * Tells that this entity is not repeatable.
+ *
+ * @return false
+ */
+ public boolean isRepeatable() {
+ return false;
+ }
+
+ /**
+ * Specifies the length of the content.
+ *
+ * @param len the number of bytes in the content, or
+ * a negative number to indicate an unknown length
+ */
+ public void setContentLength(final long len) {
+ this.length = len;
+ }
+
+ /**
+ * Specifies the content.
+ *
+ * @param instream the stream to return with the next call to
+ * {@link #getContent getContent}
+ */
+ public void setContent(final InputStream instream) {
+ this.content = instream;
+ }
+
+ public void writeTo(final OutputStream outstream) throws IOException {
+ Args.notNull(outstream, "Output stream");
+ final InputStream instream = getContent();
+ try {
+ int l;
+ final byte[] tmp = new byte[OUTPUT_BUFFER_SIZE];
+ while ((l = instream.read(tmp)) != -1) {
+ outstream.write(tmp, 0, l);
+ }
+ } finally {
+ instream.close();
+ }
+ }
+
+ public boolean isStreaming() {
+ return this.content != null;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/BufferedHttpEntity.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/BufferedHttpEntity.java
new file mode 100644
index 000000000..6cb7495d7
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/BufferedHttpEntity.java
@@ -0,0 +1,125 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.EntityUtils;
+
+/**
+ * A wrapping entity that buffers it content if necessary.
+ * The buffered entity is always repeatable.
+ * If the wrapped entity is repeatable itself, calls are passed through.
+ * If the wrapped entity is not repeatable, the content is read into a
+ * buffer once and provided from there as often as required.
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class BufferedHttpEntity extends HttpEntityWrapper {
+
+ private final byte[] buffer;
+
+ /**
+ * Creates a new buffered entity wrapper.
+ *
+ * @param entity the entity to wrap, not null
+ * @throws IllegalArgumentException if wrapped is null
+ */
+ public BufferedHttpEntity(final HttpEntity entity) throws IOException {
+ super(entity);
+ if (!entity.isRepeatable() || entity.getContentLength() < 0) {
+ this.buffer = EntityUtils.toByteArray(entity);
+ } else {
+ this.buffer = null;
+ }
+ }
+
+ @Override
+ public long getContentLength() {
+ if (this.buffer != null) {
+ return this.buffer.length;
+ } else {
+ return super.getContentLength();
+ }
+ }
+
+ @Override
+ public InputStream getContent() throws IOException {
+ if (this.buffer != null) {
+ return new ByteArrayInputStream(this.buffer);
+ } else {
+ return super.getContent();
+ }
+ }
+
+ /**
+ * Tells that this entity does not have to be chunked.
+ *
+ * @return false
+ */
+ @Override
+ public boolean isChunked() {
+ return (buffer == null) && super.isChunked();
+ }
+
+ /**
+ * Tells that this entity is repeatable.
+ *
+ * @return true
+ */
+ @Override
+ public boolean isRepeatable() {
+ return true;
+ }
+
+
+ @Override
+ public void writeTo(final OutputStream outstream) throws IOException {
+ Args.notNull(outstream, "Output stream");
+ if (this.buffer != null) {
+ outstream.write(this.buffer);
+ } else {
+ super.writeTo(outstream);
+ }
+ }
+
+
+ // non-javadoc, see interface HttpEntity
+ @Override
+ public boolean isStreaming() {
+ return (buffer == null) && super.isStreaming();
+ }
+
+} // class BufferedHttpEntity
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/ByteArrayEntity.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/ByteArrayEntity.java
new file mode 100644
index 000000000..9f0af3ab8
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/ByteArrayEntity.java
@@ -0,0 +1,131 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * A self contained, repeatable entity that obtains its content from a byte array.
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class ByteArrayEntity extends AbstractHttpEntity implements Cloneable {
+
+ /**
+ * @deprecated (4.2)
+ */
+ @Deprecated
+ protected final byte[] content;
+ private final byte[] b;
+ private final int off, len;
+
+ /**
+ * @since 4.2
+ */
+ @SuppressWarnings("deprecation")
+ public ByteArrayEntity(final byte[] b, final ContentType contentType) {
+ super();
+ Args.notNull(b, "Source byte array");
+ this.content = b;
+ this.b = b;
+ this.off = 0;
+ this.len = this.b.length;
+ if (contentType != null) {
+ setContentType(contentType.toString());
+ }
+ }
+
+ /**
+ * @since 4.2
+ */
+ @SuppressWarnings("deprecation")
+ public ByteArrayEntity(final byte[] b, final int off, final int len, final ContentType contentType) {
+ super();
+ Args.notNull(b, "Source byte array");
+ if ((off < 0) || (off > b.length) || (len < 0) ||
+ ((off + len) < 0) || ((off + len) > b.length)) {
+ throw new IndexOutOfBoundsException("off: " + off + " len: " + len + " b.length: " + b.length);
+ }
+ this.content = b;
+ this.b = b;
+ this.off = off;
+ this.len = len;
+ if (contentType != null) {
+ setContentType(contentType.toString());
+ }
+ }
+
+ public ByteArrayEntity(final byte[] b) {
+ this(b, null);
+ }
+
+ public ByteArrayEntity(final byte[] b, final int off, final int len) {
+ this(b, off, len, null);
+ }
+
+ public boolean isRepeatable() {
+ return true;
+ }
+
+ public long getContentLength() {
+ return this.len;
+ }
+
+ public InputStream getContent() {
+ return new ByteArrayInputStream(this.b, this.off, this.len);
+ }
+
+ public void writeTo(final OutputStream outstream) throws IOException {
+ Args.notNull(outstream, "Output stream");
+ outstream.write(this.b, this.off, this.len);
+ outstream.flush();
+ }
+
+
+ /**
+ * Tells that this entity is not streaming.
+ *
+ * @return false
+ */
+ public boolean isStreaming() {
+ return false;
+ }
+
+ @Override
+ public Object clone() throws CloneNotSupportedException {
+ return super.clone();
+ }
+
+} // class ByteArrayEntity
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/ContentLengthStrategy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/ContentLengthStrategy.java
new file mode 100644
index 000000000..4dbc1afaf
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/ContentLengthStrategy.java
@@ -0,0 +1,57 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity;
+
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpMessage;
+
+/**
+ * Represents a strategy to determine length of the enclosed content entity
+ * based on properties of the HTTP message.
+ *
+ * @since 4.0
+ */
+public interface ContentLengthStrategy {
+
+ public static final int IDENTITY = -1;
+ public static final int CHUNKED = -2;
+
+ /**
+ * Returns length of the given message in bytes. The returned value
+ * must be a non-negative number, {@link #IDENTITY} if the end of the
+ * message will be delimited by the end of connection, or {@link #CHUNKED}
+ * if the message is chunk coded
+ *
+ * @param message HTTP message
+ * @return content length, {@link #IDENTITY}, or {@link #CHUNKED}
+ *
+ * @throws HttpException in case of HTTP protocol violation
+ */
+ long determineLength(HttpMessage message) throws HttpException;
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/ContentProducer.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/ContentProducer.java
new file mode 100644
index 000000000..3ced2e48b
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/ContentProducer.java
@@ -0,0 +1,44 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * An abstract entity content producer.
+ *
Content producers are expected to be able to produce their
+ * content multiple times
+ *
+ * @since 4.0
+ */
+public interface ContentProducer {
+
+ void writeTo(OutputStream outstream) throws IOException;
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/ContentType.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/ContentType.java
new file mode 100644
index 000000000..e486b83b3
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/ContentType.java
@@ -0,0 +1,305 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity;
+
+import java.io.Serializable;
+import java.nio.charset.Charset;
+import java.nio.charset.UnsupportedCharsetException;
+import java.util.Locale;
+
+import ch.boye.httpclientandroidlib.Consts;
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HeaderElement;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.NameValuePair;
+import ch.boye.httpclientandroidlib.ParseException;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.message.BasicHeaderValueFormatter;
+import ch.boye.httpclientandroidlib.message.BasicHeaderValueParser;
+import ch.boye.httpclientandroidlib.message.ParserCursor;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
+import ch.boye.httpclientandroidlib.util.TextUtils;
+
+/**
+ * Content type information consisting of a MIME type and an optional charset.
+ *
+ * This class makes no attempts to verify validity of the MIME type.
+ * The input parameters of the {@link #create(String, String)} method, however, may not
+ * contain characters <">, <;>, <,> reserved by the HTTP specification.
+ *
+ * @since 4.2
+ */
+@Immutable
+public final class ContentType implements Serializable {
+
+ private static final long serialVersionUID = -7768694718232371896L;
+
+ // constants
+ public static final ContentType APPLICATION_ATOM_XML = create(
+ "application/atom+xml", Consts.ISO_8859_1);
+ public static final ContentType APPLICATION_FORM_URLENCODED = create(
+ "application/x-www-form-urlencoded", Consts.ISO_8859_1);
+ public static final ContentType APPLICATION_JSON = create(
+ "application/json", Consts.UTF_8);
+ public static final ContentType APPLICATION_OCTET_STREAM = create(
+ "application/octet-stream", (Charset) null);
+ public static final ContentType APPLICATION_SVG_XML = create(
+ "application/svg+xml", Consts.ISO_8859_1);
+ public static final ContentType APPLICATION_XHTML_XML = create(
+ "application/xhtml+xml", Consts.ISO_8859_1);
+ public static final ContentType APPLICATION_XML = create(
+ "application/xml", Consts.ISO_8859_1);
+ public static final ContentType MULTIPART_FORM_DATA = create(
+ "multipart/form-data", Consts.ISO_8859_1);
+ public static final ContentType TEXT_HTML = create(
+ "text/html", Consts.ISO_8859_1);
+ public static final ContentType TEXT_PLAIN = create(
+ "text/plain", Consts.ISO_8859_1);
+ public static final ContentType TEXT_XML = create(
+ "text/xml", Consts.ISO_8859_1);
+ public static final ContentType WILDCARD = create(
+ "*/*", (Charset) null);
+
+ // defaults
+ public static final ContentType DEFAULT_TEXT = TEXT_PLAIN;
+ public static final ContentType DEFAULT_BINARY = APPLICATION_OCTET_STREAM;
+
+ private final String mimeType;
+ private final Charset charset;
+ private final NameValuePair[] params;
+
+ ContentType(
+ final String mimeType,
+ final Charset charset) {
+ this.mimeType = mimeType;
+ this.charset = charset;
+ this.params = null;
+ }
+
+ ContentType(
+ final String mimeType,
+ final NameValuePair[] params) throws UnsupportedCharsetException {
+ this.mimeType = mimeType;
+ this.params = params;
+ final String s = getParameter("charset");
+ this.charset = !TextUtils.isBlank(s) ? Charset.forName(s) : null;
+ }
+
+ public String getMimeType() {
+ return this.mimeType;
+ }
+
+ public Charset getCharset() {
+ return this.charset;
+ }
+
+ /**
+ * @since 4.3
+ */
+ public String getParameter(final String name) {
+ Args.notEmpty(name, "Parameter name");
+ if (this.params == null) {
+ return null;
+ }
+ for (final NameValuePair param: this.params) {
+ if (param.getName().equalsIgnoreCase(name)) {
+ return param.getValue();
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Generates textual representation of this content type which can be used as the value
+ * of a Content-Type header.
+ */
+ @Override
+ public String toString() {
+ final CharArrayBuffer buf = new CharArrayBuffer(64);
+ buf.append(this.mimeType);
+ if (this.params != null) {
+ buf.append("; ");
+ BasicHeaderValueFormatter.INSTANCE.formatParameters(buf, this.params, false);
+ } else if (this.charset != null) {
+ buf.append("; charset=");
+ buf.append(this.charset.name());
+ }
+ return buf.toString();
+ }
+
+ private static boolean valid(final String s) {
+ for (int i = 0; i < s.length(); i++) {
+ final char ch = s.charAt(i);
+ if (ch == '"' || ch == ',' || ch == ';') {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Creates a new instance of {@link ContentType}.
+ *
+ * @param mimeType MIME type. It may not be null or empty. It may not contain
+ * characters <">, <;>, <,> reserved by the HTTP specification.
+ * @param charset charset.
+ * @return content type
+ */
+ public static ContentType create(final String mimeType, final Charset charset) {
+ final String type = Args.notBlank(mimeType, "MIME type").toLowerCase(Locale.US);
+ Args.check(valid(type), "MIME type may not contain reserved characters");
+ return new ContentType(type, charset);
+ }
+
+ /**
+ * Creates a new instance of {@link ContentType} without a charset.
+ *
+ * @param mimeType MIME type. It may not be null or empty. It may not contain
+ * characters <">, <;>, <,> reserved by the HTTP specification.
+ * @return content type
+ */
+ public static ContentType create(final String mimeType) {
+ return new ContentType(mimeType, (Charset) null);
+ }
+
+ /**
+ * Creates a new instance of {@link ContentType}.
+ *
+ * @param mimeType MIME type. It may not be null or empty. It may not contain
+ * characters <">, <;>, <,> reserved by the HTTP specification.
+ * @param charset charset. It may not contain characters <">, <;>, <,> reserved by the HTTP
+ * specification. This parameter is optional.
+ * @return content type
+ * @throws UnsupportedCharsetException Thrown when the named charset is not available in
+ * this instance of the Java virtual machine
+ */
+ public static ContentType create(
+ final String mimeType, final String charset) throws UnsupportedCharsetException {
+ return create(mimeType, !TextUtils.isBlank(charset) ? Charset.forName(charset) : null);
+ }
+
+ private static ContentType create(final HeaderElement helem) {
+ final String mimeType = helem.getName();
+ final NameValuePair[] params = helem.getParameters();
+ return new ContentType(mimeType, params != null && params.length > 0 ? params : null);
+ }
+
+ /**
+ * Parses textual representation of Content-Type value.
+ *
+ * @param s text
+ * @return content type
+ * @throws ParseException if the given text does not represent a valid
+ * Content-Type value.
+ * @throws UnsupportedCharsetException Thrown when the named charset is not available in
+ * this instance of the Java virtual machine
+ */
+ public static ContentType parse(
+ final String s) throws ParseException, UnsupportedCharsetException {
+ Args.notNull(s, "Content type");
+ final CharArrayBuffer buf = new CharArrayBuffer(s.length());
+ buf.append(s);
+ final ParserCursor cursor = new ParserCursor(0, s.length());
+ final HeaderElement[] elements = BasicHeaderValueParser.INSTANCE.parseElements(buf, cursor);
+ if (elements.length > 0) {
+ return create(elements[0]);
+ } else {
+ throw new ParseException("Invalid content type: " + s);
+ }
+ }
+
+ /**
+ * Extracts Content-Type value from {@link HttpEntity} exactly as
+ * specified by the Content-Type header of the entity. Returns null
+ * if not specified.
+ *
+ * @param entity HTTP entity
+ * @return content type
+ * @throws ParseException if the given text does not represent a valid
+ * Content-Type value.
+ * @throws UnsupportedCharsetException Thrown when the named charset is not available in
+ * this instance of the Java virtual machine
+ */
+ public static ContentType get(
+ final HttpEntity entity) throws ParseException, UnsupportedCharsetException {
+ if (entity == null) {
+ return null;
+ }
+ final Header header = entity.getContentType();
+ if (header != null) {
+ final HeaderElement[] elements = header.getElements();
+ if (elements.length > 0) {
+ return create(elements[0]);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Extracts Content-Type value from {@link HttpEntity} or returns the default value
+ * {@link #DEFAULT_TEXT} if not explicitly specified.
+ *
+ * @param entity HTTP entity
+ * @return content type
+ * @throws ParseException if the given text does not represent a valid
+ * Content-Type value.
+ * @throws UnsupportedCharsetException Thrown when the named charset is not available in
+ * this instance of the Java virtual machine
+ */
+ public static ContentType getOrDefault(
+ final HttpEntity entity) throws ParseException, UnsupportedCharsetException {
+ final ContentType contentType = get(entity);
+ return contentType != null ? contentType : DEFAULT_TEXT;
+ }
+
+ /**
+ * Creates a new instance with this MIME type and the given Charset.
+ *
+ * @param charset charset
+ * @return a new instance with this MIME type and the given Charset.
+ * @since 4.3
+ */
+ public ContentType withCharset(final Charset charset) {
+ return create(this.getMimeType(), charset);
+ }
+
+ /**
+ * Creates a new instance with this MIME type and the given Charset name.
+ *
+ * @param charset name
+ * @return a new instance with this MIME type and the given Charset name.
+ * @throws UnsupportedCharsetException Thrown when the named charset is not available in
+ * this instance of the Java virtual machine
+ * @since 4.3
+ */
+ public ContentType withCharset(final String charset) {
+ return create(this.getMimeType(), charset);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/EntityTemplate.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/EntityTemplate.java
new file mode 100644
index 000000000..8e5a79431
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/EntityTemplate.java
@@ -0,0 +1,76 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Entity that delegates the process of content generation
+ * to a {@link ContentProducer}.
+ *
+ * @since 4.0
+ */
+public class EntityTemplate extends AbstractHttpEntity {
+
+ private final ContentProducer contentproducer;
+
+ public EntityTemplate(final ContentProducer contentproducer) {
+ super();
+ this.contentproducer = Args.notNull(contentproducer, "Content producer");
+ }
+
+ public long getContentLength() {
+ return -1;
+ }
+
+ public InputStream getContent() throws IOException {
+ final ByteArrayOutputStream buf = new ByteArrayOutputStream();
+ writeTo(buf);
+ return new ByteArrayInputStream(buf.toByteArray());
+ }
+
+ public boolean isRepeatable() {
+ return true;
+ }
+
+ public void writeTo(final OutputStream outstream) throws IOException {
+ Args.notNull(outstream, "Output stream");
+ this.contentproducer.writeTo(outstream);
+ }
+
+ public boolean isStreaming() {
+ return false;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/FileEntity.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/FileEntity.java
new file mode 100644
index 000000000..8801d3733
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/FileEntity.java
@@ -0,0 +1,121 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * A self contained, repeatable entity that obtains its content from a file.
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class FileEntity extends AbstractHttpEntity implements Cloneable {
+
+ protected final File file;
+
+ /**
+ * @deprecated (4.1.3) {@link #FileEntity(File, ContentType)}
+ */
+ @Deprecated
+ public FileEntity(final File file, final String contentType) {
+ super();
+ this.file = Args.notNull(file, "File");
+ setContentType(contentType);
+ }
+
+ /**
+ * @since 4.2
+ */
+ public FileEntity(final File file, final ContentType contentType) {
+ super();
+ this.file = Args.notNull(file, "File");
+ if (contentType != null) {
+ setContentType(contentType.toString());
+ }
+ }
+
+ /**
+ * @since 4.2
+ */
+ public FileEntity(final File file) {
+ super();
+ this.file = Args.notNull(file, "File");
+ }
+
+ public boolean isRepeatable() {
+ return true;
+ }
+
+ public long getContentLength() {
+ return this.file.length();
+ }
+
+ public InputStream getContent() throws IOException {
+ return new FileInputStream(this.file);
+ }
+
+ public void writeTo(final OutputStream outstream) throws IOException {
+ Args.notNull(outstream, "Output stream");
+ final InputStream instream = new FileInputStream(this.file);
+ try {
+ final byte[] tmp = new byte[OUTPUT_BUFFER_SIZE];
+ int l;
+ while ((l = instream.read(tmp)) != -1) {
+ outstream.write(tmp, 0, l);
+ }
+ outstream.flush();
+ } finally {
+ instream.close();
+ }
+ }
+
+ /**
+ * Tells that this entity is not streaming.
+ *
+ * @return false
+ */
+ public boolean isStreaming() {
+ return false;
+ }
+
+ @Override
+ public Object clone() throws CloneNotSupportedException {
+ // File instance is considered immutable
+ // No need to make a copy of it
+ return super.clone();
+ }
+
+} // class FileEntity
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/HttpEntityWrapper.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/HttpEntityWrapper.java
new file mode 100644
index 000000000..77b1245f4
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/HttpEntityWrapper.java
@@ -0,0 +1,105 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Base class for wrapping entities.
+ * Keeps a {@link #wrappedEntity wrappedEntity} and delegates all
+ * calls to it. Implementations of wrapping entities can derive
+ * from this class and need to override only those methods that
+ * should not be delegated to the wrapped entity.
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class HttpEntityWrapper implements HttpEntity {
+
+ /** The wrapped entity. */
+ protected HttpEntity wrappedEntity;
+
+ /**
+ * Creates a new entity wrapper.
+ */
+ public HttpEntityWrapper(final HttpEntity wrappedEntity) {
+ super();
+ this.wrappedEntity = Args.notNull(wrappedEntity, "Wrapped entity");
+ } // constructor
+
+ public boolean isRepeatable() {
+ return wrappedEntity.isRepeatable();
+ }
+
+ public boolean isChunked() {
+ return wrappedEntity.isChunked();
+ }
+
+ public long getContentLength() {
+ return wrappedEntity.getContentLength();
+ }
+
+ public Header getContentType() {
+ return wrappedEntity.getContentType();
+ }
+
+ public Header getContentEncoding() {
+ return wrappedEntity.getContentEncoding();
+ }
+
+ public InputStream getContent()
+ throws IOException {
+ return wrappedEntity.getContent();
+ }
+
+ public void writeTo(final OutputStream outstream)
+ throws IOException {
+ wrappedEntity.writeTo(outstream);
+ }
+
+ public boolean isStreaming() {
+ return wrappedEntity.isStreaming();
+ }
+
+ /**
+ * @deprecated (4.1) Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that;
+ * otherwise call {@link #writeTo(OutputStream)} which is required to free the resources.
+ */
+ @Deprecated
+ public void consumeContent() throws IOException {
+ wrappedEntity.consumeContent();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/InputStreamEntity.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/InputStreamEntity.java
new file mode 100644
index 000000000..8a53ef68c
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/InputStreamEntity.java
@@ -0,0 +1,155 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * A streamed, non-repeatable entity that obtains its content from
+ * an {@link InputStream}.
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class InputStreamEntity extends AbstractHttpEntity {
+
+ private final InputStream content;
+ private final long length;
+
+ /**
+ * Creates an entity with an unknown length.
+ * Equivalent to {@code new InputStreamEntity(instream, -1)}.
+ *
+ * @param instream input stream
+ * @throws IllegalArgumentException if {@code instream} is {@code null}
+ * @since 4.3
+ */
+ public InputStreamEntity(final InputStream instream) {
+ this(instream, -1);
+ }
+
+ /**
+ * Creates an entity with a specified content length.
+ *
+ * @param instream input stream
+ * @param length of the input stream, {@code -1} if unknown
+ * @throws IllegalArgumentException if {@code instream} is {@code null}
+ */
+ public InputStreamEntity(final InputStream instream, final long length) {
+ this(instream, length, null);
+ }
+
+ /**
+ * Creates an entity with a content type and unknown length.
+ * Equivalent to {@code new InputStreamEntity(instream, -1, contentType)}.
+ *
+ * @param instream input stream
+ * @param contentType content type
+ * @throws IllegalArgumentException if {@code instream} is {@code null}
+ * @since 4.3
+ */
+ public InputStreamEntity(final InputStream instream, final ContentType contentType) {
+ this(instream, -1, contentType);
+ }
+
+ /**
+ * @param instream input stream
+ * @param length of the input stream, {@code -1} if unknown
+ * @param contentType for specifying the {@code Content-Type} header, may be {@code null}
+ * @throws IllegalArgumentException if {@code instream} is {@code null}
+ * @since 4.2
+ */
+ public InputStreamEntity(final InputStream instream, final long length, final ContentType contentType) {
+ super();
+ this.content = Args.notNull(instream, "Source input stream");
+ this.length = length;
+ if (contentType != null) {
+ setContentType(contentType.toString());
+ }
+ }
+
+ public boolean isRepeatable() {
+ return false;
+ }
+
+ /**
+ * @return the content length or {@code -1} if unknown
+ */
+ public long getContentLength() {
+ return this.length;
+ }
+
+ public InputStream getContent() throws IOException {
+ return this.content;
+ }
+
+ /**
+ * Writes bytes from the {@code InputStream} this entity was constructed
+ * with to an {@code OutputStream}. The content length
+ * determines how many bytes are written. If the length is unknown ({@code -1}), the
+ * stream will be completely consumed (to the end of the stream).
+ *
+ */
+ public void writeTo(final OutputStream outstream) throws IOException {
+ Args.notNull(outstream, "Output stream");
+ final InputStream instream = this.content;
+ try {
+ final byte[] buffer = new byte[OUTPUT_BUFFER_SIZE];
+ int l;
+ if (this.length < 0) {
+ // consume until EOF
+ while ((l = instream.read(buffer)) != -1) {
+ outstream.write(buffer, 0, l);
+ }
+ } else {
+ // consume no more than length
+ long remaining = this.length;
+ while (remaining > 0) {
+ l = instream.read(buffer, 0, (int)Math.min(OUTPUT_BUFFER_SIZE, remaining));
+ if (l == -1) {
+ break;
+ }
+ outstream.write(buffer, 0, l);
+ remaining -= l;
+ }
+ }
+ } finally {
+ instream.close();
+ }
+ }
+
+ public boolean isStreaming() {
+ return true;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/SerializableEntity.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/SerializableEntity.java
new file mode 100644
index 000000000..f5e125309
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/SerializableEntity.java
@@ -0,0 +1,126 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+import java.io.Serializable;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * A streamed entity that obtains its content from a {@link Serializable}.
+ * The content obtained from the {@link Serializable} instance can
+ * optionally be buffered in a byte array in order to make the
+ * entity self-contained and repeatable.
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class SerializableEntity extends AbstractHttpEntity {
+
+ private byte[] objSer;
+
+ private Serializable objRef;
+
+ /**
+ * Creates new instance of this class.
+ *
+ * @param ser input
+ * @param bufferize tells whether the content should be
+ * stored in an internal buffer
+ * @throws IOException in case of an I/O error
+ */
+ public SerializableEntity(final Serializable ser, final boolean bufferize) throws IOException {
+ super();
+ Args.notNull(ser, "Source object");
+ if (bufferize) {
+ createBytes(ser);
+ } else {
+ this.objRef = ser;
+ }
+ }
+
+ /**
+ * @since 4.3
+ */
+ public SerializableEntity(final Serializable ser) {
+ super();
+ Args.notNull(ser, "Source object");
+ this.objRef = ser;
+ }
+
+ private void createBytes(final Serializable ser) throws IOException {
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ final ObjectOutputStream out = new ObjectOutputStream(baos);
+ out.writeObject(ser);
+ out.flush();
+ this.objSer = baos.toByteArray();
+ }
+
+ public InputStream getContent() throws IOException, IllegalStateException {
+ if (this.objSer == null) {
+ createBytes(this.objRef);
+ }
+ return new ByteArrayInputStream(this.objSer);
+ }
+
+ public long getContentLength() {
+ if (this.objSer == null) {
+ return -1;
+ } else {
+ return this.objSer.length;
+ }
+ }
+
+ public boolean isRepeatable() {
+ return true;
+ }
+
+ public boolean isStreaming() {
+ return this.objSer == null;
+ }
+
+ public void writeTo(final OutputStream outstream) throws IOException {
+ Args.notNull(outstream, "Output stream");
+ if (this.objSer == null) {
+ final ObjectOutputStream out = new ObjectOutputStream(outstream);
+ out.writeObject(this.objRef);
+ out.flush();
+ } else {
+ outstream.write(this.objSer);
+ outstream.flush();
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/StringEntity.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/StringEntity.java
new file mode 100644
index 000000000..bf4889119
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/StringEntity.java
@@ -0,0 +1,188 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.nio.charset.Charset;
+import java.nio.charset.UnsupportedCharsetException;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * A self contained, repeatable entity that obtains its content from
+ * a {@link String}.
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class StringEntity extends AbstractHttpEntity implements Cloneable {
+
+ protected final byte[] content;
+
+ /**
+ * Creates a StringEntity with the specified content and content type.
+ *
+ * @param string content to be used. Not {@code null}.
+ * @param contentType content type to be used. May be {@code null}, in which case the default
+ * MIME type {@link ContentType#TEXT_PLAIN} is assumed.
+ *
+ * @throws IllegalArgumentException if the string parameter is null
+ * @throws UnsupportedCharsetException Thrown when the named charset is not available in
+ * this instance of the Java virtual machine
+ * @since 4.2
+ */
+ public StringEntity(final String string, final ContentType contentType) throws UnsupportedCharsetException {
+ super();
+ Args.notNull(string, "Source string");
+ Charset charset = contentType != null ? contentType.getCharset() : null;
+ if (charset == null) {
+ charset = HTTP.DEF_CONTENT_CHARSET;
+ }
+ try {
+ this.content = string.getBytes(charset.name());
+ } catch (final UnsupportedEncodingException ex) {
+ // should never happen
+ throw new UnsupportedCharsetException(charset.name());
+ }
+ if (contentType != null) {
+ setContentType(contentType.toString());
+ }
+ }
+
+ /**
+ * Creates a StringEntity with the specified content, MIME type and charset
+ *
+ * @param string content to be used. Not {@code null}.
+ * @param mimeType MIME type to be used. May be {@code null}, in which case the default
+ * is {@link HTTP#PLAIN_TEXT_TYPE} i.e. "text/plain"
+ * @param charset character set to be used. May be {@code null}, in which case the default
+ * is {@link HTTP#DEF_CONTENT_CHARSET} i.e. "ISO-8859-1"
+ * @throws UnsupportedEncodingException If the named charset is not supported.
+ *
+ * @since 4.1
+ * @throws IllegalArgumentException if the string parameter is null
+ *
+ * @deprecated (4.1.3) use {@link #StringEntity(String, ContentType)}
+ */
+ @Deprecated
+ public StringEntity(
+ final String string, final String mimeType, final String charset) throws UnsupportedEncodingException {
+ super();
+ Args.notNull(string, "Source string");
+ final String mt = mimeType != null ? mimeType : HTTP.PLAIN_TEXT_TYPE;
+ final String cs = charset != null ? charset :HTTP.DEFAULT_CONTENT_CHARSET;
+ this.content = string.getBytes(cs);
+ setContentType(mt + HTTP.CHARSET_PARAM + cs);
+ }
+
+ /**
+ * Creates a StringEntity with the specified content and charset. The MIME type defaults
+ * to "text/plain".
+ *
+ * @param string content to be used. Not {@code null}.
+ * @param charset character set to be used. May be {@code null}, in which case the default
+ * is {@link HTTP#DEF_CONTENT_CHARSET} is assumed
+ *
+ * @throws IllegalArgumentException if the string parameter is null
+ * @throws UnsupportedCharsetException Thrown when the named charset is not available in
+ * this instance of the Java virtual machine
+ */
+ public StringEntity(final String string, final String charset)
+ throws UnsupportedCharsetException {
+ this(string, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), charset));
+ }
+
+ /**
+ * Creates a StringEntity with the specified content and charset. The MIME type defaults
+ * to "text/plain".
+ *
+ * @param string content to be used. Not {@code null}.
+ * @param charset character set to be used. May be {@code null}, in which case the default
+ * is {@link HTTP#DEF_CONTENT_CHARSET} is assumed
+ *
+ * @throws IllegalArgumentException if the string parameter is null
+ *
+ * @since 4.2
+ */
+ public StringEntity(final String string, final Charset charset) {
+ this(string, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), charset));
+ }
+
+ /**
+ * Creates a StringEntity with the specified content. The content type defaults to
+ * {@link ContentType#TEXT_PLAIN}.
+ *
+ * @param string content to be used. Not {@code null}.
+ *
+ * @throws IllegalArgumentException if the string parameter is null
+ * @throws UnsupportedEncodingException if the default HTTP charset is not supported.
+ */
+ public StringEntity(final String string)
+ throws UnsupportedEncodingException {
+ this(string, ContentType.DEFAULT_TEXT);
+ }
+
+ public boolean isRepeatable() {
+ return true;
+ }
+
+ public long getContentLength() {
+ return this.content.length;
+ }
+
+ public InputStream getContent() throws IOException {
+ return new ByteArrayInputStream(this.content);
+ }
+
+ public void writeTo(final OutputStream outstream) throws IOException {
+ Args.notNull(outstream, "Output stream");
+ outstream.write(this.content);
+ outstream.flush();
+ }
+
+ /**
+ * Tells that this entity is not streaming.
+ *
+ * @return false
+ */
+ public boolean isStreaming() {
+ return false;
+ }
+
+ @Override
+ public Object clone() throws CloneNotSupportedException {
+ return super.clone();
+ }
+
+} // class StringEntity
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/AbstractMultipartForm.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/AbstractMultipartForm.java
new file mode 100644
index 000000000..ade6bfe4b
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/AbstractMultipartForm.java
@@ -0,0 +1,211 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.Charset;
+import java.util.List;
+
+import ch.boye.httpclientandroidlib.entity.mime.content.ContentBody;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.ByteArrayBuffer;
+
+/**
+ * HttpMultipart represents a collection of MIME multipart encoded content bodies. This class is
+ * capable of operating either in the strict (RFC 822, RFC 2045, RFC 2046 compliant) or
+ * the browser compatible modes.
+ *
+ * @since 4.3
+ */
+abstract class AbstractMultipartForm {
+
+ private static ByteArrayBuffer encode(
+ final Charset charset, final String string) {
+ final ByteBuffer encoded = charset.encode(CharBuffer.wrap(string));
+ final ByteArrayBuffer bab = new ByteArrayBuffer(encoded.remaining());
+ bab.append(encoded.array(), encoded.position(), encoded.remaining());
+ return bab;
+ }
+
+ private static void writeBytes(
+ final ByteArrayBuffer b, final OutputStream out) throws IOException {
+ out.write(b.buffer(), 0, b.length());
+ }
+
+ private static void writeBytes(
+ final String s, final Charset charset, final OutputStream out) throws IOException {
+ final ByteArrayBuffer b = encode(charset, s);
+ writeBytes(b, out);
+ }
+
+ private static void writeBytes(
+ final String s, final OutputStream out) throws IOException {
+ final ByteArrayBuffer b = encode(MIME.DEFAULT_CHARSET, s);
+ writeBytes(b, out);
+ }
+
+ protected static void writeField(
+ final MinimalField field, final OutputStream out) throws IOException {
+ writeBytes(field.getName(), out);
+ writeBytes(FIELD_SEP, out);
+ writeBytes(field.getBody(), out);
+ writeBytes(CR_LF, out);
+ }
+
+ protected static void writeField(
+ final MinimalField field, final Charset charset, final OutputStream out) throws IOException {
+ writeBytes(field.getName(), charset, out);
+ writeBytes(FIELD_SEP, out);
+ writeBytes(field.getBody(), charset, out);
+ writeBytes(CR_LF, out);
+ }
+
+ private static final ByteArrayBuffer FIELD_SEP = encode(MIME.DEFAULT_CHARSET, ": ");
+ private static final ByteArrayBuffer CR_LF = encode(MIME.DEFAULT_CHARSET, "\r\n");
+ private static final ByteArrayBuffer TWO_DASHES = encode(MIME.DEFAULT_CHARSET, "--");
+
+ private final String subType;
+ protected final Charset charset;
+ private final String boundary;
+
+ /**
+ * Creates an instance with the specified settings.
+ *
+ * @param subType MIME subtype - must not be {@code null}
+ * @param charset the character set to use. May be {@code null}, in which case {@link MIME#DEFAULT_CHARSET} - i.e. US-ASCII - is used.
+ * @param boundary to use - must not be {@code null}
+ * @throws IllegalArgumentException if charset is null or boundary is null
+ */
+ public AbstractMultipartForm(final String subType, final Charset charset, final String boundary) {
+ super();
+ Args.notNull(subType, "Multipart subtype");
+ Args.notNull(boundary, "Multipart boundary");
+ this.subType = subType;
+ this.charset = charset != null ? charset : MIME.DEFAULT_CHARSET;
+ this.boundary = boundary;
+ }
+
+ public AbstractMultipartForm(final String subType, final String boundary) {
+ this(subType, null, boundary);
+ }
+
+ public String getSubType() {
+ return this.subType;
+ }
+
+ public Charset getCharset() {
+ return this.charset;
+ }
+
+ public abstract List getBodyParts();
+
+ public String getBoundary() {
+ return this.boundary;
+ }
+
+ void doWriteTo(
+ final OutputStream out,
+ final boolean writeContent) throws IOException {
+
+ final ByteArrayBuffer boundary = encode(this.charset, getBoundary());
+ for (final FormBodyPart part: getBodyParts()) {
+ writeBytes(TWO_DASHES, out);
+ writeBytes(boundary, out);
+ writeBytes(CR_LF, out);
+
+ formatMultipartHeader(part, out);
+
+ writeBytes(CR_LF, out);
+
+ if (writeContent) {
+ part.getBody().writeTo(out);
+ }
+ writeBytes(CR_LF, out);
+ }
+ writeBytes(TWO_DASHES, out);
+ writeBytes(boundary, out);
+ writeBytes(TWO_DASHES, out);
+ writeBytes(CR_LF, out);
+ }
+
+ /**
+ * Write the multipart header fields; depends on the style.
+ */
+ protected abstract void formatMultipartHeader(
+ final FormBodyPart part,
+ final OutputStream out) throws IOException;
+
+ /**
+ * Writes out the content in the multipart/form encoding. This method
+ * produces slightly different formatting depending on its compatibility
+ * mode.
+ */
+ public void writeTo(final OutputStream out) throws IOException {
+ doWriteTo(out, true);
+ }
+
+ /**
+ * Determines the total length of the multipart content (content length of
+ * individual parts plus that of extra elements required to delimit the parts
+ * from one another). If any of the @{link BodyPart}s contained in this object
+ * is of a streaming entity of unknown length the total length is also unknown.
+ *
+ * This method buffers only a small amount of data in order to determine the
+ * total length of the entire entity. The content of individual parts is not
+ * buffered.
+ *
+ * @return total length of the multipart entity if known, -1
+ * otherwise.
+ */
+ public long getTotalLength() {
+ long contentLen = 0;
+ for (final FormBodyPart part: getBodyParts()) {
+ final ContentBody body = part.getBody();
+ final long len = body.getContentLength();
+ if (len >= 0) {
+ contentLen += len;
+ } else {
+ return -1;
+ }
+ }
+ final ByteArrayOutputStream out = new ByteArrayOutputStream();
+ try {
+ doWriteTo(out, false);
+ final byte[] extra = out.toByteArray();
+ return contentLen + extra.length;
+ } catch (final IOException ex) {
+ // Should never happen
+ return -1;
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/FormBodyPart.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/FormBodyPart.java
new file mode 100644
index 000000000..a3d2c0954
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/FormBodyPart.java
@@ -0,0 +1,116 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime;
+
+import ch.boye.httpclientandroidlib.entity.ContentType;
+import ch.boye.httpclientandroidlib.entity.mime.content.AbstractContentBody;
+import ch.boye.httpclientandroidlib.entity.mime.content.ContentBody;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * FormBodyPart class represents a content body that can be used as a part of multipart encoded
+ * entities. This class automatically populates the header with standard fields based on
+ * the content description of the enclosed body.
+ *
+ * @since 4.0
+ */
+public class FormBodyPart {
+
+ private final String name;
+ private final Header header;
+
+ private final ContentBody body;
+
+ public FormBodyPart(final String name, final ContentBody body) {
+ super();
+ Args.notNull(name, "Name");
+ Args.notNull(body, "Body");
+ this.name = name;
+ this.body = body;
+ this.header = new Header();
+
+ generateContentDisp(body);
+ generateContentType(body);
+ generateTransferEncoding(body);
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public ContentBody getBody() {
+ return this.body;
+ }
+
+ public Header getHeader() {
+ return this.header;
+ }
+
+ public void addField(final String name, final String value) {
+ Args.notNull(name, "Field name");
+ this.header.addField(new MinimalField(name, value));
+ }
+
+ protected void generateContentDisp(final ContentBody body) {
+ final StringBuilder buffer = new StringBuilder();
+ buffer.append("form-data; name=\"");
+ buffer.append(getName());
+ buffer.append("\"");
+ if (body.getFilename() != null) {
+ buffer.append("; filename=\"");
+ buffer.append(body.getFilename());
+ buffer.append("\"");
+ }
+ addField(MIME.CONTENT_DISPOSITION, buffer.toString());
+ }
+
+ protected void generateContentType(final ContentBody body) {
+ final ContentType contentType;
+ if (body instanceof AbstractContentBody) {
+ contentType = ((AbstractContentBody) body).getContentType();
+ } else {
+ contentType = null;
+ }
+ if (contentType != null) {
+ addField(MIME.CONTENT_TYPE, contentType.toString());
+ } else {
+ final StringBuilder buffer = new StringBuilder();
+ buffer.append(body.getMimeType()); // MimeType cannot be null
+ if (body.getCharset() != null) { // charset may legitimately be null
+ buffer.append("; charset=");
+ buffer.append(body.getCharset());
+ }
+ addField(MIME.CONTENT_TYPE, buffer.toString());
+ }
+ }
+
+ protected void generateTransferEncoding(final ContentBody body) {
+ addField(MIME.CONTENT_TRANSFER_ENC, body.getTransferEncoding()); // TE cannot be null
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/Header.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/Header.java
new file mode 100644
index 000000000..15d70acc9
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/Header.java
@@ -0,0 +1,144 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+/**
+ * The header of an entity (see RFC 2045).
+ */
+public class Header implements Iterable {
+
+ private final List fields;
+ private final Map> fieldMap;
+
+ public Header() {
+ super();
+ this.fields = new LinkedList();
+ this.fieldMap = new HashMap>();
+ }
+
+ public void addField(final MinimalField field) {
+ if (field == null) {
+ return;
+ }
+ final String key = field.getName().toLowerCase(Locale.ENGLISH);
+ List values = this.fieldMap.get(key);
+ if (values == null) {
+ values = new LinkedList();
+ this.fieldMap.put(key, values);
+ }
+ values.add(field);
+ this.fields.add(field);
+ }
+
+ public List getFields() {
+ return new ArrayList(this.fields);
+ }
+
+ public MinimalField getField(final String name) {
+ if (name == null) {
+ return null;
+ }
+ final String key = name.toLowerCase(Locale.ENGLISH);
+ final List list = this.fieldMap.get(key);
+ if (list != null && !list.isEmpty()) {
+ return list.get(0);
+ }
+ return null;
+ }
+
+ public List getFields(final String name) {
+ if (name == null) {
+ return null;
+ }
+ final String key = name.toLowerCase(Locale.ENGLISH);
+ final List list = this.fieldMap.get(key);
+ if (list == null || list.isEmpty()) {
+ return Collections.emptyList();
+ } else {
+ return new ArrayList(list);
+ }
+ }
+
+ public int removeFields(final String name) {
+ if (name == null) {
+ return 0;
+ }
+ final String key = name.toLowerCase(Locale.ENGLISH);
+ final List removed = fieldMap.remove(key);
+ if (removed == null || removed.isEmpty()) {
+ return 0;
+ }
+ this.fields.removeAll(removed);
+ return removed.size();
+ }
+
+ public void setField(final MinimalField field) {
+ if (field == null) {
+ return;
+ }
+ final String key = field.getName().toLowerCase(Locale.ENGLISH);
+ final List list = fieldMap.get(key);
+ if (list == null || list.isEmpty()) {
+ addField(field);
+ return;
+ }
+ list.clear();
+ list.add(field);
+ int firstOccurrence = -1;
+ int index = 0;
+ for (final Iterator it = this.fields.iterator(); it.hasNext(); index++) {
+ final MinimalField f = it.next();
+ if (f.getName().equalsIgnoreCase(field.getName())) {
+ it.remove();
+ if (firstOccurrence == -1) {
+ firstOccurrence = index;
+ }
+ }
+ }
+ this.fields.add(firstOccurrence, field);
+ }
+
+ public Iterator iterator() {
+ return Collections.unmodifiableList(fields).iterator();
+ }
+
+ @Override
+ public String toString() {
+ return this.fields.toString();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/HttpBrowserCompatibleMultipart.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/HttpBrowserCompatibleMultipart.java
new file mode 100644
index 000000000..dfc0a657e
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/HttpBrowserCompatibleMultipart.java
@@ -0,0 +1,79 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.charset.Charset;
+import java.util.List;
+
+/**
+ * HttpBrowserCompatibleMultipart represents a collection of MIME multipart encoded
+ * content bodies. This class is emulates browser compatibility, e.g. IE 5 or earlier.
+ *
+ * @since 4.3
+ */
+class HttpBrowserCompatibleMultipart extends AbstractMultipartForm {
+
+ private final List parts;
+
+ public HttpBrowserCompatibleMultipart(
+ final String subType,
+ final Charset charset,
+ final String boundary,
+ final List parts) {
+ super(subType, charset, boundary);
+ this.parts = parts;
+ }
+
+ @Override
+ public List getBodyParts() {
+ return this.parts;
+ }
+
+ /**
+ * Write the multipart header fields; depends on the style.
+ */
+ @Override
+ protected void formatMultipartHeader(
+ final FormBodyPart part,
+ final OutputStream out) throws IOException {
+ // For browser-compatible, only write Content-Disposition
+ // Use content charset
+ final Header header = part.getHeader();
+ final MinimalField cd = header.getField(MIME.CONTENT_DISPOSITION);
+ writeField(cd, this.charset, out);
+ final String filename = part.getBody().getFilename();
+ if (filename != null) {
+ final MinimalField ct = header.getField(MIME.CONTENT_TYPE);
+ writeField(ct, this.charset, out);
+ }
+
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/HttpMultipartMode.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/HttpMultipartMode.java
new file mode 100644
index 000000000..ab73e4983
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/HttpMultipartMode.java
@@ -0,0 +1,43 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime;
+
+/**
+ *
+ * @since 4.0
+ */
+public enum HttpMultipartMode {
+
+ /** RFC 822, RFC 2045, RFC 2046 compliant */
+ STRICT,
+ /** browser-compatible mode, i.e. only write Content-Disposition; use content charset */
+ BROWSER_COMPATIBLE,
+ /** RFC 6532 compliant */
+ RFC6532
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/HttpRFC6532Multipart.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/HttpRFC6532Multipart.java
new file mode 100644
index 000000000..634a12b23
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/HttpRFC6532Multipart.java
@@ -0,0 +1,72 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.charset.Charset;
+import java.util.List;
+
+/**
+ * HttpRFC6532Multipart represents a collection of MIME multipart encoded content bodies,
+ * implementing the strict (RFC 822, RFC 2045, RFC 2046 compliant) interpretation
+ * of the spec, with the exception of allowing UTF-8 headers, as per RFC6532.
+ *
+ * @since 4.3
+ */
+class HttpRFC6532Multipart extends AbstractMultipartForm {
+
+ private final List parts;
+
+ public HttpRFC6532Multipart(
+ final String subType,
+ final Charset charset,
+ final String boundary,
+ final List parts) {
+ super(subType, charset, boundary);
+ this.parts = parts;
+ }
+
+ @Override
+ public List getBodyParts() {
+ return this.parts;
+ }
+
+ @Override
+ protected void formatMultipartHeader(
+ final FormBodyPart part,
+ final OutputStream out) throws IOException {
+
+ // For RFC6532, we output all fields with UTF-8 encoding.
+ final Header header = part.getHeader();
+ for (final MinimalField field: header) {
+ writeField(field, MIME.UTF8_CHARSET, out);
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/HttpStrictMultipart.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/HttpStrictMultipart.java
new file mode 100644
index 000000000..d6e68c6e2
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/HttpStrictMultipart.java
@@ -0,0 +1,72 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.charset.Charset;
+import java.util.List;
+
+/**
+ * HttpStrictMultipart represents a collection of MIME multipart encoded content bodies,
+ * implementing the strict (RFC 822, RFC 2045, RFC 2046 compliant) interpretation
+ * of the spec.
+ *
+ * @since 4.3
+ */
+class HttpStrictMultipart extends AbstractMultipartForm {
+
+ private final List parts;
+
+ public HttpStrictMultipart(
+ final String subType,
+ final Charset charset,
+ final String boundary,
+ final List parts) {
+ super(subType, charset, boundary);
+ this.parts = parts;
+ }
+
+ @Override
+ public List getBodyParts() {
+ return this.parts;
+ }
+
+ @Override
+ protected void formatMultipartHeader(
+ final FormBodyPart part,
+ final OutputStream out) throws IOException {
+
+ // For strict, we output all fields with MIME-standard encoding.
+ final Header header = part.getHeader();
+ for (final MinimalField field: header) {
+ writeField(field, out);
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/MIME.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/MIME.java
new file mode 100644
index 000000000..d5896312d
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/MIME.java
@@ -0,0 +1,53 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime;
+
+import ch.boye.httpclientandroidlib.Consts;
+
+import java.nio.charset.Charset;
+
+/**
+ *
+ * @since 4.0
+ */
+public final class MIME {
+
+ public static final String CONTENT_TYPE = "Content-Type";
+ public static final String CONTENT_TRANSFER_ENC = "Content-Transfer-Encoding";
+ public static final String CONTENT_DISPOSITION = "Content-Disposition";
+
+ public static final String ENC_8BIT = "8bit";
+ public static final String ENC_BINARY = "binary";
+
+ /** The default character set to be used, i.e. "US-ASCII" */
+ public static final Charset DEFAULT_CHARSET = Consts.ASCII;
+
+ /** UTF-8 is used for RFC6532 */
+ public static final Charset UTF8_CHARSET = Consts.UTF_8;
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/MinimalField.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/MinimalField.java
new file mode 100644
index 000000000..35af51233
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/MinimalField.java
@@ -0,0 +1,63 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime;
+
+/**
+ * Minimal MIME field.
+ *
+ * @since 4.0
+ */
+public class MinimalField {
+
+ private final String name;
+ private final String value;
+
+ public MinimalField(final String name, final String value) {
+ super();
+ this.name = name;
+ this.value = value;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public String getBody() {
+ return this.value;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder buffer = new StringBuilder();
+ buffer.append(this.name);
+ buffer.append(": ");
+ buffer.append(this.value);
+ return buffer.toString();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/MultipartEntityBuilder.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/MultipartEntityBuilder.java
new file mode 100644
index 000000000..5074001d7
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/MultipartEntityBuilder.java
@@ -0,0 +1,207 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime;
+
+import java.io.File;
+import java.io.InputStream;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.entity.ContentType;
+import ch.boye.httpclientandroidlib.entity.mime.content.ByteArrayBody;
+import ch.boye.httpclientandroidlib.entity.mime.content.ContentBody;
+import ch.boye.httpclientandroidlib.entity.mime.content.FileBody;
+import ch.boye.httpclientandroidlib.entity.mime.content.InputStreamBody;
+import ch.boye.httpclientandroidlib.entity.mime.content.StringBody;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Builder for multipart {@link HttpEntity}s.
+ *
+ * @since 4.3
+ */
+public class MultipartEntityBuilder {
+
+ /**
+ * The pool of ASCII chars to be used for generating a multipart boundary.
+ */
+ private final static char[] MULTIPART_CHARS =
+ "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ .toCharArray();
+
+ private final static String DEFAULT_SUBTYPE = "form-data";
+
+ private String subType = DEFAULT_SUBTYPE;
+ private HttpMultipartMode mode = HttpMultipartMode.STRICT;
+ private String boundary = null;
+ private Charset charset = null;
+ private List bodyParts = null;
+
+ public static MultipartEntityBuilder create() {
+ return new MultipartEntityBuilder();
+ }
+
+ MultipartEntityBuilder() {
+ super();
+ }
+
+ public MultipartEntityBuilder setMode(final HttpMultipartMode mode) {
+ this.mode = mode;
+ return this;
+ }
+
+ public MultipartEntityBuilder setLaxMode() {
+ this.mode = HttpMultipartMode.BROWSER_COMPATIBLE;
+ return this;
+ }
+
+ public MultipartEntityBuilder setStrictMode() {
+ this.mode = HttpMultipartMode.STRICT;
+ return this;
+ }
+
+ public MultipartEntityBuilder setBoundary(final String boundary) {
+ this.boundary = boundary;
+ return this;
+ }
+
+ public MultipartEntityBuilder setCharset(final Charset charset) {
+ this.charset = charset;
+ return this;
+ }
+
+ MultipartEntityBuilder addPart(final FormBodyPart bodyPart) {
+ if (bodyPart == null) {
+ return this;
+ }
+ if (this.bodyParts == null) {
+ this.bodyParts = new ArrayList();
+ }
+ this.bodyParts.add(bodyPart);
+ return this;
+ }
+
+ public MultipartEntityBuilder addPart(final String name, final ContentBody contentBody) {
+ Args.notNull(name, "Name");
+ Args.notNull(contentBody, "Content body");
+ return addPart(new FormBodyPart(name, contentBody));
+ }
+
+ public MultipartEntityBuilder addTextBody(
+ final String name, final String text, final ContentType contentType) {
+ return addPart(name, new StringBody(text, contentType));
+ }
+
+ public MultipartEntityBuilder addTextBody(
+ final String name, final String text) {
+ return addTextBody(name, text, ContentType.DEFAULT_TEXT);
+ }
+
+ public MultipartEntityBuilder addBinaryBody(
+ final String name, final byte[] b, final ContentType contentType, final String filename) {
+ return addPart(name, new ByteArrayBody(b, contentType, filename));
+ }
+
+ public MultipartEntityBuilder addBinaryBody(
+ final String name, final byte[] b) {
+ return addBinaryBody(name, b, ContentType.DEFAULT_BINARY, null);
+ }
+
+ public MultipartEntityBuilder addBinaryBody(
+ final String name, final File file, final ContentType contentType, final String filename) {
+ return addPart(name, new FileBody(file, contentType, filename));
+ }
+
+ public MultipartEntityBuilder addBinaryBody(
+ final String name, final File file) {
+ return addBinaryBody(name, file, ContentType.DEFAULT_BINARY, file != null ? file.getName() : null);
+ }
+
+ public MultipartEntityBuilder addBinaryBody(
+ final String name, final InputStream stream, final ContentType contentType,
+ final String filename) {
+ return addPart(name, new InputStreamBody(stream, contentType, filename));
+ }
+
+ public MultipartEntityBuilder addBinaryBody(final String name, final InputStream stream) {
+ return addBinaryBody(name, stream, ContentType.DEFAULT_BINARY, null);
+ }
+
+ private String generateContentType(
+ final String boundary,
+ final Charset charset) {
+ final StringBuilder buffer = new StringBuilder();
+ buffer.append("multipart/form-data; boundary=");
+ buffer.append(boundary);
+ if (charset != null) {
+ buffer.append("; charset=");
+ buffer.append(charset.name());
+ }
+ return buffer.toString();
+ }
+
+ private String generateBoundary() {
+ final StringBuilder buffer = new StringBuilder();
+ final Random rand = new Random();
+ final int count = rand.nextInt(11) + 30; // a random size from 30 to 40
+ for (int i = 0; i < count; i++) {
+ buffer.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
+ }
+ return buffer.toString();
+ }
+
+ MultipartFormEntity buildEntity() {
+ final String st = subType != null ? subType : DEFAULT_SUBTYPE;
+ final Charset cs = charset;
+ final String b = boundary != null ? boundary : generateBoundary();
+ final List bps = bodyParts != null ? new ArrayList(bodyParts) :
+ Collections.emptyList();
+ final HttpMultipartMode m = mode != null ? mode : HttpMultipartMode.STRICT;
+ final AbstractMultipartForm form;
+ switch (m) {
+ case BROWSER_COMPATIBLE:
+ form = new HttpBrowserCompatibleMultipart(st, cs, b, bps);
+ break;
+ case RFC6532:
+ form = new HttpRFC6532Multipart(st, cs, b, bps);
+ break;
+ default:
+ form = new HttpStrictMultipart(st, cs, b, bps);
+ }
+ return new MultipartFormEntity(form, generateContentType(b, cs), form.getTotalLength());
+ }
+
+ public HttpEntity build() {
+ return buildEntity();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/MultipartFormEntity.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/MultipartFormEntity.java
new file mode 100644
index 000000000..9da2f4724
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/MultipartFormEntity.java
@@ -0,0 +1,100 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.message.BasicHeader;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+class MultipartFormEntity implements HttpEntity {
+
+ private final AbstractMultipartForm multipart;
+ private final Header contentType;
+ private final long contentLength;
+
+ MultipartFormEntity(
+ final AbstractMultipartForm multipart,
+ final String contentType,
+ final long contentLength) {
+ super();
+ this.multipart = multipart;
+ this.contentType = new BasicHeader(HTTP.CONTENT_TYPE, contentType);
+ this.contentLength = contentLength;
+ }
+
+ AbstractMultipartForm getMultipart() {
+ return this.multipart;
+ }
+
+ public boolean isRepeatable() {
+ return this.contentLength != -1;
+ }
+
+ public boolean isChunked() {
+ return !isRepeatable();
+ }
+
+ public boolean isStreaming() {
+ return !isRepeatable();
+ }
+
+ public long getContentLength() {
+ return this.contentLength;
+ }
+
+ public Header getContentType() {
+ return this.contentType;
+ }
+
+ public Header getContentEncoding() {
+ return null;
+ }
+
+ public void consumeContent()
+ throws IOException, UnsupportedOperationException{
+ if (isStreaming()) {
+ throw new UnsupportedOperationException(
+ "Streaming entity does not implement #consumeContent()");
+ }
+ }
+
+ public InputStream getContent() throws IOException {
+ throw new UnsupportedOperationException(
+ "Multipart form entity does not implement #getContent()");
+ }
+
+ public void writeTo(final OutputStream outstream) throws IOException {
+ this.multipart.writeTo(outstream);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/AbstractContentBody.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/AbstractContentBody.java
new file mode 100644
index 000000000..b6b58ad35
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/AbstractContentBody.java
@@ -0,0 +1,96 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime.content;
+
+import java.nio.charset.Charset;
+
+import ch.boye.httpclientandroidlib.entity.ContentType;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ *
+ * @since 4.0
+ */
+public abstract class AbstractContentBody implements ContentBody {
+
+ private final ContentType contentType;
+
+ /**
+ * @since 4.3
+ */
+ public AbstractContentBody(final ContentType contentType) {
+ super();
+ Args.notNull(contentType, "Content type");
+ this.contentType = contentType;
+ }
+
+ /**
+ * @deprecated (4.3) use {@link AbstractContentBody#AbstractContentBody(ContentType)}
+ */
+ @Deprecated
+ public AbstractContentBody(final String mimeType) {
+ this(ContentType.parse(mimeType));
+ }
+
+ /**
+ * @since 4.3
+ */
+ public ContentType getContentType() {
+ return this.contentType;
+ }
+
+ public String getMimeType() {
+ return this.contentType.getMimeType();
+ }
+
+ public String getMediaType() {
+ final String mimeType = this.contentType.getMimeType();
+ final int i = mimeType.indexOf('/');
+ if (i != -1) {
+ return mimeType.substring(0, i);
+ } else {
+ return mimeType;
+ }
+ }
+
+ public String getSubType() {
+ final String mimeType = this.contentType.getMimeType();
+ final int i = mimeType.indexOf('/');
+ if (i != -1) {
+ return mimeType.substring(i + 1);
+ } else {
+ return null;
+ }
+ }
+
+ public String getCharset() {
+ final Charset charset = this.contentType.getCharset();
+ return charset != null ? charset.name() : null;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/ByteArrayBody.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/ByteArrayBody.java
new file mode 100644
index 000000000..ea60fa047
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/ByteArrayBody.java
@@ -0,0 +1,111 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.entity.mime.content;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+import ch.boye.httpclientandroidlib.entity.ContentType;
+import ch.boye.httpclientandroidlib.entity.mime.MIME;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Binary body part backed by a byte array.
+ *
+ * @see ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder
+ *
+ * @since 4.1
+ */
+public class ByteArrayBody extends AbstractContentBody {
+
+ /**
+ * The contents of the file contained in this part.
+ */
+ private final byte[] data;
+
+ /**
+ * The name of the file contained in this part.
+ */
+ private final String filename;
+
+ /**
+ * Creates a new ByteArrayBody.
+ *
+ * @param data The contents of the file contained in this part.
+ * @param mimeType The MIME type of the file contained in this part.
+ * @param filename The name of the file contained in this part.
+ *
+ * @deprecated (4.3) use {@link ByteArrayBody#ByteArrayBody(byte[], ContentType, String)}
+ * or {@link ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder}
+ */
+ @Deprecated
+ public ByteArrayBody(final byte[] data, final String mimeType, final String filename) {
+ this(data, ContentType.create(mimeType), filename);
+ }
+
+ /**
+ * @since 4.3
+ */
+ public ByteArrayBody(final byte[] data, final ContentType contentType, final String filename) {
+ super(contentType);
+ Args.notNull(data, "byte[]");
+ this.data = data;
+ this.filename = filename;
+ }
+
+ /**
+ * Creates a new ByteArrayBody.
+ *
+ * @param data The contents of the file contained in this part.
+ * @param filename The name of the file contained in this part.
+ */
+ public ByteArrayBody(final byte[] data, final String filename) {
+ this(data, "application/octet-stream", filename);
+ }
+
+ public String getFilename() {
+ return filename;
+ }
+
+ public void writeTo(final OutputStream out) throws IOException {
+ out.write(data);
+ }
+
+ @Override
+ public String getCharset() {
+ return null;
+ }
+
+ public String getTransferEncoding() {
+ return MIME.ENC_BINARY;
+ }
+
+ public long getContentLength() {
+ return data.length;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/ContentBody.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/ContentBody.java
new file mode 100644
index 000000000..d62aaff54
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/ContentBody.java
@@ -0,0 +1,43 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime.content;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ *
+ * @since 4.0
+ */
+public interface ContentBody extends ContentDescriptor {
+
+ String getFilename();
+
+ void writeTo(OutputStream out) throws IOException;
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/ContentDescriptor.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/ContentDescriptor.java
new file mode 100644
index 000000000..87237ec23
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/ContentDescriptor.java
@@ -0,0 +1,89 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime.content;
+
+/**
+ * Represents common content properties.
+ */
+public interface ContentDescriptor {
+
+ /**
+ * Returns the body descriptors MIME type.
+ * @see #getMediaType()
+ * @see #getSubType()
+ * @return The MIME type, which has been parsed from the
+ * content-type definition. Must not be null, but
+ * "text/plain", if no content-type was specified.
+ */
+ String getMimeType();
+
+ /**
+ * Gets the defaulted MIME media type for this content.
+ * For example TEXT, IMAGE, MULTIPART
+ * @see #getMimeType()
+ * @return the MIME media type when content-type specified,
+ * otherwise the correct default (TEXT)
+ */
+ String getMediaType();
+
+ /**
+ * Gets the defaulted MIME sub type for this content.
+ * @see #getMimeType()
+ * @return the MIME media type when content-type is specified,
+ * otherwise the correct default (PLAIN)
+ */
+ String getSubType();
+
+ /**
+ *
The body descriptors character set, defaulted appropriately for the MIME type.
+ *
+ * For TEXT types, this will be defaulted to us-ascii.
+ * For other types, when the charset parameter is missing this property will be null.
+ *
+ * @return Character set, which has been parsed from the
+ * content-type definition. Not null for TEXT types, when unset will
+ * be set to default us-ascii. For other types, when unset,
+ * null will be returned.
+ */
+ String getCharset();
+
+ /**
+ * Returns the body descriptors transfer encoding.
+ * @return The transfer encoding. Must not be null, but "7bit",
+ * if no transfer-encoding was specified.
+ */
+ String getTransferEncoding();
+
+ /**
+ * Returns the body descriptors content-length.
+ * @return Content length, if known, or -1, to indicate the absence of a
+ * content-length header.
+ */
+ long getContentLength();
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/FileBody.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/FileBody.java
new file mode 100644
index 000000000..7641236a4
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/FileBody.java
@@ -0,0 +1,144 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime.content;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import ch.boye.httpclientandroidlib.entity.ContentType;
+import ch.boye.httpclientandroidlib.entity.mime.MIME;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Binary body part backed by a file.
+ *
+ * @see ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder
+ *
+ * @since 4.0
+ */
+public class FileBody extends AbstractContentBody {
+
+ private final File file;
+ private final String filename;
+
+ /**
+ * @since 4.1
+ *
+ * @deprecated (4.3) use {@link FileBody#FileBody(File, ContentType, String)}
+ * or {@link ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder}
+ */
+ @Deprecated
+ public FileBody(final File file,
+ final String filename,
+ final String mimeType,
+ final String charset) {
+ this(file, ContentType.create(mimeType, charset), filename);
+ }
+
+ /**
+ * @since 4.1
+ *
+ * @deprecated (4.3) use {@link FileBody#FileBody(File, ContentType)}
+ * or {@link ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder}
+ */
+ @Deprecated
+ public FileBody(final File file,
+ final String mimeType,
+ final String charset) {
+ this(file, null, mimeType, charset);
+ }
+
+ /**
+ * @deprecated (4.3) use {@link FileBody#FileBody(File, ContentType)}
+ * or {@link ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder}
+ */
+ @Deprecated
+ public FileBody(final File file, final String mimeType) {
+ this(file, ContentType.create(mimeType), null);
+ }
+
+ public FileBody(final File file) {
+ this(file, ContentType.DEFAULT_BINARY, file != null ? file.getName() : null);
+ }
+
+ /**
+ * @since 4.3
+ */
+ public FileBody(final File file, final ContentType contentType, final String filename) {
+ super(contentType);
+ Args.notNull(file, "File");
+ this.file = file;
+ this.filename = filename;
+ }
+
+ /**
+ * @since 4.3
+ */
+ public FileBody(final File file, final ContentType contentType) {
+ this(file, contentType, null);
+ }
+
+ public InputStream getInputStream() throws IOException {
+ return new FileInputStream(this.file);
+ }
+
+ public void writeTo(final OutputStream out) throws IOException {
+ Args.notNull(out, "Output stream");
+ final InputStream in = new FileInputStream(this.file);
+ try {
+ final byte[] tmp = new byte[4096];
+ int l;
+ while ((l = in.read(tmp)) != -1) {
+ out.write(tmp, 0, l);
+ }
+ out.flush();
+ } finally {
+ in.close();
+ }
+ }
+
+ public String getTransferEncoding() {
+ return MIME.ENC_BINARY;
+ }
+
+ public long getContentLength() {
+ return this.file.length();
+ }
+
+ public String getFilename() {
+ return filename;
+ }
+
+ public File getFile() {
+ return this.file;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/InputStreamBody.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/InputStreamBody.java
new file mode 100644
index 000000000..267a78ea5
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/InputStreamBody.java
@@ -0,0 +1,112 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime.content;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import ch.boye.httpclientandroidlib.entity.ContentType;
+import ch.boye.httpclientandroidlib.entity.mime.MIME;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Binary body part backed by an input stream.
+ *
+ * @see ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder
+ *
+ * @since 4.0
+ */
+public class InputStreamBody extends AbstractContentBody {
+
+ private final InputStream in;
+ private final String filename;
+
+ /**
+ * @since 4.1
+ *
+ * @deprecated (4.3) use {@link InputStreamBody#InputStreamBody(InputStream, ContentType,
+ * String)} or {@link ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder}
+ */
+ @Deprecated
+ public InputStreamBody(final InputStream in, final String mimeType, final String filename) {
+ this(in, ContentType.create(mimeType), filename);
+ }
+
+ public InputStreamBody(final InputStream in, final String filename) {
+ this(in, ContentType.DEFAULT_BINARY, filename);
+ }
+
+ /**
+ * @since 4.3
+ */
+ public InputStreamBody(final InputStream in, final ContentType contentType, final String filename) {
+ super(contentType);
+ Args.notNull(in, "Input stream");
+ this.in = in;
+ this.filename = filename;
+ }
+
+ /**
+ * @since 4.3
+ */
+ public InputStreamBody(final InputStream in, final ContentType contentType) {
+ this(in, contentType, null);
+ }
+
+ public InputStream getInputStream() {
+ return this.in;
+ }
+
+ public void writeTo(final OutputStream out) throws IOException {
+ Args.notNull(out, "Output stream");
+ try {
+ final byte[] tmp = new byte[4096];
+ int l;
+ while ((l = this.in.read(tmp)) != -1) {
+ out.write(tmp, 0, l);
+ }
+ out.flush();
+ } finally {
+ this.in.close();
+ }
+ }
+
+ public String getTransferEncoding() {
+ return MIME.ENC_BINARY;
+ }
+
+ public long getContentLength() {
+ return -1;
+ }
+
+ public String getFilename() {
+ return this.filename;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/StringBody.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/StringBody.java
new file mode 100644
index 000000000..c5ad5632d
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/StringBody.java
@@ -0,0 +1,197 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.entity.mime.content;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.io.UnsupportedEncodingException;
+import java.nio.charset.Charset;
+import java.nio.charset.UnsupportedCharsetException;
+
+import ch.boye.httpclientandroidlib.Consts;
+import ch.boye.httpclientandroidlib.entity.ContentType;
+import ch.boye.httpclientandroidlib.entity.mime.MIME;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Text body part backed by a byte array.
+ *
+ * @see ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder
+ *
+ * @since 4.0
+ */
+public class StringBody extends AbstractContentBody {
+
+ private final byte[] content;
+
+ /**
+ * @since 4.1
+ *
+ * @deprecated (4.3) use {@link StringBody#StringBody(String, ContentType)}
+ * or {@link ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder}
+ */
+ @Deprecated
+ public static StringBody create(
+ final String text,
+ final String mimeType,
+ final Charset charset) throws IllegalArgumentException {
+ try {
+ return new StringBody(text, mimeType, charset);
+ } catch (final UnsupportedEncodingException ex) {
+ throw new IllegalArgumentException("Charset " + charset + " is not supported", ex);
+ }
+ }
+
+ /**
+ * @since 4.1
+ *
+ * @deprecated (4.3) use {@link StringBody#StringBody(String, ContentType)}
+ * or {@link ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder}
+ */
+ @Deprecated
+ public static StringBody create(
+ final String text, final Charset charset) throws IllegalArgumentException {
+ return create(text, null, charset);
+ }
+
+ /**
+ * @since 4.1
+ *
+ * @deprecated (4.3) use {@link StringBody#StringBody(String, ContentType)}
+ * or {@link ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder}
+ */
+ @Deprecated
+ public static StringBody create(final String text) throws IllegalArgumentException {
+ return create(text, null, null);
+ }
+
+ /**
+ * Create a StringBody from the specified text, MIME type and character set.
+ *
+ * @param text to be used for the body, not {@code null}
+ * @param mimeType the MIME type, not {@code null}
+ * @param charset the character set, may be {@code null}, in which case the US-ASCII charset is used
+ * @throws UnsupportedEncodingException
+ * @throws IllegalArgumentException if the {@code text} parameter is null
+ *
+ * @deprecated (4.3) use {@link StringBody#StringBody(String, ContentType)}
+ * or {@link ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder}
+ */
+ @Deprecated
+ public StringBody(
+ final String text,
+ final String mimeType,
+ final Charset charset) throws UnsupportedEncodingException {
+ this(text, ContentType.create(mimeType, charset));
+ }
+
+ /**
+ * Create a StringBody from the specified text and character set.
+ * The MIME type is set to "text/plain".
+ *
+ * @param text to be used for the body, not {@code null}
+ * @param charset the character set, may be {@code null}, in which case the US-ASCII charset is used
+ * @throws UnsupportedEncodingException
+ * @throws IllegalArgumentException if the {@code text} parameter is null
+ *
+ * @deprecated (4.3) use {@link StringBody#StringBody(String, ContentType)}
+ * or {@link ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder}
+ */
+ @Deprecated
+ public StringBody(final String text, final Charset charset) throws UnsupportedEncodingException {
+ this(text, "text/plain", charset);
+ }
+
+ /**
+ * Create a StringBody from the specified text.
+ * The MIME type is set to "text/plain".
+ * The {@linkplain Consts#ASCII ASCII} charset is used.
+ *
+ * @param text to be used for the body, not {@code null}
+ * @throws UnsupportedEncodingException
+ * @throws IllegalArgumentException if the {@code text} parameter is null
+ *
+ * @deprecated (4.3) use {@link StringBody#StringBody(String, ContentType)}
+ * or {@link ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder}
+ */
+ @Deprecated
+ public StringBody(final String text) throws UnsupportedEncodingException {
+ this(text, "text/plain", Consts.ASCII);
+ }
+
+ /**
+ * @since 4.3
+ */
+ public StringBody(final String text, final ContentType contentType) {
+ super(contentType);
+ Args.notNull(text, "Text");
+ final Charset charset = contentType.getCharset();
+ final String csname = charset != null ? charset.name() : Consts.ASCII.name();
+ try {
+ this.content = text.getBytes(csname);
+ } catch (final UnsupportedEncodingException ex) {
+ // Should never happen
+ throw new UnsupportedCharsetException(csname);
+ }
+ }
+
+ public Reader getReader() {
+ final Charset charset = getContentType().getCharset();
+ return new InputStreamReader(
+ new ByteArrayInputStream(this.content),
+ charset != null ? charset : Consts.ASCII);
+ }
+
+ public void writeTo(final OutputStream out) throws IOException {
+ Args.notNull(out, "Output stream");
+ final InputStream in = new ByteArrayInputStream(this.content);
+ final byte[] tmp = new byte[4096];
+ int l;
+ while ((l = in.read(tmp)) != -1) {
+ out.write(tmp, 0, l);
+ }
+ out.flush();
+ }
+
+ public String getTransferEncoding() {
+ return MIME.ENC_8BIT;
+ }
+
+ public long getContentLength() {
+ return this.content.length;
+ }
+
+ public String getFilename() {
+ return null;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/package-info.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/package-info.java
new file mode 100644
index 000000000..ff5e2ed0d
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/content/package-info.java
@@ -0,0 +1,31 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+/**
+ * MIME body part implementations.
+ */
+package ch.boye.httpclientandroidlib.entity.mime.content;
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/package-info.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/package-info.java
new file mode 100644
index 000000000..0ef01f9ed
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/mime/package-info.java
@@ -0,0 +1,31 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+/**
+ * MIME coded HTTP entity implementations.
+ */
+package ch.boye.httpclientandroidlib.entity.mime;
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/package-info.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/package-info.java
new file mode 100644
index 000000000..0027ae98d
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/entity/package-info.java
@@ -0,0 +1,31 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+/**
+ * Core HTTP entity implementations.
+ */
+package ch.boye.httpclientandroidlib.entity;
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/AbstractHttpClientConnection.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/AbstractHttpClientConnection.java
new file mode 100644
index 000000000..3f3c5f406
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/AbstractHttpClientConnection.java
@@ -0,0 +1,323 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import java.io.IOException;
+import java.net.SocketTimeoutException;
+
+import ch.boye.httpclientandroidlib.HttpClientConnection;
+import ch.boye.httpclientandroidlib.HttpConnectionMetrics;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpResponseFactory;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.impl.entity.EntityDeserializer;
+import ch.boye.httpclientandroidlib.impl.entity.EntitySerializer;
+import ch.boye.httpclientandroidlib.impl.entity.LaxContentLengthStrategy;
+import ch.boye.httpclientandroidlib.impl.entity.StrictContentLengthStrategy;
+import ch.boye.httpclientandroidlib.impl.io.DefaultHttpResponseParser;
+import ch.boye.httpclientandroidlib.impl.io.HttpRequestWriter;
+import ch.boye.httpclientandroidlib.io.EofSensor;
+import ch.boye.httpclientandroidlib.io.HttpMessageParser;
+import ch.boye.httpclientandroidlib.io.HttpMessageWriter;
+import ch.boye.httpclientandroidlib.io.HttpTransportMetrics;
+import ch.boye.httpclientandroidlib.io.SessionInputBuffer;
+import ch.boye.httpclientandroidlib.io.SessionOutputBuffer;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Abstract client-side HTTP connection capable of transmitting and receiving
+ * data using arbitrary {@link SessionInputBuffer} and
+ * {@link SessionOutputBuffer} implementations.
+ *
+ * The following parameters can be used to customize the behavior of this
+ * class:
+ *
+ * This constructor will invoke {@link #createEntityDeserializer()}
+ * and {@link #createEntitySerializer()} methods in order to initialize
+ * HTTP entity serializer and deserializer implementations for this
+ * connection.
+ */
+ public AbstractHttpClientConnection() {
+ super();
+ this.entityserializer = createEntitySerializer();
+ this.entitydeserializer = createEntityDeserializer();
+ }
+
+ /**
+ * Asserts if the connection is open.
+ *
+ * @throws IllegalStateException if the connection is not open.
+ */
+ protected abstract void assertOpen() throws IllegalStateException;
+
+ /**
+ * Creates an instance of {@link EntityDeserializer} with the
+ * {@link LaxContentLengthStrategy} implementation to be used for
+ * de-serializing entities received over this connection.
+ *
+ * This method can be overridden in a super class in order to create
+ * instances of {@link EntityDeserializer} using a custom
+ * {@link ch.boye.httpclientandroidlib.entity.ContentLengthStrategy}.
+ *
+ * @return HTTP entity deserializer
+ */
+ protected EntityDeserializer createEntityDeserializer() {
+ return new EntityDeserializer(new LaxContentLengthStrategy());
+ }
+
+ /**
+ * Creates an instance of {@link EntitySerializer} with the
+ * {@link StrictContentLengthStrategy} implementation to be used for
+ * serializing HTTP entities sent over this connection.
+ *
+ * This method can be overridden in a super class in order to create
+ * instances of {@link EntitySerializer} using a custom
+ * {@link ch.boye.httpclientandroidlib.entity.ContentLengthStrategy}.
+ *
+ * @return HTTP entity serialzier.
+ */
+ protected EntitySerializer createEntitySerializer() {
+ return new EntitySerializer(new StrictContentLengthStrategy());
+ }
+
+ /**
+ * Creates an instance of {@link DefaultHttpResponseFactory} to be used
+ * for creating {@link HttpResponse} objects received by over this
+ * connection.
+ *
+ * This method can be overridden in a super class in order to provide
+ * a different implementation of the {@link HttpResponseFactory} interface.
+ *
+ * @return HTTP response factory.
+ */
+ protected HttpResponseFactory createHttpResponseFactory() {
+ return DefaultHttpResponseFactory.INSTANCE;
+ }
+
+ /**
+ * Creates an instance of {@link HttpMessageParser} to be used for parsing
+ * HTTP responses received over this connection.
+ *
+ * This method can be overridden in a super class in order to provide
+ * a different implementation of the {@link HttpMessageParser} interface or
+ * to pass a different implementation of the
+ * {@link ch.boye.httpclientandroidlib.message.LineParser} to the the
+ * {@link DefaultHttpResponseParser} constructor.
+ *
+ * @param buffer the session input buffer.
+ * @param responseFactory the HTTP response factory.
+ * @param params HTTP parameters.
+ * @return HTTP message parser.
+ */
+ protected HttpMessageParser createResponseParser(
+ final SessionInputBuffer buffer,
+ final HttpResponseFactory responseFactory,
+ final HttpParams params) {
+ return new DefaultHttpResponseParser(buffer, null, responseFactory, params);
+ }
+
+ /**
+ * Creates an instance of {@link HttpMessageWriter} to be used for
+ * writing out HTTP requests sent over this connection.
+ *
+ * This method can be overridden in a super class in order to provide
+ * a different implementation of the {@link HttpMessageWriter} interface or
+ * to pass a different implementation of
+ * {@link ch.boye.httpclientandroidlib.message.LineFormatter} to the the default implementation
+ * {@link HttpRequestWriter}.
+ *
+ * @param buffer the session output buffer
+ * @param params HTTP parameters
+ * @return HTTP message writer
+ */
+ protected HttpMessageWriter createRequestWriter(
+ final SessionOutputBuffer buffer,
+ final HttpParams params) {
+ return new HttpRequestWriter(buffer, null, params);
+ }
+
+ /**
+ * @since 4.1
+ */
+ protected HttpConnectionMetricsImpl createConnectionMetrics(
+ final HttpTransportMetrics inTransportMetric,
+ final HttpTransportMetrics outTransportMetric) {
+ return new HttpConnectionMetricsImpl(inTransportMetric, outTransportMetric);
+ }
+
+ /**
+ * Initializes this connection object with {@link SessionInputBuffer} and
+ * {@link SessionOutputBuffer} instances to be used for sending and
+ * receiving data. These session buffers can be bound to any arbitrary
+ * physical output medium.
+ *
+ * This method will invoke {@link #createHttpResponseFactory()},
+ * {@link #createRequestWriter(SessionOutputBuffer, HttpParams)}
+ * and {@link #createResponseParser(SessionInputBuffer, HttpResponseFactory, HttpParams)}
+ * methods to initialize HTTP request writer and response parser for this
+ * connection.
+ *
+ * @param inbuffer the session input buffer.
+ * @param outbuffer the session output buffer.
+ * @param params HTTP parameters.
+ */
+ protected void init(
+ final SessionInputBuffer inbuffer,
+ final SessionOutputBuffer outbuffer,
+ final HttpParams params) {
+ this.inbuffer = Args.notNull(inbuffer, "Input session buffer");
+ this.outbuffer = Args.notNull(outbuffer, "Output session buffer");
+ if (inbuffer instanceof EofSensor) {
+ this.eofSensor = (EofSensor) inbuffer;
+ }
+ this.responseParser = createResponseParser(
+ inbuffer,
+ createHttpResponseFactory(),
+ params);
+ this.requestWriter = createRequestWriter(
+ outbuffer, params);
+ this.metrics = createConnectionMetrics(
+ inbuffer.getMetrics(),
+ outbuffer.getMetrics());
+ }
+
+ public boolean isResponseAvailable(final int timeout) throws IOException {
+ assertOpen();
+ try {
+ return this.inbuffer.isDataAvailable(timeout);
+ } catch (final SocketTimeoutException ex) {
+ return false;
+ }
+ }
+
+ public void sendRequestHeader(final HttpRequest request)
+ throws HttpException, IOException {
+ Args.notNull(request, "HTTP request");
+ assertOpen();
+ this.requestWriter.write(request);
+ this.metrics.incrementRequestCount();
+ }
+
+ public void sendRequestEntity(final HttpEntityEnclosingRequest request)
+ throws HttpException, IOException {
+ Args.notNull(request, "HTTP request");
+ assertOpen();
+ if (request.getEntity() == null) {
+ return;
+ }
+ this.entityserializer.serialize(
+ this.outbuffer,
+ request,
+ request.getEntity());
+ }
+
+ protected void doFlush() throws IOException {
+ this.outbuffer.flush();
+ }
+
+ public void flush() throws IOException {
+ assertOpen();
+ doFlush();
+ }
+
+ public HttpResponse receiveResponseHeader()
+ throws HttpException, IOException {
+ assertOpen();
+ final HttpResponse response = this.responseParser.parse();
+ if (response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK) {
+ this.metrics.incrementResponseCount();
+ }
+ return response;
+ }
+
+ public void receiveResponseEntity(final HttpResponse response)
+ throws HttpException, IOException {
+ Args.notNull(response, "HTTP response");
+ assertOpen();
+ final HttpEntity entity = this.entitydeserializer.deserialize(this.inbuffer, response);
+ response.setEntity(entity);
+ }
+
+ protected boolean isEof() {
+ return this.eofSensor != null && this.eofSensor.isEof();
+ }
+
+ public boolean isStale() {
+ if (!isOpen()) {
+ return true;
+ }
+ if (isEof()) {
+ return true;
+ }
+ try {
+ this.inbuffer.isDataAvailable(1);
+ return isEof();
+ } catch (final SocketTimeoutException ex) {
+ return false;
+ } catch (final IOException ex) {
+ return true;
+ }
+ }
+
+ public HttpConnectionMetrics getMetrics() {
+ return this.metrics;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/AbstractHttpServerConnection.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/AbstractHttpServerConnection.java
new file mode 100644
index 000000000..e9e67e5b1
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/AbstractHttpServerConnection.java
@@ -0,0 +1,310 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.HttpConnectionMetrics;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpRequestFactory;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpServerConnection;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.impl.entity.DisallowIdentityContentLengthStrategy;
+import ch.boye.httpclientandroidlib.impl.entity.EntityDeserializer;
+import ch.boye.httpclientandroidlib.impl.entity.EntitySerializer;
+import ch.boye.httpclientandroidlib.impl.entity.LaxContentLengthStrategy;
+import ch.boye.httpclientandroidlib.impl.entity.StrictContentLengthStrategy;
+import ch.boye.httpclientandroidlib.impl.io.DefaultHttpRequestParser;
+import ch.boye.httpclientandroidlib.impl.io.HttpResponseWriter;
+import ch.boye.httpclientandroidlib.io.EofSensor;
+import ch.boye.httpclientandroidlib.io.HttpMessageParser;
+import ch.boye.httpclientandroidlib.io.HttpMessageWriter;
+import ch.boye.httpclientandroidlib.io.HttpTransportMetrics;
+import ch.boye.httpclientandroidlib.io.SessionInputBuffer;
+import ch.boye.httpclientandroidlib.io.SessionOutputBuffer;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Abstract server-side HTTP connection capable of transmitting and receiving
+ * data using arbitrary {@link SessionInputBuffer} and
+ * {@link SessionOutputBuffer} implementations.
+ *
+ * The following parameters can be used to customize the behavior of this
+ * class:
+ *
+ * This constructor will invoke {@link #createEntityDeserializer()}
+ * and {@link #createEntitySerializer()} methods in order to initialize
+ * HTTP entity serializer and deserializer implementations for this
+ * connection.
+ */
+ public AbstractHttpServerConnection() {
+ super();
+ this.entityserializer = createEntitySerializer();
+ this.entitydeserializer = createEntityDeserializer();
+ }
+
+ /**
+ * Asserts if the connection is open.
+ *
+ * @throws IllegalStateException if the connection is not open.
+ */
+ protected abstract void assertOpen() throws IllegalStateException;
+
+ /**
+ * Creates an instance of {@link EntityDeserializer} with the
+ * {@link LaxContentLengthStrategy} implementation to be used for
+ * de-serializing entities received over this connection.
+ *
+ * This method can be overridden in a super class in order to create
+ * instances of {@link EntityDeserializer} using a custom
+ * {@link ch.boye.httpclientandroidlib.entity.ContentLengthStrategy}.
+ *
+ * @return HTTP entity deserializer
+ */
+ protected EntityDeserializer createEntityDeserializer() {
+ return new EntityDeserializer(new DisallowIdentityContentLengthStrategy(
+ new LaxContentLengthStrategy(0)));
+ }
+
+ /**
+ * Creates an instance of {@link EntitySerializer} with the
+ * {@link StrictContentLengthStrategy} implementation to be used for
+ * serializing HTTP entities sent over this connection.
+ *
+ * This method can be overridden in a super class in order to create
+ * instances of {@link EntitySerializer} using a custom
+ * {@link ch.boye.httpclientandroidlib.entity.ContentLengthStrategy}.
+ *
+ * @return HTTP entity serialzier.
+ */
+ protected EntitySerializer createEntitySerializer() {
+ return new EntitySerializer(new StrictContentLengthStrategy());
+ }
+
+ /**
+ * Creates an instance of {@link DefaultHttpRequestFactory} to be used
+ * for creating {@link HttpRequest} objects received by over this
+ * connection.
+ *
+ * This method can be overridden in a super class in order to provide
+ * a different implementation of the {@link HttpRequestFactory} interface.
+ *
+ * @return HTTP request factory.
+ */
+ protected HttpRequestFactory createHttpRequestFactory() {
+ return DefaultHttpRequestFactory.INSTANCE;
+ }
+
+ /**
+ * Creates an instance of {@link HttpMessageParser} to be used for parsing
+ * HTTP requests received over this connection.
+ *
+ * This method can be overridden in a super class in order to provide
+ * a different implementation of the {@link HttpMessageParser} interface or
+ * to pass a different implementation of the
+ * {@link ch.boye.httpclientandroidlib.message.LineParser} to the
+ * {@link DefaultHttpRequestParser} constructor.
+ *
+ * @param buffer the session input buffer.
+ * @param requestFactory the HTTP request factory.
+ * @param params HTTP parameters.
+ * @return HTTP message parser.
+ */
+ protected HttpMessageParser createRequestParser(
+ final SessionInputBuffer buffer,
+ final HttpRequestFactory requestFactory,
+ final HttpParams params) {
+ return new DefaultHttpRequestParser(buffer, null, requestFactory, params);
+ }
+
+ /**
+ * Creates an instance of {@link HttpMessageWriter} to be used for
+ * writing out HTTP responses sent over this connection.
+ *
+ * This method can be overridden in a super class in order to provide
+ * a different implementation of the {@link HttpMessageWriter} interface or
+ * to pass a different implementation of
+ * {@link ch.boye.httpclientandroidlib.message.LineFormatter} to the the default
+ * implementation {@link HttpResponseWriter}.
+ *
+ * @param buffer the session output buffer
+ * @param params HTTP parameters
+ * @return HTTP message writer
+ */
+ protected HttpMessageWriter createResponseWriter(
+ final SessionOutputBuffer buffer,
+ final HttpParams params) {
+ return new HttpResponseWriter(buffer, null, params);
+ }
+
+ /**
+ * @since 4.1
+ */
+ protected HttpConnectionMetricsImpl createConnectionMetrics(
+ final HttpTransportMetrics inTransportMetric,
+ final HttpTransportMetrics outTransportMetric) {
+ return new HttpConnectionMetricsImpl(inTransportMetric, outTransportMetric);
+ }
+
+ /**
+ * Initializes this connection object with {@link SessionInputBuffer} and
+ * {@link SessionOutputBuffer} instances to be used for sending and
+ * receiving data. These session buffers can be bound to any arbitrary
+ * physical output medium.
+ *
+ * This method will invoke {@link #createHttpRequestFactory},
+ * {@link #createRequestParser(SessionInputBuffer, HttpRequestFactory, HttpParams)}
+ * and {@link #createResponseWriter(SessionOutputBuffer, HttpParams)}
+ * methods to initialize HTTP request parser and response writer for this
+ * connection.
+ *
+ * @param inbuffer the session input buffer.
+ * @param outbuffer the session output buffer.
+ * @param params HTTP parameters.
+ */
+ protected void init(
+ final SessionInputBuffer inbuffer,
+ final SessionOutputBuffer outbuffer,
+ final HttpParams params) {
+ this.inbuffer = Args.notNull(inbuffer, "Input session buffer");
+ this.outbuffer = Args.notNull(outbuffer, "Output session buffer");
+ if (inbuffer instanceof EofSensor) {
+ this.eofSensor = (EofSensor) inbuffer;
+ }
+ this.requestParser = createRequestParser(
+ inbuffer,
+ createHttpRequestFactory(),
+ params);
+ this.responseWriter = createResponseWriter(
+ outbuffer, params);
+ this.metrics = createConnectionMetrics(
+ inbuffer.getMetrics(),
+ outbuffer.getMetrics());
+ }
+
+ public HttpRequest receiveRequestHeader()
+ throws HttpException, IOException {
+ assertOpen();
+ final HttpRequest request = this.requestParser.parse();
+ this.metrics.incrementRequestCount();
+ return request;
+ }
+
+ public void receiveRequestEntity(final HttpEntityEnclosingRequest request)
+ throws HttpException, IOException {
+ Args.notNull(request, "HTTP request");
+ assertOpen();
+ final HttpEntity entity = this.entitydeserializer.deserialize(this.inbuffer, request);
+ request.setEntity(entity);
+ }
+
+ protected void doFlush() throws IOException {
+ this.outbuffer.flush();
+ }
+
+ public void flush() throws IOException {
+ assertOpen();
+ doFlush();
+ }
+
+ public void sendResponseHeader(final HttpResponse response)
+ throws HttpException, IOException {
+ Args.notNull(response, "HTTP response");
+ assertOpen();
+ this.responseWriter.write(response);
+ if (response.getStatusLine().getStatusCode() >= 200) {
+ this.metrics.incrementResponseCount();
+ }
+ }
+
+ public void sendResponseEntity(final HttpResponse response)
+ throws HttpException, IOException {
+ if (response.getEntity() == null) {
+ return;
+ }
+ this.entityserializer.serialize(
+ this.outbuffer,
+ response,
+ response.getEntity());
+ }
+
+ protected boolean isEof() {
+ return this.eofSensor != null && this.eofSensor.isEof();
+ }
+
+ public boolean isStale() {
+ if (!isOpen()) {
+ return true;
+ }
+ if (isEof()) {
+ return true;
+ }
+ try {
+ this.inbuffer.isDataAvailable(1);
+ return isEof();
+ } catch (final IOException ex) {
+ return true;
+ }
+ }
+
+ public HttpConnectionMetrics getMetrics() {
+ return this.metrics;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/BHttpConnectionBase.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/BHttpConnectionBase.java
new file mode 100644
index 000000000..2215aa6e2
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/BHttpConnectionBase.java
@@ -0,0 +1,393 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.net.SocketTimeoutException;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CharsetEncoder;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpConnection;
+import ch.boye.httpclientandroidlib.HttpConnectionMetrics;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpInetConnection;
+import ch.boye.httpclientandroidlib.HttpMessage;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.config.MessageConstraints;
+import ch.boye.httpclientandroidlib.entity.BasicHttpEntity;
+import ch.boye.httpclientandroidlib.entity.ContentLengthStrategy;
+import ch.boye.httpclientandroidlib.impl.entity.LaxContentLengthStrategy;
+import ch.boye.httpclientandroidlib.impl.entity.StrictContentLengthStrategy;
+import ch.boye.httpclientandroidlib.impl.io.ChunkedInputStream;
+import ch.boye.httpclientandroidlib.impl.io.ChunkedOutputStream;
+import ch.boye.httpclientandroidlib.impl.io.ContentLengthInputStream;
+import ch.boye.httpclientandroidlib.impl.io.ContentLengthOutputStream;
+import ch.boye.httpclientandroidlib.impl.io.HttpTransportMetricsImpl;
+import ch.boye.httpclientandroidlib.impl.io.IdentityInputStream;
+import ch.boye.httpclientandroidlib.impl.io.IdentityOutputStream;
+import ch.boye.httpclientandroidlib.impl.io.SessionInputBufferImpl;
+import ch.boye.httpclientandroidlib.impl.io.SessionOutputBufferImpl;
+import ch.boye.httpclientandroidlib.io.SessionInputBuffer;
+import ch.boye.httpclientandroidlib.io.SessionOutputBuffer;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.Asserts;
+import ch.boye.httpclientandroidlib.util.NetUtils;
+
+/**
+ * This class serves as a base for all {@link HttpConnection} implementations and provides
+ * functionality common to both client and server HTTP connections.
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class BHttpConnectionBase implements HttpConnection, HttpInetConnection {
+
+ private final SessionInputBufferImpl inbuffer;
+ private final SessionOutputBufferImpl outbuffer;
+ private final HttpConnectionMetricsImpl connMetrics;
+ private final ContentLengthStrategy incomingContentStrategy;
+ private final ContentLengthStrategy outgoingContentStrategy;
+
+ private volatile boolean open;
+ private volatile Socket socket;
+
+ /**
+ * Creates new instance of BHttpConnectionBase.
+ *
+ * @param buffersize buffer size. Must be a positive number.
+ * @param fragmentSizeHint fragment size hint.
+ * @param chardecoder decoder to be used for decoding HTTP protocol elements.
+ * If null simple type cast will be used for byte to char conversion.
+ * @param charencoder encoder to be used for encoding HTTP protocol elements.
+ * If null simple type cast will be used for char to byte conversion.
+ * @param constraints Message constraints. If null
+ * {@link MessageConstraints#DEFAULT} will be used.
+ * @param incomingContentStrategy incoming content length strategy. If null
+ * {@link LaxContentLengthStrategy#INSTANCE} will be used.
+ * @param outgoingContentStrategy outgoing content length strategy. If null
+ * {@link StrictContentLengthStrategy#INSTANCE} will be used.
+ */
+ protected BHttpConnectionBase(
+ final int buffersize,
+ final int fragmentSizeHint,
+ final CharsetDecoder chardecoder,
+ final CharsetEncoder charencoder,
+ final MessageConstraints constraints,
+ final ContentLengthStrategy incomingContentStrategy,
+ final ContentLengthStrategy outgoingContentStrategy) {
+ super();
+ Args.positive(buffersize, "Buffer size");
+ final HttpTransportMetricsImpl inTransportMetrics = new HttpTransportMetricsImpl();
+ final HttpTransportMetricsImpl outTransportMetrics = new HttpTransportMetricsImpl();
+ this.inbuffer = new SessionInputBufferImpl(inTransportMetrics, buffersize, -1,
+ constraints != null ? constraints : MessageConstraints.DEFAULT, chardecoder);
+ this.outbuffer = new SessionOutputBufferImpl(outTransportMetrics, buffersize, fragmentSizeHint,
+ charencoder);
+ this.connMetrics = new HttpConnectionMetricsImpl(inTransportMetrics, outTransportMetrics);
+ this.incomingContentStrategy = incomingContentStrategy != null ? incomingContentStrategy :
+ LaxContentLengthStrategy.INSTANCE;
+ this.outgoingContentStrategy = outgoingContentStrategy != null ? outgoingContentStrategy :
+ StrictContentLengthStrategy.INSTANCE;
+ }
+
+ protected void ensureOpen() throws IOException {
+ Asserts.check(this.open, "Connection is not open");
+ if (!this.inbuffer.isBound()) {
+ this.inbuffer.bind(getSocketInputStream(this.socket));
+ }
+ if (!this.outbuffer.isBound()) {
+ this.outbuffer.bind(getSocketOutputStream(this.socket));
+ }
+ }
+
+ protected InputStream getSocketInputStream(final Socket socket) throws IOException {
+ return socket.getInputStream();
+ }
+
+ protected OutputStream getSocketOutputStream(final Socket socket) throws IOException {
+ return socket.getOutputStream();
+ }
+
+ /**
+ * Binds this connection to the given {@link Socket}. This socket will be
+ * used by the connection to send and receive data.
+ *
+ * After this method's execution the connection status will be reported
+ * as open and the {@link #isOpen()} will return true.
+ *
+ * @param socket the socket.
+ * @throws IOException in case of an I/O error.
+ */
+ protected void bind(final Socket socket) throws IOException {
+ Args.notNull(socket, "Socket");
+ this.socket = socket;
+ this.open = true;
+ this.inbuffer.bind(null);
+ this.outbuffer.bind(null);
+ }
+
+ protected SessionInputBuffer getSessionInputBuffer() {
+ return this.inbuffer;
+ }
+
+ protected SessionOutputBuffer getSessionOutputBuffer() {
+ return this.outbuffer;
+ }
+
+ protected void doFlush() throws IOException {
+ this.outbuffer.flush();
+ }
+
+ public boolean isOpen() {
+ return this.open;
+ }
+
+ protected Socket getSocket() {
+ return this.socket;
+ }
+
+ protected OutputStream createOutputStream(
+ final long len,
+ final SessionOutputBuffer outbuffer) {
+ if (len == ContentLengthStrategy.CHUNKED) {
+ return new ChunkedOutputStream(2048, outbuffer);
+ } else if (len == ContentLengthStrategy.IDENTITY) {
+ return new IdentityOutputStream(outbuffer);
+ } else {
+ return new ContentLengthOutputStream(outbuffer, len);
+ }
+ }
+
+ protected OutputStream prepareOutput(final HttpMessage message) throws HttpException {
+ final long len = this.outgoingContentStrategy.determineLength(message);
+ return createOutputStream(len, this.outbuffer);
+ }
+
+ protected InputStream createInputStream(
+ final long len,
+ final SessionInputBuffer inbuffer) {
+ if (len == ContentLengthStrategy.CHUNKED) {
+ return new ChunkedInputStream(inbuffer);
+ } else if (len == ContentLengthStrategy.IDENTITY) {
+ return new IdentityInputStream(inbuffer);
+ } else {
+ return new ContentLengthInputStream(inbuffer, len);
+ }
+ }
+
+ protected HttpEntity prepareInput(final HttpMessage message) throws HttpException {
+ final BasicHttpEntity entity = new BasicHttpEntity();
+
+ final long len = this.incomingContentStrategy.determineLength(message);
+ final InputStream instream = createInputStream(len, this.inbuffer);
+ if (len == ContentLengthStrategy.CHUNKED) {
+ entity.setChunked(true);
+ entity.setContentLength(-1);
+ entity.setContent(instream);
+ } else if (len == ContentLengthStrategy.IDENTITY) {
+ entity.setChunked(false);
+ entity.setContentLength(-1);
+ entity.setContent(instream);
+ } else {
+ entity.setChunked(false);
+ entity.setContentLength(len);
+ entity.setContent(instream);
+ }
+
+ final Header contentTypeHeader = message.getFirstHeader(HTTP.CONTENT_TYPE);
+ if (contentTypeHeader != null) {
+ entity.setContentType(contentTypeHeader);
+ }
+ final Header contentEncodingHeader = message.getFirstHeader(HTTP.CONTENT_ENCODING);
+ if (contentEncodingHeader != null) {
+ entity.setContentEncoding(contentEncodingHeader);
+ }
+ return entity;
+ }
+
+ public InetAddress getLocalAddress() {
+ if (this.socket != null) {
+ return this.socket.getLocalAddress();
+ } else {
+ return null;
+ }
+ }
+
+ public int getLocalPort() {
+ if (this.socket != null) {
+ return this.socket.getLocalPort();
+ } else {
+ return -1;
+ }
+ }
+
+ public InetAddress getRemoteAddress() {
+ if (this.socket != null) {
+ return this.socket.getInetAddress();
+ } else {
+ return null;
+ }
+ }
+
+ public int getRemotePort() {
+ if (this.socket != null) {
+ return this.socket.getPort();
+ } else {
+ return -1;
+ }
+ }
+
+ public void setSocketTimeout(final int timeout) {
+ if (this.socket != null) {
+ try {
+ this.socket.setSoTimeout(timeout);
+ } catch (final SocketException ignore) {
+ // It is not quite clear from the Sun's documentation if there are any
+ // other legitimate cases for a socket exception to be thrown when setting
+ // SO_TIMEOUT besides the socket being already closed
+ }
+ }
+ }
+
+ public int getSocketTimeout() {
+ if (this.socket != null) {
+ try {
+ return this.socket.getSoTimeout();
+ } catch (final SocketException ignore) {
+ return -1;
+ }
+ } else {
+ return -1;
+ }
+ }
+
+ public void shutdown() throws IOException {
+ this.open = false;
+ final Socket tmpsocket = this.socket;
+ if (tmpsocket != null) {
+ tmpsocket.close();
+ }
+ }
+
+ public void close() throws IOException {
+ if (!this.open) {
+ return;
+ }
+ this.open = false;
+ final Socket sock = this.socket;
+ try {
+ this.inbuffer.clear();
+ this.outbuffer.flush();
+ try {
+ try {
+ sock.shutdownOutput();
+ } catch (final IOException ignore) {
+ }
+ try {
+ sock.shutdownInput();
+ } catch (final IOException ignore) {
+ }
+ } catch (final UnsupportedOperationException ignore) {
+ // if one isn't supported, the other one isn't either
+ }
+ } finally {
+ sock.close();
+ }
+ }
+
+ private int fillInputBuffer(final int timeout) throws IOException {
+ final int oldtimeout = this.socket.getSoTimeout();
+ try {
+ this.socket.setSoTimeout(timeout);
+ return this.inbuffer.fillBuffer();
+ } finally {
+ this.socket.setSoTimeout(oldtimeout);
+ }
+ }
+
+ protected boolean awaitInput(final int timeout) throws IOException {
+ if (this.inbuffer.hasBufferedData()) {
+ return true;
+ }
+ fillInputBuffer(timeout);
+ return this.inbuffer.hasBufferedData();
+ }
+
+ public boolean isStale() {
+ if (!isOpen()) {
+ return true;
+ }
+ try {
+ final int bytesRead = fillInputBuffer(1);
+ return bytesRead < 0;
+ } catch (final SocketTimeoutException ex) {
+ return false;
+ } catch (final IOException ex) {
+ return true;
+ }
+ }
+
+ protected void incrementRequestCount() {
+ this.connMetrics.incrementRequestCount();
+ }
+
+ protected void incrementResponseCount() {
+ this.connMetrics.incrementResponseCount();
+ }
+
+ public HttpConnectionMetrics getMetrics() {
+ return this.connMetrics;
+ }
+
+ @Override
+ public String toString() {
+ if (this.socket != null) {
+ final StringBuilder buffer = new StringBuilder();
+ final SocketAddress remoteAddress = this.socket.getRemoteSocketAddress();
+ final SocketAddress localAddress = this.socket.getLocalSocketAddress();
+ if (remoteAddress != null && localAddress != null) {
+ NetUtils.formatAddress(buffer, localAddress);
+ buffer.append("<->");
+ NetUtils.formatAddress(buffer, remoteAddress);
+ }
+ return buffer.toString();
+ } else {
+ return "[Not bound]";
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/ConnSupport.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/ConnSupport.java
new file mode 100644
index 000000000..ba82a2a7c
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/ConnSupport.java
@@ -0,0 +1,75 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl;
+
+import ch.boye.httpclientandroidlib.config.ConnectionConfig;
+
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CharsetEncoder;
+import java.nio.charset.CodingErrorAction;
+
+/**
+ * Connection support methods.
+ *
+ * @since 4.3
+ */
+public final class ConnSupport {
+
+ public static CharsetDecoder createDecoder(final ConnectionConfig cconfig) {
+ if (cconfig == null) {
+ return null;
+ }
+ final Charset charset = cconfig.getCharset();
+ final CodingErrorAction malformed = cconfig.getMalformedInputAction();
+ final CodingErrorAction unmappable = cconfig.getUnmappableInputAction();
+ if (charset != null) {
+ return charset.newDecoder()
+ .onMalformedInput(malformed != null ? malformed : CodingErrorAction.REPORT)
+ .onUnmappableCharacter(unmappable != null ? unmappable: CodingErrorAction.REPORT);
+ } else {
+ return null;
+ }
+ }
+
+ public static CharsetEncoder createEncoder(final ConnectionConfig cconfig) {
+ if (cconfig == null) {
+ return null;
+ }
+ final Charset charset = cconfig.getCharset();
+ if (charset != null) {
+ final CodingErrorAction malformed = cconfig.getMalformedInputAction();
+ final CodingErrorAction unmappable = cconfig.getUnmappableInputAction();
+ return charset.newEncoder()
+ .onMalformedInput(malformed != null ? malformed : CodingErrorAction.REPORT)
+ .onUnmappableCharacter(unmappable != null ? unmappable: CodingErrorAction.REPORT);
+ } else {
+ return null;
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultBHttpClientConnection.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultBHttpClientConnection.java
new file mode 100644
index 000000000..9627e53f2
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultBHttpClientConnection.java
@@ -0,0 +1,182 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.Socket;
+import java.net.SocketTimeoutException;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CharsetEncoder;
+
+import ch.boye.httpclientandroidlib.HttpClientConnection;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.config.MessageConstraints;
+import ch.boye.httpclientandroidlib.entity.ContentLengthStrategy;
+import ch.boye.httpclientandroidlib.impl.io.DefaultHttpRequestWriterFactory;
+import ch.boye.httpclientandroidlib.impl.io.DefaultHttpResponseParserFactory;
+import ch.boye.httpclientandroidlib.io.HttpMessageParser;
+import ch.boye.httpclientandroidlib.io.HttpMessageParserFactory;
+import ch.boye.httpclientandroidlib.io.HttpMessageWriter;
+import ch.boye.httpclientandroidlib.io.HttpMessageWriterFactory;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Default implementation of {@link HttpClientConnection}.
+ *
+ * @since 4.3
+ */
+@NotThreadSafe
+public class DefaultBHttpClientConnection extends BHttpConnectionBase
+ implements HttpClientConnection {
+
+ private final HttpMessageParser responseParser;
+ private final HttpMessageWriter requestWriter;
+
+ /**
+ * Creates new instance of DefaultBHttpClientConnection.
+ *
+ * @param buffersize buffer size. Must be a positive number.
+ * @param fragmentSizeHint fragment size hint.
+ * @param chardecoder decoder to be used for decoding HTTP protocol elements.
+ * If null simple type cast will be used for byte to char conversion.
+ * @param charencoder encoder to be used for encoding HTTP protocol elements.
+ * If null simple type cast will be used for char to byte conversion.
+ * @param constraints Message constraints. If null
+ * {@link MessageConstraints#DEFAULT} will be used.
+ * @param incomingContentStrategy incoming content length strategy. If null
+ * {@link ch.boye.httpclientandroidlib.impl.entity.LaxContentLengthStrategy#INSTANCE} will be used.
+ * @param outgoingContentStrategy outgoing content length strategy. If null
+ * {@link ch.boye.httpclientandroidlib.impl.entity.StrictContentLengthStrategy#INSTANCE} will be used.
+ * @param requestWriterFactory request writer factory. If null
+ * {@link DefaultHttpRequestWriterFactory#INSTANCE} will be used.
+ * @param responseParserFactory response parser factory. If null
+ * {@link DefaultHttpResponseParserFactory#INSTANCE} will be used.
+ */
+ public DefaultBHttpClientConnection(
+ final int buffersize,
+ final int fragmentSizeHint,
+ final CharsetDecoder chardecoder,
+ final CharsetEncoder charencoder,
+ final MessageConstraints constraints,
+ final ContentLengthStrategy incomingContentStrategy,
+ final ContentLengthStrategy outgoingContentStrategy,
+ final HttpMessageWriterFactory requestWriterFactory,
+ final HttpMessageParserFactory responseParserFactory) {
+ super(buffersize, fragmentSizeHint, chardecoder, charencoder,
+ constraints, incomingContentStrategy, outgoingContentStrategy);
+ this.requestWriter = (requestWriterFactory != null ? requestWriterFactory :
+ DefaultHttpRequestWriterFactory.INSTANCE).create(getSessionOutputBuffer());
+ this.responseParser = (responseParserFactory != null ? responseParserFactory :
+ DefaultHttpResponseParserFactory.INSTANCE).create(getSessionInputBuffer(), constraints);
+ }
+
+ public DefaultBHttpClientConnection(
+ final int buffersize,
+ final CharsetDecoder chardecoder,
+ final CharsetEncoder charencoder,
+ final MessageConstraints constraints) {
+ this(buffersize, buffersize, chardecoder, charencoder, constraints, null, null, null, null);
+ }
+
+ public DefaultBHttpClientConnection(final int buffersize) {
+ this(buffersize, buffersize, null, null, null, null, null, null, null);
+ }
+
+ protected void onResponseReceived(final HttpResponse response) {
+ }
+
+ protected void onRequestSubmitted(final HttpRequest request) {
+ }
+
+ @Override
+ public void bind(final Socket socket) throws IOException {
+ super.bind(socket);
+ }
+
+ public boolean isResponseAvailable(final int timeout) throws IOException {
+ ensureOpen();
+ try {
+ return awaitInput(timeout);
+ } catch (final SocketTimeoutException ex) {
+ return false;
+ }
+ }
+
+ public void sendRequestHeader(final HttpRequest request)
+ throws HttpException, IOException {
+ Args.notNull(request, "HTTP request");
+ ensureOpen();
+ this.requestWriter.write(request);
+ onRequestSubmitted(request);
+ incrementRequestCount();
+ }
+
+ public void sendRequestEntity(final HttpEntityEnclosingRequest request)
+ throws HttpException, IOException {
+ Args.notNull(request, "HTTP request");
+ ensureOpen();
+ final HttpEntity entity = request.getEntity();
+ if (entity == null) {
+ return;
+ }
+ final OutputStream outstream = prepareOutput(request);
+ entity.writeTo(outstream);
+ outstream.close();
+ }
+
+ public HttpResponse receiveResponseHeader() throws HttpException, IOException {
+ ensureOpen();
+ final HttpResponse response = this.responseParser.parse();
+ onResponseReceived(response);
+ if (response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK) {
+ incrementResponseCount();
+ }
+ return response;
+ }
+
+ public void receiveResponseEntity(
+ final HttpResponse response) throws HttpException, IOException {
+ Args.notNull(response, "HTTP response");
+ ensureOpen();
+ final HttpEntity entity = prepareInput(response);
+ response.setEntity(entity);
+ }
+
+ public void flush() throws IOException {
+ ensureOpen();
+ doFlush();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultBHttpClientConnectionFactory.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultBHttpClientConnectionFactory.java
new file mode 100644
index 000000000..f337339c3
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultBHttpClientConnectionFactory.java
@@ -0,0 +1,103 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import ch.boye.httpclientandroidlib.HttpConnectionFactory;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.config.ConnectionConfig;
+import ch.boye.httpclientandroidlib.entity.ContentLengthStrategy;
+import ch.boye.httpclientandroidlib.io.HttpMessageParserFactory;
+import ch.boye.httpclientandroidlib.io.HttpMessageWriterFactory;
+
+import java.io.IOException;
+import java.net.Socket;
+
+/**
+ * Default factory for {@link ch.boye.httpclientandroidlib.HttpClientConnection}s.
+ *
+ * @since 4.3
+ */
+@Immutable
+public class DefaultBHttpClientConnectionFactory
+ implements HttpConnectionFactory {
+
+ public static final DefaultBHttpClientConnectionFactory INSTANCE = new DefaultBHttpClientConnectionFactory();
+
+ private final ConnectionConfig cconfig;
+ private final ContentLengthStrategy incomingContentStrategy;
+ private final ContentLengthStrategy outgoingContentStrategy;
+ private final HttpMessageWriterFactory requestWriterFactory;
+ private final HttpMessageParserFactory responseParserFactory;
+
+ public DefaultBHttpClientConnectionFactory(
+ final ConnectionConfig cconfig,
+ final ContentLengthStrategy incomingContentStrategy,
+ final ContentLengthStrategy outgoingContentStrategy,
+ final HttpMessageWriterFactory requestWriterFactory,
+ final HttpMessageParserFactory responseParserFactory) {
+ super();
+ this.cconfig = cconfig != null ? cconfig : ConnectionConfig.DEFAULT;
+ this.incomingContentStrategy = incomingContentStrategy;
+ this.outgoingContentStrategy = outgoingContentStrategy;
+ this.requestWriterFactory = requestWriterFactory;
+ this.responseParserFactory = responseParserFactory;
+ }
+
+ public DefaultBHttpClientConnectionFactory(
+ final ConnectionConfig cconfig,
+ final HttpMessageWriterFactory requestWriterFactory,
+ final HttpMessageParserFactory responseParserFactory) {
+ this(cconfig, null, null, requestWriterFactory, responseParserFactory);
+ }
+
+ public DefaultBHttpClientConnectionFactory(final ConnectionConfig cconfig) {
+ this(cconfig, null, null, null, null);
+ }
+
+ public DefaultBHttpClientConnectionFactory() {
+ this(null, null, null, null, null);
+ }
+
+ public DefaultBHttpClientConnection createConnection(final Socket socket) throws IOException {
+ final DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(
+ this.cconfig.getBufferSize(),
+ this.cconfig.getFragmentSizeHint(),
+ ConnSupport.createDecoder(this.cconfig),
+ ConnSupport.createEncoder(this.cconfig),
+ this.cconfig.getMessageConstraints(),
+ this.incomingContentStrategy,
+ this.outgoingContentStrategy,
+ this.requestWriterFactory,
+ this.responseParserFactory);
+ conn.bind(socket);
+ return conn;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultBHttpServerConnection.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultBHttpServerConnection.java
new file mode 100644
index 000000000..6ee4fb740
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultBHttpServerConnection.java
@@ -0,0 +1,174 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.Socket;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CharsetEncoder;
+
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpServerConnection;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.config.MessageConstraints;
+import ch.boye.httpclientandroidlib.entity.ContentLengthStrategy;
+import ch.boye.httpclientandroidlib.impl.entity.DisallowIdentityContentLengthStrategy;
+import ch.boye.httpclientandroidlib.impl.io.DefaultHttpRequestParserFactory;
+import ch.boye.httpclientandroidlib.impl.io.DefaultHttpResponseWriterFactory;
+import ch.boye.httpclientandroidlib.io.HttpMessageParser;
+import ch.boye.httpclientandroidlib.io.HttpMessageParserFactory;
+import ch.boye.httpclientandroidlib.io.HttpMessageWriter;
+import ch.boye.httpclientandroidlib.io.HttpMessageWriterFactory;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Default implementation of {@link HttpServerConnection}.
+ *
+ * @since 4.3
+ */
+@NotThreadSafe
+public class DefaultBHttpServerConnection extends BHttpConnectionBase
+ implements HttpServerConnection {
+
+ private final HttpMessageParser requestParser;
+ private final HttpMessageWriter responseWriter;
+
+ /**
+ * Creates new instance of DefaultBHttpServerConnection.
+ *
+ * @param buffersize buffer size. Must be a positive number.
+ * @param fragmentSizeHint fragment size hint.
+ * @param chardecoder decoder to be used for decoding HTTP protocol elements.
+ * If null simple type cast will be used for byte to char conversion.
+ * @param charencoder encoder to be used for encoding HTTP protocol elements.
+ * If null simple type cast will be used for char to byte conversion.
+ * @param constraints Message constraints. If null
+ * {@link MessageConstraints#DEFAULT} will be used.
+ * @param incomingContentStrategy incoming content length strategy. If null
+ * {@link DisallowIdentityContentLengthStrategy#INSTANCE} will be used.
+ * @param outgoingContentStrategy outgoing content length strategy. If null
+ * {@link ch.boye.httpclientandroidlib.impl.entity.StrictContentLengthStrategy#INSTANCE} will be used.
+ * @param requestParserFactory request parser factory. If null
+ * {@link DefaultHttpRequestParserFactory#INSTANCE} will be used.
+ * @param responseWriterFactory response writer factory. If null
+ * {@link DefaultHttpResponseWriterFactory#INSTANCE} will be used.
+ */
+ public DefaultBHttpServerConnection(
+ final int buffersize,
+ final int fragmentSizeHint,
+ final CharsetDecoder chardecoder,
+ final CharsetEncoder charencoder,
+ final MessageConstraints constraints,
+ final ContentLengthStrategy incomingContentStrategy,
+ final ContentLengthStrategy outgoingContentStrategy,
+ final HttpMessageParserFactory requestParserFactory,
+ final HttpMessageWriterFactory responseWriterFactory) {
+ super(buffersize, fragmentSizeHint, chardecoder, charencoder, constraints,
+ incomingContentStrategy != null ? incomingContentStrategy :
+ DisallowIdentityContentLengthStrategy.INSTANCE, outgoingContentStrategy);
+ this.requestParser = (requestParserFactory != null ? requestParserFactory :
+ DefaultHttpRequestParserFactory.INSTANCE).create(getSessionInputBuffer(), constraints);
+ this.responseWriter = (responseWriterFactory != null ? responseWriterFactory :
+ DefaultHttpResponseWriterFactory.INSTANCE).create(getSessionOutputBuffer());
+ }
+
+ public DefaultBHttpServerConnection(
+ final int buffersize,
+ final CharsetDecoder chardecoder,
+ final CharsetEncoder charencoder,
+ final MessageConstraints constraints) {
+ this(buffersize, buffersize, chardecoder, charencoder, constraints, null, null, null, null);
+ }
+
+ public DefaultBHttpServerConnection(final int buffersize) {
+ this(buffersize, buffersize, null, null, null, null, null, null, null);
+ }
+
+ protected void onRequestReceived(final HttpRequest request) {
+ }
+
+ protected void onResponseSubmitted(final HttpResponse response) {
+ }
+
+ @Override
+ public void bind(final Socket socket) throws IOException {
+ super.bind(socket);
+ }
+
+ public HttpRequest receiveRequestHeader()
+ throws HttpException, IOException {
+ ensureOpen();
+ final HttpRequest request = this.requestParser.parse();
+ onRequestReceived(request);
+ incrementRequestCount();
+ return request;
+ }
+
+ public void receiveRequestEntity(final HttpEntityEnclosingRequest request)
+ throws HttpException, IOException {
+ Args.notNull(request, "HTTP request");
+ ensureOpen();
+ final HttpEntity entity = prepareInput(request);
+ request.setEntity(entity);
+ }
+
+ public void sendResponseHeader(final HttpResponse response)
+ throws HttpException, IOException {
+ Args.notNull(response, "HTTP response");
+ ensureOpen();
+ this.responseWriter.write(response);
+ onResponseSubmitted(response);
+ if (response.getStatusLine().getStatusCode() >= 200) {
+ incrementResponseCount();
+ }
+ }
+
+ public void sendResponseEntity(final HttpResponse response)
+ throws HttpException, IOException {
+ Args.notNull(response, "HTTP response");
+ ensureOpen();
+ final HttpEntity entity = response.getEntity();
+ if (entity == null) {
+ return;
+ }
+ final OutputStream outstream = prepareOutput(response);
+ entity.writeTo(outstream);
+ outstream.close();
+ }
+
+ public void flush() throws IOException {
+ ensureOpen();
+ doFlush();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultBHttpServerConnectionFactory.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultBHttpServerConnectionFactory.java
new file mode 100644
index 000000000..a312320aa
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultBHttpServerConnectionFactory.java
@@ -0,0 +1,103 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import ch.boye.httpclientandroidlib.HttpConnectionFactory;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.config.ConnectionConfig;
+import ch.boye.httpclientandroidlib.entity.ContentLengthStrategy;
+import ch.boye.httpclientandroidlib.io.HttpMessageParserFactory;
+import ch.boye.httpclientandroidlib.io.HttpMessageWriterFactory;
+
+import java.io.IOException;
+import java.net.Socket;
+
+/**
+ * Default factory for {@link ch.boye.httpclientandroidlib.HttpServerConnection}s.
+ *
+ * @since 4.3
+ */
+@Immutable
+public class DefaultBHttpServerConnectionFactory
+ implements HttpConnectionFactory {
+
+ public static final DefaultBHttpServerConnectionFactory INSTANCE = new DefaultBHttpServerConnectionFactory();
+
+ private final ConnectionConfig cconfig;
+ private final ContentLengthStrategy incomingContentStrategy;
+ private final ContentLengthStrategy outgoingContentStrategy;
+ private final HttpMessageParserFactory requestParserFactory;
+ private final HttpMessageWriterFactory responseWriterFactory;
+
+ public DefaultBHttpServerConnectionFactory(
+ final ConnectionConfig cconfig,
+ final ContentLengthStrategy incomingContentStrategy,
+ final ContentLengthStrategy outgoingContentStrategy,
+ final HttpMessageParserFactory requestParserFactory,
+ final HttpMessageWriterFactory responseWriterFactory) {
+ super();
+ this.cconfig = cconfig != null ? cconfig : ConnectionConfig.DEFAULT;
+ this.incomingContentStrategy = incomingContentStrategy;
+ this.outgoingContentStrategy = outgoingContentStrategy;
+ this.requestParserFactory = requestParserFactory;
+ this.responseWriterFactory = responseWriterFactory;
+ }
+
+ public DefaultBHttpServerConnectionFactory(
+ final ConnectionConfig cconfig,
+ final HttpMessageParserFactory requestParserFactory,
+ final HttpMessageWriterFactory responseWriterFactory) {
+ this(cconfig, null, null, requestParserFactory, responseWriterFactory);
+ }
+
+ public DefaultBHttpServerConnectionFactory(final ConnectionConfig cconfig) {
+ this(cconfig, null, null, null, null);
+ }
+
+ public DefaultBHttpServerConnectionFactory() {
+ this(null, null, null, null, null);
+ }
+
+ public DefaultBHttpServerConnection createConnection(final Socket socket) throws IOException {
+ final DefaultBHttpServerConnection conn = new DefaultBHttpServerConnection(
+ this.cconfig.getBufferSize(),
+ this.cconfig.getFragmentSizeHint(),
+ ConnSupport.createDecoder(this.cconfig),
+ ConnSupport.createEncoder(this.cconfig),
+ this.cconfig.getMessageConstraints(),
+ this.incomingContentStrategy,
+ this.outgoingContentStrategy,
+ this.requestParserFactory,
+ this.responseWriterFactory);
+ conn.bind(socket);
+ return conn;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultConnectionReuseStrategy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultConnectionReuseStrategy.java
new file mode 100644
index 000000000..b58127e5f
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultConnectionReuseStrategy.java
@@ -0,0 +1,189 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import ch.boye.httpclientandroidlib.ConnectionReuseStrategy;
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HeaderIterator;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.HttpVersion;
+import ch.boye.httpclientandroidlib.ParseException;
+import ch.boye.httpclientandroidlib.ProtocolVersion;
+import ch.boye.httpclientandroidlib.TokenIterator;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.message.BasicTokenIterator;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Default implementation of a strategy deciding about connection re-use.
+ * The default implementation first checks some basics, for example
+ * whether the connection is still open or whether the end of the
+ * request entity can be determined without closing the connection.
+ * If these checks pass, the tokens in the Connection header will
+ * be examined. In the absence of a Connection header, the
+ * non-standard but commonly used Proxy-Connection header takes
+ * it's role. A token close indicates that the connection cannot
+ * be reused. If there is no such token, a token keep-alive
+ * indicates that the connection should be re-used. If neither token is found,
+ * or if there are no Connection headers, the default policy for
+ * the HTTP version is applied. Since HTTP/1.1, connections are
+ * re-used by default. Up until HTTP/1.0, connections are not
+ * re-used by default.
+ *
+ * @since 4.0
+ */
+@Immutable
+public class DefaultConnectionReuseStrategy implements ConnectionReuseStrategy {
+
+ public static final DefaultConnectionReuseStrategy INSTANCE = new DefaultConnectionReuseStrategy();
+
+ public DefaultConnectionReuseStrategy() {
+ super();
+ }
+
+ // see interface ConnectionReuseStrategy
+ public boolean keepAlive(final HttpResponse response,
+ final HttpContext context) {
+ Args.notNull(response, "HTTP response");
+ Args.notNull(context, "HTTP context");
+
+ // Check for a self-terminating entity. If the end of the entity will
+ // be indicated by closing the connection, there is no keep-alive.
+ final ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
+ final Header teh = response.getFirstHeader(HTTP.TRANSFER_ENCODING);
+ if (teh != null) {
+ if (!HTTP.CHUNK_CODING.equalsIgnoreCase(teh.getValue())) {
+ return false;
+ }
+ } else {
+ if (canResponseHaveBody(response)) {
+ final Header[] clhs = response.getHeaders(HTTP.CONTENT_LEN);
+ // Do not reuse if not properly content-length delimited
+ if (clhs.length == 1) {
+ final Header clh = clhs[0];
+ try {
+ final int contentLen = Integer.parseInt(clh.getValue());
+ if (contentLen < 0) {
+ return false;
+ }
+ } catch (final NumberFormatException ex) {
+ return false;
+ }
+ } else {
+ return false;
+ }
+ }
+ }
+
+ // Check for the "Connection" header. If that is absent, check for
+ // the "Proxy-Connection" header. The latter is an unspecified and
+ // broken but unfortunately common extension of HTTP.
+ HeaderIterator hit = response.headerIterator(HTTP.CONN_DIRECTIVE);
+ if (!hit.hasNext()) {
+ hit = response.headerIterator("Proxy-Connection");
+ }
+
+ // Experimental usage of the "Connection" header in HTTP/1.0 is
+ // documented in RFC 2068, section 19.7.1. A token "keep-alive" is
+ // used to indicate that the connection should be persistent.
+ // Note that the final specification of HTTP/1.1 in RFC 2616 does not
+ // include this information. Neither is the "Connection" header
+ // mentioned in RFC 1945, which informally describes HTTP/1.0.
+ //
+ // RFC 2616 specifies "close" as the only connection token with a
+ // specific meaning: it disables persistent connections.
+ //
+ // The "Proxy-Connection" header is not formally specified anywhere,
+ // but is commonly used to carry one token, "close" or "keep-alive".
+ // The "Connection" header, on the other hand, is defined as a
+ // sequence of tokens, where each token is a header name, and the
+ // token "close" has the above-mentioned additional meaning.
+ //
+ // To get through this mess, we treat the "Proxy-Connection" header
+ // in exactly the same way as the "Connection" header, but only if
+ // the latter is missing. We scan the sequence of tokens for both
+ // "close" and "keep-alive". As "close" is specified by RFC 2068,
+ // it takes precedence and indicates a non-persistent connection.
+ // If there is no "close" but a "keep-alive", we take the hint.
+
+ if (hit.hasNext()) {
+ try {
+ final TokenIterator ti = createTokenIterator(hit);
+ boolean keepalive = false;
+ while (ti.hasNext()) {
+ final String token = ti.nextToken();
+ if (HTTP.CONN_CLOSE.equalsIgnoreCase(token)) {
+ return false;
+ } else if (HTTP.CONN_KEEP_ALIVE.equalsIgnoreCase(token)) {
+ // continue the loop, there may be a "close" afterwards
+ keepalive = true;
+ }
+ }
+ if (keepalive)
+ {
+ return true;
+ // neither "close" nor "keep-alive", use default policy
+ }
+
+ } catch (final ParseException px) {
+ // invalid connection header means no persistent connection
+ // we don't have logging in HttpCore, so the exception is lost
+ return false;
+ }
+ }
+
+ // default since HTTP/1.1 is persistent, before it was non-persistent
+ return !ver.lessEquals(HttpVersion.HTTP_1_0);
+ }
+
+
+ /**
+ * Creates a token iterator from a header iterator.
+ * This method can be overridden to replace the implementation of
+ * the token iterator.
+ *
+ * @param hit the header iterator
+ *
+ * @return the token iterator
+ */
+ protected TokenIterator createTokenIterator(final HeaderIterator hit) {
+ return new BasicTokenIterator(hit);
+ }
+
+ private boolean canResponseHaveBody(final HttpResponse response) {
+ final int status = response.getStatusLine().getStatusCode();
+ return status >= HttpStatus.SC_OK
+ && status != HttpStatus.SC_NO_CONTENT
+ && status != HttpStatus.SC_NOT_MODIFIED
+ && status != HttpStatus.SC_RESET_CONTENT;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultHttpClientConnection.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultHttpClientConnection.java
new file mode 100644
index 000000000..adb597863
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultHttpClientConnection.java
@@ -0,0 +1,70 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import java.io.IOException;
+import java.net.Socket;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.params.CoreConnectionPNames;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Default implementation of a client-side HTTP connection.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link DefaultBHttpClientConnection}
+ */
+@NotThreadSafe
+@Deprecated
+public class DefaultHttpClientConnection extends SocketHttpClientConnection {
+
+ public DefaultHttpClientConnection() {
+ super();
+ }
+
+ @Override
+ public void bind(
+ final Socket socket,
+ final HttpParams params) throws IOException {
+ Args.notNull(socket, "Socket");
+ Args.notNull(params, "HTTP parameters");
+ assertNotOpen();
+ socket.setTcpNoDelay(params.getBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true));
+ socket.setSoTimeout(params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0));
+ socket.setKeepAlive(params.getBooleanParameter(CoreConnectionPNames.SO_KEEPALIVE, false));
+ final int linger = params.getIntParameter(CoreConnectionPNames.SO_LINGER, -1);
+ if (linger >= 0) {
+ socket.setSoLinger(linger > 0, linger);
+ }
+ super.bind(socket, params);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultHttpRequestFactory.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultHttpRequestFactory.java
new file mode 100644
index 000000000..0491e94bd
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultHttpRequestFactory.java
@@ -0,0 +1,109 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpRequestFactory;
+import ch.boye.httpclientandroidlib.MethodNotSupportedException;
+import ch.boye.httpclientandroidlib.RequestLine;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.message.BasicHttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.message.BasicHttpRequest;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Default factory for creating {@link HttpRequest} objects.
+ *
+ * @since 4.0
+ */
+@Immutable
+public class DefaultHttpRequestFactory implements HttpRequestFactory {
+
+ public static final DefaultHttpRequestFactory INSTANCE = new DefaultHttpRequestFactory();
+
+ private static final String[] RFC2616_COMMON_METHODS = {
+ "GET"
+ };
+
+ private static final String[] RFC2616_ENTITY_ENC_METHODS = {
+ "POST",
+ "PUT"
+ };
+
+ private static final String[] RFC2616_SPECIAL_METHODS = {
+ "HEAD",
+ "OPTIONS",
+ "DELETE",
+ "TRACE",
+ "CONNECT"
+ };
+
+
+ public DefaultHttpRequestFactory() {
+ super();
+ }
+
+ private static boolean isOneOf(final String[] methods, final String method) {
+ for (final String method2 : methods) {
+ if (method2.equalsIgnoreCase(method)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public HttpRequest newHttpRequest(final RequestLine requestline)
+ throws MethodNotSupportedException {
+ Args.notNull(requestline, "Request line");
+ final String method = requestline.getMethod();
+ if (isOneOf(RFC2616_COMMON_METHODS, method)) {
+ return new BasicHttpRequest(requestline);
+ } else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) {
+ return new BasicHttpEntityEnclosingRequest(requestline);
+ } else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) {
+ return new BasicHttpRequest(requestline);
+ } else {
+ throw new MethodNotSupportedException(method + " method not supported");
+ }
+ }
+
+ public HttpRequest newHttpRequest(final String method, final String uri)
+ throws MethodNotSupportedException {
+ if (isOneOf(RFC2616_COMMON_METHODS, method)) {
+ return new BasicHttpRequest(method, uri);
+ } else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) {
+ return new BasicHttpEntityEnclosingRequest(method, uri);
+ } else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) {
+ return new BasicHttpRequest(method, uri);
+ } else {
+ throw new MethodNotSupportedException(method
+ + " method not supported");
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultHttpResponseFactory.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultHttpResponseFactory.java
new file mode 100644
index 000000000..21511b9ff
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultHttpResponseFactory.java
@@ -0,0 +1,109 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import java.util.Locale;
+
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpResponseFactory;
+import ch.boye.httpclientandroidlib.ProtocolVersion;
+import ch.boye.httpclientandroidlib.ReasonPhraseCatalog;
+import ch.boye.httpclientandroidlib.StatusLine;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.message.BasicHttpResponse;
+import ch.boye.httpclientandroidlib.message.BasicStatusLine;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Default factory for creating {@link HttpResponse} objects.
+ *
+ * @since 4.0
+ */
+@Immutable
+public class DefaultHttpResponseFactory implements HttpResponseFactory {
+
+ public static final DefaultHttpResponseFactory INSTANCE = new DefaultHttpResponseFactory();
+
+ /** The catalog for looking up reason phrases. */
+ protected final ReasonPhraseCatalog reasonCatalog;
+
+
+ /**
+ * Creates a new response factory with the given catalog.
+ *
+ * @param catalog the catalog of reason phrases
+ */
+ public DefaultHttpResponseFactory(final ReasonPhraseCatalog catalog) {
+ this.reasonCatalog = Args.notNull(catalog, "Reason phrase catalog");
+ }
+
+ /**
+ * Creates a new response factory with the default catalog.
+ * The default catalog is {@link EnglishReasonPhraseCatalog}.
+ */
+ public DefaultHttpResponseFactory() {
+ this(EnglishReasonPhraseCatalog.INSTANCE);
+ }
+
+
+ // non-javadoc, see interface HttpResponseFactory
+ public HttpResponse newHttpResponse(
+ final ProtocolVersion ver,
+ final int status,
+ final HttpContext context) {
+ Args.notNull(ver, "HTTP version");
+ final Locale loc = determineLocale(context);
+ final String reason = this.reasonCatalog.getReason(status, loc);
+ final StatusLine statusline = new BasicStatusLine(ver, status, reason);
+ return new BasicHttpResponse(statusline, this.reasonCatalog, loc);
+ }
+
+
+ // non-javadoc, see interface HttpResponseFactory
+ public HttpResponse newHttpResponse(
+ final StatusLine statusline,
+ final HttpContext context) {
+ Args.notNull(statusline, "Status line");
+ return new BasicHttpResponse(statusline, this.reasonCatalog, determineLocale(context));
+ }
+
+ /**
+ * Determines the locale of the response.
+ * The implementation in this class always returns the default locale.
+ *
+ * @param context the context from which to determine the locale, or
+ * null to use the default locale
+ *
+ * @return the locale for the response, never null
+ */
+ protected Locale determineLocale(final HttpContext context) {
+ return Locale.getDefault();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultHttpServerConnection.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultHttpServerConnection.java
new file mode 100644
index 000000000..8162e6107
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/DefaultHttpServerConnection.java
@@ -0,0 +1,71 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import java.io.IOException;
+import java.net.Socket;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.params.CoreConnectionPNames;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Default implementation of a server-side HTTP connection.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link DefaultBHttpServerConnection}
+ */
+@NotThreadSafe
+@Deprecated
+public class DefaultHttpServerConnection extends SocketHttpServerConnection {
+
+ public DefaultHttpServerConnection() {
+ super();
+ }
+
+ @Override
+ public void bind(final Socket socket, final HttpParams params) throws IOException {
+ Args.notNull(socket, "Socket");
+ Args.notNull(params, "HTTP parameters");
+ assertNotOpen();
+ socket.setTcpNoDelay(params.getBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true));
+ socket.setSoTimeout(params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0));
+ socket.setKeepAlive(params.getBooleanParameter(CoreConnectionPNames.SO_KEEPALIVE, false));
+ final int linger = params.getIntParameter(CoreConnectionPNames.SO_LINGER, -1);
+ if (linger >= 0) {
+ socket.setSoLinger(linger > 0, linger);
+ }
+ if (linger >= 0) {
+ socket.setSoLinger(linger > 0, linger);
+ }
+ super.bind(socket, params);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/EnglishReasonPhraseCatalog.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/EnglishReasonPhraseCatalog.java
new file mode 100644
index 000000000..51e435c0a
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/EnglishReasonPhraseCatalog.java
@@ -0,0 +1,224 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import java.util.Locale;
+
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.ReasonPhraseCatalog;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * English reason phrases for HTTP status codes.
+ * All status codes defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and
+ * RFC2518 (WebDAV) are supported.
+ *
+ * @since 4.0
+ */
+@Immutable
+public class EnglishReasonPhraseCatalog implements ReasonPhraseCatalog {
+
+ // static array with english reason phrases defined below
+
+ /**
+ * The default instance of this catalog.
+ * This catalog is thread safe, so there typically
+ * is no need to create other instances.
+ */
+ public final static EnglishReasonPhraseCatalog INSTANCE =
+ new EnglishReasonPhraseCatalog();
+
+
+ /**
+ * Restricted default constructor, for derived classes.
+ * If you need an instance of this class, use {@link #INSTANCE INSTANCE}.
+ */
+ protected EnglishReasonPhraseCatalog() {
+ // no body
+ }
+
+
+ /**
+ * Obtains the reason phrase for a status code.
+ *
+ * @param status the status code, in the range 100-599
+ * @param loc ignored
+ *
+ * @return the reason phrase, or null
+ */
+ public String getReason(final int status, final Locale loc) {
+ Args.check(status >= 100 && status < 600, "Unknown category for status code " + status);
+ final int category = status / 100;
+ final int subcode = status - 100*category;
+
+ String reason = null;
+ if (REASON_PHRASES[category].length > subcode) {
+ reason = REASON_PHRASES[category][subcode];
+ }
+
+ return reason;
+ }
+
+
+ /** Reason phrases lookup table. */
+ private static final String[][] REASON_PHRASES = new String[][]{
+ null,
+ new String[3], // 1xx
+ new String[8], // 2xx
+ new String[8], // 3xx
+ new String[25], // 4xx
+ new String[8] // 5xx
+ };
+
+
+
+ /**
+ * Stores the given reason phrase, by status code.
+ * Helper method to initialize the static lookup table.
+ *
+ * @param status the status code for which to define the phrase
+ * @param reason the reason phrase for this status code
+ */
+ private static void setReason(final int status, final String reason) {
+ final int category = status / 100;
+ final int subcode = status - 100*category;
+ REASON_PHRASES[category][subcode] = reason;
+ }
+
+
+ // ----------------------------------------------------- Static Initializer
+
+ /** Set up status code to "reason phrase" map. */
+ static {
+ // HTTP 1.0 Server status codes -- see RFC 1945
+ setReason(HttpStatus.SC_OK,
+ "OK");
+ setReason(HttpStatus.SC_CREATED,
+ "Created");
+ setReason(HttpStatus.SC_ACCEPTED,
+ "Accepted");
+ setReason(HttpStatus.SC_NO_CONTENT,
+ "No Content");
+ setReason(HttpStatus.SC_MOVED_PERMANENTLY,
+ "Moved Permanently");
+ setReason(HttpStatus.SC_MOVED_TEMPORARILY,
+ "Moved Temporarily");
+ setReason(HttpStatus.SC_NOT_MODIFIED,
+ "Not Modified");
+ setReason(HttpStatus.SC_BAD_REQUEST,
+ "Bad Request");
+ setReason(HttpStatus.SC_UNAUTHORIZED,
+ "Unauthorized");
+ setReason(HttpStatus.SC_FORBIDDEN,
+ "Forbidden");
+ setReason(HttpStatus.SC_NOT_FOUND,
+ "Not Found");
+ setReason(HttpStatus.SC_INTERNAL_SERVER_ERROR,
+ "Internal Server Error");
+ setReason(HttpStatus.SC_NOT_IMPLEMENTED,
+ "Not Implemented");
+ setReason(HttpStatus.SC_BAD_GATEWAY,
+ "Bad Gateway");
+ setReason(HttpStatus.SC_SERVICE_UNAVAILABLE,
+ "Service Unavailable");
+
+ // HTTP 1.1 Server status codes -- see RFC 2048
+ setReason(HttpStatus.SC_CONTINUE,
+ "Continue");
+ setReason(HttpStatus.SC_TEMPORARY_REDIRECT,
+ "Temporary Redirect");
+ setReason(HttpStatus.SC_METHOD_NOT_ALLOWED,
+ "Method Not Allowed");
+ setReason(HttpStatus.SC_CONFLICT,
+ "Conflict");
+ setReason(HttpStatus.SC_PRECONDITION_FAILED,
+ "Precondition Failed");
+ setReason(HttpStatus.SC_REQUEST_TOO_LONG,
+ "Request Too Long");
+ setReason(HttpStatus.SC_REQUEST_URI_TOO_LONG,
+ "Request-URI Too Long");
+ setReason(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported Media Type");
+ setReason(HttpStatus.SC_MULTIPLE_CHOICES,
+ "Multiple Choices");
+ setReason(HttpStatus.SC_SEE_OTHER,
+ "See Other");
+ setReason(HttpStatus.SC_USE_PROXY,
+ "Use Proxy");
+ setReason(HttpStatus.SC_PAYMENT_REQUIRED,
+ "Payment Required");
+ setReason(HttpStatus.SC_NOT_ACCEPTABLE,
+ "Not Acceptable");
+ setReason(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED,
+ "Proxy Authentication Required");
+ setReason(HttpStatus.SC_REQUEST_TIMEOUT,
+ "Request Timeout");
+
+ setReason(HttpStatus.SC_SWITCHING_PROTOCOLS,
+ "Switching Protocols");
+ setReason(HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION,
+ "Non Authoritative Information");
+ setReason(HttpStatus.SC_RESET_CONTENT,
+ "Reset Content");
+ setReason(HttpStatus.SC_PARTIAL_CONTENT,
+ "Partial Content");
+ setReason(HttpStatus.SC_GATEWAY_TIMEOUT,
+ "Gateway Timeout");
+ setReason(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED,
+ "Http Version Not Supported");
+ setReason(HttpStatus.SC_GONE,
+ "Gone");
+ setReason(HttpStatus.SC_LENGTH_REQUIRED,
+ "Length Required");
+ setReason(HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE,
+ "Requested Range Not Satisfiable");
+ setReason(HttpStatus.SC_EXPECTATION_FAILED,
+ "Expectation Failed");
+
+ // WebDAV Server-specific status codes
+ setReason(HttpStatus.SC_PROCESSING,
+ "Processing");
+ setReason(HttpStatus.SC_MULTI_STATUS,
+ "Multi-Status");
+ setReason(HttpStatus.SC_UNPROCESSABLE_ENTITY,
+ "Unprocessable Entity");
+ setReason(HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE,
+ "Insufficient Space On Resource");
+ setReason(HttpStatus.SC_METHOD_FAILURE,
+ "Method Failure");
+ setReason(HttpStatus.SC_LOCKED,
+ "Locked");
+ setReason(HttpStatus.SC_INSUFFICIENT_STORAGE,
+ "Insufficient Storage");
+ setReason(HttpStatus.SC_FAILED_DEPENDENCY,
+ "Failed Dependency");
+ }
+
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/HttpConnectionMetricsImpl.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/HttpConnectionMetricsImpl.java
new file mode 100644
index 000000000..bfc415082
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/HttpConnectionMetricsImpl.java
@@ -0,0 +1,148 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import ch.boye.httpclientandroidlib.HttpConnectionMetrics;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.io.HttpTransportMetrics;
+
+/**
+ * Default implementation of the {@link HttpConnectionMetrics} interface.
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class HttpConnectionMetricsImpl implements HttpConnectionMetrics {
+
+ public static final String REQUEST_COUNT = "http.request-count";
+ public static final String RESPONSE_COUNT = "http.response-count";
+ public static final String SENT_BYTES_COUNT = "http.sent-bytes-count";
+ public static final String RECEIVED_BYTES_COUNT = "http.received-bytes-count";
+
+ private final HttpTransportMetrics inTransportMetric;
+ private final HttpTransportMetrics outTransportMetric;
+ private long requestCount = 0;
+ private long responseCount = 0;
+
+ /**
+ * The cache map for all metrics values.
+ */
+ private Map metricsCache;
+
+ public HttpConnectionMetricsImpl(
+ final HttpTransportMetrics inTransportMetric,
+ final HttpTransportMetrics outTransportMetric) {
+ super();
+ this.inTransportMetric = inTransportMetric;
+ this.outTransportMetric = outTransportMetric;
+ }
+
+ /* ------------------ Public interface method -------------------------- */
+
+ public long getReceivedBytesCount() {
+ if (this.inTransportMetric != null) {
+ return this.inTransportMetric.getBytesTransferred();
+ } else {
+ return -1;
+ }
+ }
+
+ public long getSentBytesCount() {
+ if (this.outTransportMetric != null) {
+ return this.outTransportMetric.getBytesTransferred();
+ } else {
+ return -1;
+ }
+ }
+
+ public long getRequestCount() {
+ return this.requestCount;
+ }
+
+ public void incrementRequestCount() {
+ this.requestCount++;
+ }
+
+ public long getResponseCount() {
+ return this.responseCount;
+ }
+
+ public void incrementResponseCount() {
+ this.responseCount++;
+ }
+
+ public Object getMetric(final String metricName) {
+ Object value = null;
+ if (this.metricsCache != null) {
+ value = this.metricsCache.get(metricName);
+ }
+ if (value == null) {
+ if (REQUEST_COUNT.equals(metricName)) {
+ value = Long.valueOf(requestCount);
+ } else if (RESPONSE_COUNT.equals(metricName)) {
+ value = Long.valueOf(responseCount);
+ } else if (RECEIVED_BYTES_COUNT.equals(metricName)) {
+ if (this.inTransportMetric != null) {
+ return Long.valueOf(this.inTransportMetric.getBytesTransferred());
+ } else {
+ return null;
+ }
+ } else if (SENT_BYTES_COUNT.equals(metricName)) {
+ if (this.outTransportMetric != null) {
+ return Long.valueOf(this.outTransportMetric.getBytesTransferred());
+ } else {
+ return null;
+ }
+ }
+ }
+ return value;
+ }
+
+ public void setMetric(final String metricName, final Object obj) {
+ if (this.metricsCache == null) {
+ this.metricsCache = new HashMap();
+ }
+ this.metricsCache.put(metricName, obj);
+ }
+
+ public void reset() {
+ if (this.outTransportMetric != null) {
+ this.outTransportMetric.reset();
+ }
+ if (this.inTransportMetric != null) {
+ this.inTransportMetric.reset();
+ }
+ this.requestCount = 0;
+ this.responseCount = 0;
+ this.metricsCache = null;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/NoConnectionReuseStrategy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/NoConnectionReuseStrategy.java
new file mode 100644
index 000000000..fdf312844
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/NoConnectionReuseStrategy.java
@@ -0,0 +1,53 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import ch.boye.httpclientandroidlib.ConnectionReuseStrategy;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+/**
+ * A strategy that never re-uses a connection.
+ *
+ * @since 4.0
+ */
+@Immutable
+public class NoConnectionReuseStrategy implements ConnectionReuseStrategy {
+
+ public static final NoConnectionReuseStrategy INSTANCE = new NoConnectionReuseStrategy();
+
+ public NoConnectionReuseStrategy() {
+ super();
+ }
+
+ public boolean keepAlive(final HttpResponse response, final HttpContext context) {
+ return false;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/SocketHttpClientConnection.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/SocketHttpClientConnection.java
new file mode 100644
index 000000000..72f2f7e87
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/SocketHttpClientConnection.java
@@ -0,0 +1,283 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketException;
+
+import ch.boye.httpclientandroidlib.HttpInetConnection;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.impl.io.SocketInputBuffer;
+import ch.boye.httpclientandroidlib.impl.io.SocketOutputBuffer;
+import ch.boye.httpclientandroidlib.io.SessionInputBuffer;
+import ch.boye.httpclientandroidlib.io.SessionOutputBuffer;
+import ch.boye.httpclientandroidlib.params.CoreConnectionPNames;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.Asserts;
+
+/**
+ * Implementation of a client-side HTTP connection that can be bound to an
+ * arbitrary {@link Socket} for receiving data from and transmitting data to
+ * a remote server.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link DefaultBHttpClientConnection}
+ */
+@NotThreadSafe
+@Deprecated
+public class SocketHttpClientConnection
+ extends AbstractHttpClientConnection implements HttpInetConnection {
+
+ private volatile boolean open;
+ private volatile Socket socket = null;
+
+ public SocketHttpClientConnection() {
+ super();
+ }
+
+ protected void assertNotOpen() {
+ Asserts.check(!this.open, "Connection is already open");
+ }
+
+ @Override
+ protected void assertOpen() {
+ Asserts.check(this.open, "Connection is not open");
+ }
+
+ /**
+ * Creates an instance of {@link SocketInputBuffer} to be used for
+ * receiving data from the given {@link Socket}.
+ *
+ * This method can be overridden in a super class in order to provide
+ * a custom implementation of {@link SessionInputBuffer} interface.
+ *
+ * @see SocketInputBuffer#SocketInputBuffer(Socket, int, HttpParams)
+ *
+ * @param socket the socket.
+ * @param buffersize the buffer size.
+ * @param params HTTP parameters.
+ * @return session input buffer.
+ * @throws IOException in case of an I/O error.
+ */
+ protected SessionInputBuffer createSessionInputBuffer(
+ final Socket socket,
+ final int buffersize,
+ final HttpParams params) throws IOException {
+ return new SocketInputBuffer(socket, buffersize, params);
+ }
+
+ /**
+ * Creates an instance of {@link SessionOutputBuffer} to be used for
+ * sending data to the given {@link Socket}.
+ *
+ * This method can be overridden in a super class in order to provide
+ * a custom implementation of {@link SocketOutputBuffer} interface.
+ *
+ * @see SocketOutputBuffer#SocketOutputBuffer(Socket, int, HttpParams)
+ *
+ * @param socket the socket.
+ * @param buffersize the buffer size.
+ * @param params HTTP parameters.
+ * @return session output buffer.
+ * @throws IOException in case of an I/O error.
+ */
+ protected SessionOutputBuffer createSessionOutputBuffer(
+ final Socket socket,
+ final int buffersize,
+ final HttpParams params) throws IOException {
+ return new SocketOutputBuffer(socket, buffersize, params);
+ }
+
+ /**
+ * Binds this connection to the given {@link Socket}. This socket will be
+ * used by the connection to send and receive data.
+ *
+ * This method will invoke {@link #createSessionInputBuffer(Socket, int, HttpParams)}
+ * and {@link #createSessionOutputBuffer(Socket, int, HttpParams)} methods
+ * to create session input / output buffers bound to this socket and then
+ * will invoke {@link #init(SessionInputBuffer, SessionOutputBuffer, HttpParams)}
+ * method to pass references to those buffers to the underlying HTTP message
+ * parser and formatter.
+ *
+ * After this method's execution the connection status will be reported
+ * as open and the {@link #isOpen()} will return true.
+ *
+ * @param socket the socket.
+ * @param params HTTP parameters.
+ * @throws IOException in case of an I/O error.
+ */
+ protected void bind(
+ final Socket socket,
+ final HttpParams params) throws IOException {
+ Args.notNull(socket, "Socket");
+ Args.notNull(params, "HTTP parameters");
+ this.socket = socket;
+
+ final int buffersize = params.getIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, -1);
+ init(
+ createSessionInputBuffer(socket, buffersize, params),
+ createSessionOutputBuffer(socket, buffersize, params),
+ params);
+
+ this.open = true;
+ }
+
+ public boolean isOpen() {
+ return this.open;
+ }
+
+ protected Socket getSocket() {
+ return this.socket;
+ }
+
+ public InetAddress getLocalAddress() {
+ if (this.socket != null) {
+ return this.socket.getLocalAddress();
+ } else {
+ return null;
+ }
+ }
+
+ public int getLocalPort() {
+ if (this.socket != null) {
+ return this.socket.getLocalPort();
+ } else {
+ return -1;
+ }
+ }
+
+ public InetAddress getRemoteAddress() {
+ if (this.socket != null) {
+ return this.socket.getInetAddress();
+ } else {
+ return null;
+ }
+ }
+
+ public int getRemotePort() {
+ if (this.socket != null) {
+ return this.socket.getPort();
+ } else {
+ return -1;
+ }
+ }
+
+ public void setSocketTimeout(final int timeout) {
+ assertOpen();
+ if (this.socket != null) {
+ try {
+ this.socket.setSoTimeout(timeout);
+ } catch (final SocketException ignore) {
+ // It is not quite clear from the Sun's documentation if there are any
+ // other legitimate cases for a socket exception to be thrown when setting
+ // SO_TIMEOUT besides the socket being already closed
+ }
+ }
+ }
+
+ public int getSocketTimeout() {
+ if (this.socket != null) {
+ try {
+ return this.socket.getSoTimeout();
+ } catch (final SocketException ignore) {
+ return -1;
+ }
+ } else {
+ return -1;
+ }
+ }
+
+ public void shutdown() throws IOException {
+ this.open = false;
+ final Socket tmpsocket = this.socket;
+ if (tmpsocket != null) {
+ tmpsocket.close();
+ }
+ }
+
+ public void close() throws IOException {
+ if (!this.open) {
+ return;
+ }
+ this.open = false;
+ final Socket sock = this.socket;
+ try {
+ doFlush();
+ try {
+ try {
+ sock.shutdownOutput();
+ } catch (final IOException ignore) {
+ }
+ try {
+ sock.shutdownInput();
+ } catch (final IOException ignore) {
+ }
+ } catch (final UnsupportedOperationException ignore) {
+ // if one isn't supported, the other one isn't either
+ }
+ } finally {
+ sock.close();
+ }
+ }
+
+ private static void formatAddress(final StringBuilder buffer, final SocketAddress socketAddress) {
+ if (socketAddress instanceof InetSocketAddress) {
+ final InetSocketAddress addr = ((InetSocketAddress) socketAddress);
+ buffer.append(addr.getAddress() != null ? addr.getAddress().getHostAddress() :
+ addr.getAddress())
+ .append(':')
+ .append(addr.getPort());
+ } else {
+ buffer.append(socketAddress);
+ }
+ }
+
+ @Override
+ public String toString() {
+ if (this.socket != null) {
+ final StringBuilder buffer = new StringBuilder();
+ final SocketAddress remoteAddress = this.socket.getRemoteSocketAddress();
+ final SocketAddress localAddress = this.socket.getLocalSocketAddress();
+ if (remoteAddress != null && localAddress != null) {
+ formatAddress(buffer, localAddress);
+ buffer.append("<->");
+ formatAddress(buffer, remoteAddress);
+ }
+ return buffer.toString();
+ } else {
+ return super.toString();
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/SocketHttpServerConnection.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/SocketHttpServerConnection.java
new file mode 100644
index 000000000..0a74b94a3
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/SocketHttpServerConnection.java
@@ -0,0 +1,271 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketException;
+
+import ch.boye.httpclientandroidlib.HttpInetConnection;
+import ch.boye.httpclientandroidlib.impl.io.SocketInputBuffer;
+import ch.boye.httpclientandroidlib.impl.io.SocketOutputBuffer;
+import ch.boye.httpclientandroidlib.io.SessionInputBuffer;
+import ch.boye.httpclientandroidlib.io.SessionOutputBuffer;
+import ch.boye.httpclientandroidlib.params.CoreConnectionPNames;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.Asserts;
+
+@Deprecated
+public class SocketHttpServerConnection extends
+ AbstractHttpServerConnection implements HttpInetConnection {
+
+ private volatile boolean open;
+ private volatile Socket socket = null;
+
+ public SocketHttpServerConnection() {
+ super();
+ }
+
+ protected void assertNotOpen() {
+ Asserts.check(!this.open, "Connection is already open");
+ }
+
+ @Override
+ protected void assertOpen() {
+ Asserts.check(this.open, "Connection is not open");
+ }
+
+ /**
+ * Creates an instance of {@link SocketInputBuffer} to be used for
+ * receiving data from the given {@link Socket}.
+ *
+ * This method can be overridden in a super class in order to provide
+ * a custom implementation of {@link SessionInputBuffer} interface.
+ *
+ * @see SocketInputBuffer#SocketInputBuffer(Socket, int, HttpParams)
+ *
+ * @param socket the socket.
+ * @param buffersize the buffer size.
+ * @param params HTTP parameters.
+ * @return session input buffer.
+ * @throws IOException in case of an I/O error.
+ */
+ protected SessionInputBuffer createSessionInputBuffer(
+ final Socket socket,
+ final int buffersize,
+ final HttpParams params) throws IOException {
+ return new SocketInputBuffer(socket, buffersize, params);
+ }
+
+ /**
+ * Creates an instance of {@link SessionOutputBuffer} to be used for
+ * sending data to the given {@link Socket}.
+ *
+ * This method can be overridden in a super class in order to provide
+ * a custom implementation of {@link SocketOutputBuffer} interface.
+ *
+ * @see SocketOutputBuffer#SocketOutputBuffer(Socket, int, HttpParams)
+ *
+ * @param socket the socket.
+ * @param buffersize the buffer size.
+ * @param params HTTP parameters.
+ * @return session output buffer.
+ * @throws IOException in case of an I/O error.
+ */
+ protected SessionOutputBuffer createSessionOutputBuffer(
+ final Socket socket,
+ final int buffersize,
+ final HttpParams params) throws IOException {
+ return new SocketOutputBuffer(socket, buffersize, params);
+ }
+
+ /**
+ * Binds this connection to the given {@link Socket}. This socket will be
+ * used by the connection to send and receive data.
+ *
+ * This method will invoke {@link #createSessionInputBuffer(Socket, int, HttpParams)}
+ * and {@link #createSessionOutputBuffer(Socket, int, HttpParams)} methods
+ * to create session input / output buffers bound to this socket and then
+ * will invoke {@link #init(SessionInputBuffer, SessionOutputBuffer, HttpParams)}
+ * method to pass references to those buffers to the underlying HTTP message
+ * parser and formatter.
+ *
+ * After this method's execution the connection status will be reported
+ * as open and the {@link #isOpen()} will return true.
+ *
+ * @param socket the socket.
+ * @param params HTTP parameters.
+ * @throws IOException in case of an I/O error.
+ */
+ protected void bind(final Socket socket, final HttpParams params) throws IOException {
+ Args.notNull(socket, "Socket");
+ Args.notNull(params, "HTTP parameters");
+ this.socket = socket;
+
+ final int buffersize = params.getIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, -1);
+ init(
+ createSessionInputBuffer(socket, buffersize, params),
+ createSessionOutputBuffer(socket, buffersize, params),
+ params);
+
+ this.open = true;
+ }
+
+ protected Socket getSocket() {
+ return this.socket;
+ }
+
+ public boolean isOpen() {
+ return this.open;
+ }
+
+ public InetAddress getLocalAddress() {
+ if (this.socket != null) {
+ return this.socket.getLocalAddress();
+ } else {
+ return null;
+ }
+ }
+
+ public int getLocalPort() {
+ if (this.socket != null) {
+ return this.socket.getLocalPort();
+ } else {
+ return -1;
+ }
+ }
+
+ public InetAddress getRemoteAddress() {
+ if (this.socket != null) {
+ return this.socket.getInetAddress();
+ } else {
+ return null;
+ }
+ }
+
+ public int getRemotePort() {
+ if (this.socket != null) {
+ return this.socket.getPort();
+ } else {
+ return -1;
+ }
+ }
+
+ public void setSocketTimeout(final int timeout) {
+ assertOpen();
+ if (this.socket != null) {
+ try {
+ this.socket.setSoTimeout(timeout);
+ } catch (final SocketException ignore) {
+ // It is not quite clear from the Sun's documentation if there are any
+ // other legitimate cases for a socket exception to be thrown when setting
+ // SO_TIMEOUT besides the socket being already closed
+ }
+ }
+ }
+
+ public int getSocketTimeout() {
+ if (this.socket != null) {
+ try {
+ return this.socket.getSoTimeout();
+ } catch (final SocketException ignore) {
+ return -1;
+ }
+ } else {
+ return -1;
+ }
+ }
+
+ public void shutdown() throws IOException {
+ this.open = false;
+ final Socket tmpsocket = this.socket;
+ if (tmpsocket != null) {
+ tmpsocket.close();
+ }
+ }
+
+ public void close() throws IOException {
+ if (!this.open) {
+ return;
+ }
+ this.open = false;
+ this.open = false;
+ final Socket sock = this.socket;
+ try {
+ doFlush();
+ try {
+ try {
+ sock.shutdownOutput();
+ } catch (final IOException ignore) {
+ }
+ try {
+ sock.shutdownInput();
+ } catch (final IOException ignore) {
+ }
+ } catch (final UnsupportedOperationException ignore) {
+ // if one isn't supported, the other one isn't either
+ }
+ } finally {
+ sock.close();
+ }
+ }
+
+ private static void formatAddress(final StringBuilder buffer, final SocketAddress socketAddress) {
+ if (socketAddress instanceof InetSocketAddress) {
+ final InetSocketAddress addr = ((InetSocketAddress) socketAddress);
+ buffer.append(addr.getAddress() != null ? addr.getAddress().getHostAddress() :
+ addr.getAddress())
+ .append(':')
+ .append(addr.getPort());
+ } else {
+ buffer.append(socketAddress);
+ }
+ }
+
+ @Override
+ public String toString() {
+ if (this.socket != null) {
+ final StringBuilder buffer = new StringBuilder();
+ final SocketAddress remoteAddress = this.socket.getRemoteSocketAddress();
+ final SocketAddress localAddress = this.socket.getLocalSocketAddress();
+ if (remoteAddress != null && localAddress != null) {
+ formatAddress(buffer, localAddress);
+ buffer.append("<->");
+ formatAddress(buffer, remoteAddress);
+ }
+ return buffer.toString();
+ } else {
+ return super.toString();
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/AuthSchemeBase.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/AuthSchemeBase.java
new file mode 100644
index 000000000..e1b98db9e
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/AuthSchemeBase.java
@@ -0,0 +1,169 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.auth;
+
+import java.util.Locale;
+
+import ch.boye.httpclientandroidlib.FormattedHeader;
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.auth.AUTH;
+import ch.boye.httpclientandroidlib.auth.AuthenticationException;
+import ch.boye.httpclientandroidlib.auth.ChallengeState;
+import ch.boye.httpclientandroidlib.auth.ContextAwareAuthScheme;
+import ch.boye.httpclientandroidlib.auth.Credentials;
+import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
+
+/**
+ * Abstract authentication scheme class that serves as a basis
+ * for all authentication schemes supported by HttpClient. This class
+ * defines the generic way of parsing an authentication challenge. It
+ * does not make any assumptions regarding the format of the challenge
+ * nor does it impose any specific way of responding to that challenge.
+ *
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public abstract class AuthSchemeBase implements ContextAwareAuthScheme {
+
+ private ChallengeState challengeState;
+
+ /**
+ * Creates an instance of AuthSchemeBase with the given challenge
+ * state.
+ *
+ * @since 4.2
+ *
+ * @deprecated (4.3) do not use.
+ */
+ @Deprecated
+ public AuthSchemeBase(final ChallengeState challengeState) {
+ super();
+ this.challengeState = challengeState;
+ }
+
+ public AuthSchemeBase() {
+ super();
+ }
+
+ /**
+ * Processes the given challenge token. Some authentication schemes
+ * may involve multiple challenge-response exchanges. Such schemes must be able
+ * to maintain the state information when dealing with sequential challenges
+ *
+ * @param header the challenge header
+ *
+ * @throws MalformedChallengeException is thrown if the authentication challenge
+ * is malformed
+ */
+ public void processChallenge(final Header header) throws MalformedChallengeException {
+ Args.notNull(header, "Header");
+ final String authheader = header.getName();
+ if (authheader.equalsIgnoreCase(AUTH.WWW_AUTH)) {
+ this.challengeState = ChallengeState.TARGET;
+ } else if (authheader.equalsIgnoreCase(AUTH.PROXY_AUTH)) {
+ this.challengeState = ChallengeState.PROXY;
+ } else {
+ throw new MalformedChallengeException("Unexpected header name: " + authheader);
+ }
+
+ final CharArrayBuffer buffer;
+ int pos;
+ if (header instanceof FormattedHeader) {
+ buffer = ((FormattedHeader) header).getBuffer();
+ pos = ((FormattedHeader) header).getValuePos();
+ } else {
+ final String s = header.getValue();
+ if (s == null) {
+ throw new MalformedChallengeException("Header value is null");
+ }
+ buffer = new CharArrayBuffer(s.length());
+ buffer.append(s);
+ pos = 0;
+ }
+ while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) {
+ pos++;
+ }
+ final int beginIndex = pos;
+ while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) {
+ pos++;
+ }
+ final int endIndex = pos;
+ final String s = buffer.substring(beginIndex, endIndex);
+ if (!s.equalsIgnoreCase(getSchemeName())) {
+ throw new MalformedChallengeException("Invalid scheme identifier: " + s);
+ }
+
+ parseChallenge(buffer, pos, buffer.length());
+ }
+
+
+ @SuppressWarnings("deprecation")
+ public Header authenticate(
+ final Credentials credentials,
+ final HttpRequest request,
+ final HttpContext context) throws AuthenticationException {
+ return authenticate(credentials, request);
+ }
+
+ protected abstract void parseChallenge(
+ CharArrayBuffer buffer, int beginIndex, int endIndex) throws MalformedChallengeException;
+
+ /**
+ * Returns true if authenticating against a proxy, false
+ * otherwise.
+ */
+ public boolean isProxy() {
+ return this.challengeState != null && this.challengeState == ChallengeState.PROXY;
+ }
+
+ /**
+ * Returns {@link ChallengeState} value or null if unchallenged.
+ *
+ * @since 4.2
+ */
+ public ChallengeState getChallengeState() {
+ return this.challengeState;
+ }
+
+ @Override
+ public String toString() {
+ final String name = getSchemeName();
+ if (name != null) {
+ return name.toUpperCase(Locale.ENGLISH);
+ } else {
+ return super.toString();
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/BasicScheme.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/BasicScheme.java
new file mode 100644
index 000000000..c58b5e582
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/BasicScheme.java
@@ -0,0 +1,219 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.auth;
+
+import java.nio.charset.Charset;
+
+import org.mozilla.apache.commons.codec.binary.Base64;
+import ch.boye.httpclientandroidlib.Consts;
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.auth.AUTH;
+import ch.boye.httpclientandroidlib.auth.AuthenticationException;
+import ch.boye.httpclientandroidlib.auth.ChallengeState;
+import ch.boye.httpclientandroidlib.auth.Credentials;
+import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
+import ch.boye.httpclientandroidlib.message.BufferedHeader;
+import ch.boye.httpclientandroidlib.protocol.BasicHttpContext;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
+import ch.boye.httpclientandroidlib.util.EncodingUtils;
+
+/**
+ * Basic authentication scheme as defined in RFC 2617.
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class BasicScheme extends RFC2617Scheme {
+
+/* Base64 instance removed by HttpClient for Android script. */
+ /** Whether the basic authentication process is complete */
+ private boolean complete;
+
+ /**
+ * @since 4.3
+ */
+ public BasicScheme(final Charset credentialsCharset) {
+ super(credentialsCharset);
+/* Base64 instance removed by HttpClient for Android script. */
+ this.complete = false;
+ }
+
+ /**
+ * Creates an instance of BasicScheme with the given challenge
+ * state.
+ *
+ * @since 4.2
+ *
+ * @deprecated (4.3) do not use.
+ */
+ @Deprecated
+ public BasicScheme(final ChallengeState challengeState) {
+ super(challengeState);
+/* Base64 instance removed by HttpClient for Android script. */
+ }
+
+ public BasicScheme() {
+ this(Consts.ASCII);
+ }
+
+ /**
+ * Returns textual designation of the basic authentication scheme.
+ *
+ * @return basic
+ */
+ public String getSchemeName() {
+ return "basic";
+ }
+
+ /**
+ * Processes the Basic challenge.
+ *
+ * @param header the challenge header
+ *
+ * @throws MalformedChallengeException is thrown if the authentication challenge
+ * is malformed
+ */
+ @Override
+ public void processChallenge(
+ final Header header) throws MalformedChallengeException {
+ super.processChallenge(header);
+ this.complete = true;
+ }
+
+ /**
+ * Tests if the Basic authentication process has been completed.
+ *
+ * @return true if Basic authorization has been processed,
+ * false otherwise.
+ */
+ public boolean isComplete() {
+ return this.complete;
+ }
+
+ /**
+ * Returns false. Basic authentication scheme is request based.
+ *
+ * @return false.
+ */
+ public boolean isConnectionBased() {
+ return false;
+ }
+
+ /**
+ * @deprecated (4.2) Use {@link ch.boye.httpclientandroidlib.auth.ContextAwareAuthScheme#authenticate(
+ * Credentials, HttpRequest, ch.boye.httpclientandroidlib.protocol.HttpContext)}
+ */
+ @Deprecated
+ public Header authenticate(
+ final Credentials credentials, final HttpRequest request) throws AuthenticationException {
+ return authenticate(credentials, request, new BasicHttpContext());
+ }
+
+ /**
+ * Produces basic authorization header for the given set of {@link Credentials}.
+ *
+ * @param credentials The set of credentials to be used for authentication
+ * @param request The request being authenticated
+ * @throws ch.boye.httpclientandroidlib.auth.InvalidCredentialsException if authentication
+ * credentials are not valid or not applicable for this authentication scheme
+ * @throws AuthenticationException if authorization string cannot
+ * be generated due to an authentication failure
+ *
+ * @return a basic authorization string
+ */
+ @Override
+ public Header authenticate(
+ final Credentials credentials,
+ final HttpRequest request,
+ final HttpContext context) throws AuthenticationException {
+
+ Args.notNull(credentials, "Credentials");
+ Args.notNull(request, "HTTP request");
+ final StringBuilder tmp = new StringBuilder();
+ tmp.append(credentials.getUserPrincipal().getName());
+ tmp.append(":");
+ tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());
+
+ final byte[] base64password = Base64.encodeBase64(
+ EncodingUtils.getBytes(tmp.toString(), getCredentialsCharset(request)));
+
+ final CharArrayBuffer buffer = new CharArrayBuffer(32);
+ if (isProxy()) {
+ buffer.append(AUTH.PROXY_AUTH_RESP);
+ } else {
+ buffer.append(AUTH.WWW_AUTH_RESP);
+ }
+ buffer.append(": Basic ");
+ buffer.append(base64password, 0, base64password.length);
+
+ return new BufferedHeader(buffer);
+ }
+
+ /**
+ * Returns a basic Authorization header value for the given
+ * {@link Credentials} and charset.
+ *
+ * @param credentials The credentials to encode.
+ * @param charset The charset to use for encoding the credentials
+ *
+ * @return a basic authorization header
+ *
+ * @deprecated (4.3) use {@link #authenticate(Credentials, HttpRequest, HttpContext)}.
+ */
+ @Deprecated
+ public static Header authenticate(
+ final Credentials credentials,
+ final String charset,
+ final boolean proxy) {
+ Args.notNull(credentials, "Credentials");
+ Args.notNull(charset, "charset");
+
+ final StringBuilder tmp = new StringBuilder();
+ tmp.append(credentials.getUserPrincipal().getName());
+ tmp.append(":");
+ tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());
+
+ final byte[] base64password = Base64.encodeBase64(
+ EncodingUtils.getBytes(tmp.toString(), charset));
+
+ final CharArrayBuffer buffer = new CharArrayBuffer(32);
+ if (proxy) {
+ buffer.append(AUTH.PROXY_AUTH_RESP);
+ } else {
+ buffer.append(AUTH.WWW_AUTH_RESP);
+ }
+ buffer.append(": Basic ");
+ buffer.append(base64password, 0, base64password.length);
+
+ return new BufferedHeader(buffer);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/BasicSchemeFactory.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/BasicSchemeFactory.java
new file mode 100644
index 000000000..c4eb8c6be
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/BasicSchemeFactory.java
@@ -0,0 +1,71 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.auth;
+
+import java.nio.charset.Charset;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.auth.AuthScheme;
+import ch.boye.httpclientandroidlib.auth.AuthSchemeFactory;
+import ch.boye.httpclientandroidlib.auth.AuthSchemeProvider;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+/**
+ * {@link AuthSchemeProvider} implementation that creates and initializes
+ * {@link BasicScheme} instances.
+ *
+ * @since 4.0
+ */
+@Immutable
+@SuppressWarnings("deprecation")
+public class BasicSchemeFactory implements AuthSchemeFactory, AuthSchemeProvider {
+
+ private final Charset charset;
+
+ /**
+ * @since 4.3
+ */
+ public BasicSchemeFactory(final Charset charset) {
+ super();
+ this.charset = charset;
+ }
+
+ public BasicSchemeFactory() {
+ this(null);
+ }
+
+ public AuthScheme newInstance(final HttpParams params) {
+ return new BasicScheme();
+ }
+
+ public AuthScheme create(final HttpContext context) {
+ return new BasicScheme(this.charset);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/DigestScheme.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/DigestScheme.java
new file mode 100644
index 000000000..542f6236b
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/DigestScheme.java
@@ -0,0 +1,489 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.auth;
+
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.security.MessageDigest;
+import java.security.SecureRandom;
+import java.util.ArrayList;
+import java.util.Formatter;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+import java.util.StringTokenizer;
+
+import ch.boye.httpclientandroidlib.Consts;
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.auth.AUTH;
+import ch.boye.httpclientandroidlib.auth.AuthenticationException;
+import ch.boye.httpclientandroidlib.auth.ChallengeState;
+import ch.boye.httpclientandroidlib.auth.Credentials;
+import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
+import ch.boye.httpclientandroidlib.message.BasicHeaderValueFormatter;
+import ch.boye.httpclientandroidlib.message.BasicNameValuePair;
+import ch.boye.httpclientandroidlib.message.BufferedHeader;
+import ch.boye.httpclientandroidlib.protocol.BasicHttpContext;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
+import ch.boye.httpclientandroidlib.util.EncodingUtils;
+
+/**
+ * Digest authentication scheme as defined in RFC 2617.
+ * Both MD5 (default) and MD5-sess are supported.
+ * Currently only qop=auth or no qop is supported. qop=auth-int
+ * is unsupported. If auth and auth-int are provided, auth is
+ * used.
+ *
+ * Since the digest username is included as clear text in the generated
+ * Authentication header, the charset of the username must be compatible
+ * with the HTTP element charset used by the connection.
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class DigestScheme extends RFC2617Scheme {
+
+ /**
+ * Hexa values used when creating 32 character long digest in HTTP DigestScheme
+ * in case of authentication.
+ *
+ * @see #encode(byte[])
+ */
+ private static final char[] HEXADECIMAL = {
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
+ 'e', 'f'
+ };
+
+ /** Whether the digest authentication process is complete */
+ private boolean complete;
+
+ private static final int QOP_UNKNOWN = -1;
+ private static final int QOP_MISSING = 0;
+ private static final int QOP_AUTH_INT = 1;
+ private static final int QOP_AUTH = 2;
+
+ private String lastNonce;
+ private long nounceCount;
+ private String cnonce;
+ private String a1;
+ private String a2;
+
+ /**
+ * @since 4.3
+ */
+ public DigestScheme(final Charset credentialsCharset) {
+ super(credentialsCharset);
+ this.complete = false;
+ }
+
+ /**
+ * Creates an instance of DigestScheme with the given challenge
+ * state.
+ *
+ * @since 4.2
+ *
+ * @deprecated (4.3) do not use.
+ */
+ @Deprecated
+ public DigestScheme(final ChallengeState challengeState) {
+ super(challengeState);
+ }
+
+ public DigestScheme() {
+ this(Consts.ASCII);
+ }
+
+ /**
+ * Processes the Digest challenge.
+ *
+ * @param header the challenge header
+ *
+ * @throws MalformedChallengeException is thrown if the authentication challenge
+ * is malformed
+ */
+ @Override
+ public void processChallenge(
+ final Header header) throws MalformedChallengeException {
+ super.processChallenge(header);
+ this.complete = true;
+ }
+
+ /**
+ * Tests if the Digest authentication process has been completed.
+ *
+ * @return true if Digest authorization has been processed,
+ * false otherwise.
+ */
+ public boolean isComplete() {
+ final String s = getParameter("stale");
+ if ("true".equalsIgnoreCase(s)) {
+ return false;
+ } else {
+ return this.complete;
+ }
+ }
+
+ /**
+ * Returns textual designation of the digest authentication scheme.
+ *
+ * @return digest
+ */
+ public String getSchemeName() {
+ return "digest";
+ }
+
+ /**
+ * Returns false. Digest authentication scheme is request based.
+ *
+ * @return false.
+ */
+ public boolean isConnectionBased() {
+ return false;
+ }
+
+ public void overrideParamter(final String name, final String value) {
+ getParameters().put(name, value);
+ }
+
+ /**
+ * @deprecated (4.2) Use {@link ch.boye.httpclientandroidlib.auth.ContextAwareAuthScheme#authenticate(
+ * Credentials, HttpRequest, ch.boye.httpclientandroidlib.protocol.HttpContext)}
+ */
+ @Deprecated
+ public Header authenticate(
+ final Credentials credentials, final HttpRequest request) throws AuthenticationException {
+ return authenticate(credentials, request, new BasicHttpContext());
+ }
+
+ /**
+ * Produces a digest authorization string for the given set of
+ * {@link Credentials}, method name and URI.
+ *
+ * @param credentials A set of credentials to be used for athentication
+ * @param request The request being authenticated
+ *
+ * @throws ch.boye.httpclientandroidlib.auth.InvalidCredentialsException if authentication credentials
+ * are not valid or not applicable for this authentication scheme
+ * @throws AuthenticationException if authorization string cannot
+ * be generated due to an authentication failure
+ *
+ * @return a digest authorization string
+ */
+ @Override
+ public Header authenticate(
+ final Credentials credentials,
+ final HttpRequest request,
+ final HttpContext context) throws AuthenticationException {
+
+ Args.notNull(credentials, "Credentials");
+ Args.notNull(request, "HTTP request");
+ if (getParameter("realm") == null) {
+ throw new AuthenticationException("missing realm in challenge");
+ }
+ if (getParameter("nonce") == null) {
+ throw new AuthenticationException("missing nonce in challenge");
+ }
+ // Add method name and request-URI to the parameter map
+ getParameters().put("methodname", request.getRequestLine().getMethod());
+ getParameters().put("uri", request.getRequestLine().getUri());
+ final String charset = getParameter("charset");
+ if (charset == null) {
+ getParameters().put("charset", getCredentialsCharset(request));
+ }
+ return createDigestHeader(credentials, request);
+ }
+
+ private static MessageDigest createMessageDigest(
+ final String digAlg) throws UnsupportedDigestAlgorithmException {
+ try {
+ return MessageDigest.getInstance(digAlg);
+ } catch (final Exception e) {
+ throw new UnsupportedDigestAlgorithmException(
+ "Unsupported algorithm in HTTP Digest authentication: "
+ + digAlg);
+ }
+ }
+
+ /**
+ * Creates digest-response header as defined in RFC2617.
+ *
+ * @param credentials User credentials
+ *
+ * @return The digest-response as String.
+ */
+ private Header createDigestHeader(
+ final Credentials credentials,
+ final HttpRequest request) throws AuthenticationException {
+ final String uri = getParameter("uri");
+ final String realm = getParameter("realm");
+ final String nonce = getParameter("nonce");
+ final String opaque = getParameter("opaque");
+ final String method = getParameter("methodname");
+ String algorithm = getParameter("algorithm");
+ // If an algorithm is not specified, default to MD5.
+ if (algorithm == null) {
+ algorithm = "MD5";
+ }
+
+ final Set qopset = new HashSet(8);
+ int qop = QOP_UNKNOWN;
+ final String qoplist = getParameter("qop");
+ if (qoplist != null) {
+ final StringTokenizer tok = new StringTokenizer(qoplist, ",");
+ while (tok.hasMoreTokens()) {
+ final String variant = tok.nextToken().trim();
+ qopset.add(variant.toLowerCase(Locale.ENGLISH));
+ }
+ if (request instanceof HttpEntityEnclosingRequest && qopset.contains("auth-int")) {
+ qop = QOP_AUTH_INT;
+ } else if (qopset.contains("auth")) {
+ qop = QOP_AUTH;
+ }
+ } else {
+ qop = QOP_MISSING;
+ }
+
+ if (qop == QOP_UNKNOWN) {
+ throw new AuthenticationException("None of the qop methods is supported: " + qoplist);
+ }
+
+ String charset = getParameter("charset");
+ if (charset == null) {
+ charset = "ISO-8859-1";
+ }
+
+ String digAlg = algorithm;
+ if (digAlg.equalsIgnoreCase("MD5-sess")) {
+ digAlg = "MD5";
+ }
+
+ final MessageDigest digester;
+ try {
+ digester = createMessageDigest(digAlg);
+ } catch (final UnsupportedDigestAlgorithmException ex) {
+ throw new AuthenticationException("Unsuppported digest algorithm: " + digAlg);
+ }
+
+ final String uname = credentials.getUserPrincipal().getName();
+ final String pwd = credentials.getPassword();
+
+ if (nonce.equals(this.lastNonce)) {
+ nounceCount++;
+ } else {
+ nounceCount = 1;
+ cnonce = null;
+ lastNonce = nonce;
+ }
+ final StringBuilder sb = new StringBuilder(256);
+ final Formatter formatter = new Formatter(sb, Locale.US);
+ formatter.format("%08x", nounceCount);
+ formatter.close();
+ final String nc = sb.toString();
+
+ if (cnonce == null) {
+ cnonce = createCnonce();
+ }
+
+ a1 = null;
+ a2 = null;
+ // 3.2.2.2: Calculating digest
+ if (algorithm.equalsIgnoreCase("MD5-sess")) {
+ // H( unq(username-value) ":" unq(realm-value) ":" passwd )
+ // ":" unq(nonce-value)
+ // ":" unq(cnonce-value)
+
+ // calculated one per session
+ sb.setLength(0);
+ sb.append(uname).append(':').append(realm).append(':').append(pwd);
+ final String checksum = encode(digester.digest(EncodingUtils.getBytes(sb.toString(), charset)));
+ sb.setLength(0);
+ sb.append(checksum).append(':').append(nonce).append(':').append(cnonce);
+ a1 = sb.toString();
+ } else {
+ // unq(username-value) ":" unq(realm-value) ":" passwd
+ sb.setLength(0);
+ sb.append(uname).append(':').append(realm).append(':').append(pwd);
+ a1 = sb.toString();
+ }
+
+ final String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset)));
+
+ if (qop == QOP_AUTH) {
+ // Method ":" digest-uri-value
+ a2 = method + ':' + uri;
+ } else if (qop == QOP_AUTH_INT) {
+ // Method ":" digest-uri-value ":" H(entity-body)
+ HttpEntity entity = null;
+ if (request instanceof HttpEntityEnclosingRequest) {
+ entity = ((HttpEntityEnclosingRequest) request).getEntity();
+ }
+ if (entity != null && !entity.isRepeatable()) {
+ // If the entity is not repeatable, try falling back onto QOP_AUTH
+ if (qopset.contains("auth")) {
+ qop = QOP_AUTH;
+ a2 = method + ':' + uri;
+ } else {
+ throw new AuthenticationException("Qop auth-int cannot be used with " +
+ "a non-repeatable entity");
+ }
+ } else {
+ final HttpEntityDigester entityDigester = new HttpEntityDigester(digester);
+ try {
+ if (entity != null) {
+ entity.writeTo(entityDigester);
+ }
+ entityDigester.close();
+ } catch (final IOException ex) {
+ throw new AuthenticationException("I/O error reading entity content", ex);
+ }
+ a2 = method + ':' + uri + ':' + encode(entityDigester.getDigest());
+ }
+ } else {
+ a2 = method + ':' + uri;
+ }
+
+ final String hasha2 = encode(digester.digest(EncodingUtils.getBytes(a2, charset)));
+
+ // 3.2.2.1
+
+ final String digestValue;
+ if (qop == QOP_MISSING) {
+ sb.setLength(0);
+ sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2);
+ digestValue = sb.toString();
+ } else {
+ sb.setLength(0);
+ sb.append(hasha1).append(':').append(nonce).append(':').append(nc).append(':')
+ .append(cnonce).append(':').append(qop == QOP_AUTH_INT ? "auth-int" : "auth")
+ .append(':').append(hasha2);
+ digestValue = sb.toString();
+ }
+
+ final String digest = encode(digester.digest(EncodingUtils.getAsciiBytes(digestValue)));
+
+ final CharArrayBuffer buffer = new CharArrayBuffer(128);
+ if (isProxy()) {
+ buffer.append(AUTH.PROXY_AUTH_RESP);
+ } else {
+ buffer.append(AUTH.WWW_AUTH_RESP);
+ }
+ buffer.append(": Digest ");
+
+ final List params = new ArrayList(20);
+ params.add(new BasicNameValuePair("username", uname));
+ params.add(new BasicNameValuePair("realm", realm));
+ params.add(new BasicNameValuePair("nonce", nonce));
+ params.add(new BasicNameValuePair("uri", uri));
+ params.add(new BasicNameValuePair("response", digest));
+
+ if (qop != QOP_MISSING) {
+ params.add(new BasicNameValuePair("qop", qop == QOP_AUTH_INT ? "auth-int" : "auth"));
+ params.add(new BasicNameValuePair("nc", nc));
+ params.add(new BasicNameValuePair("cnonce", cnonce));
+ }
+ // algorithm cannot be null here
+ params.add(new BasicNameValuePair("algorithm", algorithm));
+ if (opaque != null) {
+ params.add(new BasicNameValuePair("opaque", opaque));
+ }
+
+ for (int i = 0; i < params.size(); i++) {
+ final BasicNameValuePair param = params.get(i);
+ if (i > 0) {
+ buffer.append(", ");
+ }
+ final String name = param.getName();
+ final boolean noQuotes = ("nc".equals(name) || "qop".equals(name)
+ || "algorithm".equals(name));
+ BasicHeaderValueFormatter.INSTANCE.formatNameValuePair(buffer, param, !noQuotes);
+ }
+ return new BufferedHeader(buffer);
+ }
+
+ String getCnonce() {
+ return cnonce;
+ }
+
+ String getA1() {
+ return a1;
+ }
+
+ String getA2() {
+ return a2;
+ }
+
+ /**
+ * Encodes the 128 bit (16 bytes) MD5 digest into a 32 characters long
+ * String according to RFC 2617.
+ *
+ * @param binaryData array containing the digest
+ * @return encoded MD5, or null if encoding failed
+ */
+ static String encode(final byte[] binaryData) {
+ final int n = binaryData.length;
+ final char[] buffer = new char[n * 2];
+ for (int i = 0; i < n; i++) {
+ final int low = (binaryData[i] & 0x0f);
+ final int high = ((binaryData[i] & 0xf0) >> 4);
+ buffer[i * 2] = HEXADECIMAL[high];
+ buffer[(i * 2) + 1] = HEXADECIMAL[low];
+ }
+
+ return new String(buffer);
+ }
+
+
+ /**
+ * Creates a random cnonce value based on the current time.
+ *
+ * @return The cnonce value as String.
+ */
+ public static String createCnonce() {
+ final SecureRandom rnd = new SecureRandom();
+ final byte[] tmp = new byte[8];
+ rnd.nextBytes(tmp);
+ return encode(tmp);
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("DIGEST [complete=").append(complete)
+ .append(", nonce=").append(lastNonce)
+ .append(", nc=").append(nounceCount)
+ .append("]");
+ return builder.toString();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/DigestSchemeFactory.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/DigestSchemeFactory.java
new file mode 100644
index 000000000..0582bed49
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/DigestSchemeFactory.java
@@ -0,0 +1,71 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.auth;
+
+import java.nio.charset.Charset;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.auth.AuthScheme;
+import ch.boye.httpclientandroidlib.auth.AuthSchemeFactory;
+import ch.boye.httpclientandroidlib.auth.AuthSchemeProvider;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+/**
+ * {@link AuthSchemeProvider} implementation that creates and initializes
+ * {@link DigestScheme} instances.
+ *
+ * @since 4.0
+ */
+@Immutable
+@SuppressWarnings("deprecation")
+public class DigestSchemeFactory implements AuthSchemeFactory, AuthSchemeProvider {
+
+ private final Charset charset;
+
+ /**
+ * @since 4.3
+ */
+ public DigestSchemeFactory(final Charset charset) {
+ super();
+ this.charset = charset;
+ }
+
+ public DigestSchemeFactory() {
+ this(null);
+ }
+
+ public AuthScheme newInstance(final HttpParams params) {
+ return new DigestScheme();
+ }
+
+ public AuthScheme create(final HttpContext context) {
+ return new DigestScheme(this.charset);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/HttpAuthenticator.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/HttpAuthenticator.java
new file mode 100644
index 000000000..28b8b74d0
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/HttpAuthenticator.java
@@ -0,0 +1,245 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.auth;
+
+import java.io.IOException;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Queue;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.auth.AuthOption;
+import ch.boye.httpclientandroidlib.auth.AuthProtocolState;
+import ch.boye.httpclientandroidlib.auth.AuthScheme;
+import ch.boye.httpclientandroidlib.auth.AuthState;
+import ch.boye.httpclientandroidlib.auth.AuthenticationException;
+import ch.boye.httpclientandroidlib.auth.ContextAwareAuthScheme;
+import ch.boye.httpclientandroidlib.auth.Credentials;
+import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
+import ch.boye.httpclientandroidlib.client.AuthenticationStrategy;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Asserts;
+
+/**
+ * @since 4.3
+ */
+public class HttpAuthenticator {
+
+ public HttpClientAndroidLog log;
+
+ public HttpAuthenticator(final HttpClientAndroidLog log) {
+ super();
+ this.log = log != null ? log : new HttpClientAndroidLog(getClass());
+ }
+
+ public HttpAuthenticator() {
+ this(null);
+ }
+
+ public boolean isAuthenticationRequested(
+ final HttpHost host,
+ final HttpResponse response,
+ final AuthenticationStrategy authStrategy,
+ final AuthState authState,
+ final HttpContext context) {
+ if (authStrategy.isAuthenticationRequested(host, response, context)) {
+ this.log.debug("Authentication required");
+ if (authState.getState() == AuthProtocolState.SUCCESS) {
+ authStrategy.authFailed(host, authState.getAuthScheme(), context);
+ }
+ return true;
+ } else {
+ switch (authState.getState()) {
+ case CHALLENGED:
+ case HANDSHAKE:
+ this.log.debug("Authentication succeeded");
+ authState.setState(AuthProtocolState.SUCCESS);
+ authStrategy.authSucceeded(host, authState.getAuthScheme(), context);
+ break;
+ case SUCCESS:
+ break;
+ default:
+ authState.setState(AuthProtocolState.UNCHALLENGED);
+ }
+ return false;
+ }
+ }
+
+ public boolean handleAuthChallenge(
+ final HttpHost host,
+ final HttpResponse response,
+ final AuthenticationStrategy authStrategy,
+ final AuthState authState,
+ final HttpContext context) {
+ try {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug(host.toHostString() + " requested authentication");
+ }
+ final Map challenges = authStrategy.getChallenges(host, response, context);
+ if (challenges.isEmpty()) {
+ this.log.debug("Response contains no authentication challenges");
+ return false;
+ }
+
+ final AuthScheme authScheme = authState.getAuthScheme();
+ switch (authState.getState()) {
+ case FAILURE:
+ return false;
+ case SUCCESS:
+ authState.reset();
+ break;
+ case CHALLENGED:
+ case HANDSHAKE:
+ if (authScheme == null) {
+ this.log.debug("Auth scheme is null");
+ authStrategy.authFailed(host, null, context);
+ authState.reset();
+ authState.setState(AuthProtocolState.FAILURE);
+ return false;
+ }
+ case UNCHALLENGED:
+ if (authScheme != null) {
+ final String id = authScheme.getSchemeName();
+ final Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
+ if (challenge != null) {
+ this.log.debug("Authorization challenge processed");
+ authScheme.processChallenge(challenge);
+ if (authScheme.isComplete()) {
+ this.log.debug("Authentication failed");
+ authStrategy.authFailed(host, authState.getAuthScheme(), context);
+ authState.reset();
+ authState.setState(AuthProtocolState.FAILURE);
+ return false;
+ } else {
+ authState.setState(AuthProtocolState.HANDSHAKE);
+ return true;
+ }
+ } else {
+ authState.reset();
+ // Retry authentication with a different scheme
+ }
+ }
+ }
+ final Queue authOptions = authStrategy.select(challenges, host, response, context);
+ if (authOptions != null && !authOptions.isEmpty()) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Selected authentication options: " + authOptions);
+ }
+ authState.setState(AuthProtocolState.CHALLENGED);
+ authState.update(authOptions);
+ return true;
+ } else {
+ return false;
+ }
+ } catch (final MalformedChallengeException ex) {
+ if (this.log.isWarnEnabled()) {
+ this.log.warn("Malformed challenge: " + ex.getMessage());
+ }
+ authState.reset();
+ return false;
+ }
+ }
+
+ public void generateAuthResponse(
+ final HttpRequest request,
+ final AuthState authState,
+ final HttpContext context) throws HttpException, IOException {
+ AuthScheme authScheme = authState.getAuthScheme();
+ Credentials creds = authState.getCredentials();
+ switch (authState.getState()) {
+ case FAILURE:
+ return;
+ case SUCCESS:
+ ensureAuthScheme(authScheme);
+ if (authScheme.isConnectionBased()) {
+ return;
+ }
+ break;
+ case CHALLENGED:
+ final Queue authOptions = authState.getAuthOptions();
+ if (authOptions != null) {
+ while (!authOptions.isEmpty()) {
+ final AuthOption authOption = authOptions.remove();
+ authScheme = authOption.getAuthScheme();
+ creds = authOption.getCredentials();
+ authState.update(authScheme, creds);
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Generating response to an authentication challenge using "
+ + authScheme.getSchemeName() + " scheme");
+ }
+ try {
+ final Header header = doAuth(authScheme, creds, request, context);
+ request.addHeader(header);
+ break;
+ } catch (final AuthenticationException ex) {
+ if (this.log.isWarnEnabled()) {
+ this.log.warn(authScheme + " authentication error: " + ex.getMessage());
+ }
+ }
+ }
+ return;
+ } else {
+ ensureAuthScheme(authScheme);
+ }
+ }
+ if (authScheme != null) {
+ try {
+ final Header header = doAuth(authScheme, creds, request, context);
+ request.addHeader(header);
+ } catch (final AuthenticationException ex) {
+ if (this.log.isErrorEnabled()) {
+ this.log.error(authScheme + " authentication error: " + ex.getMessage());
+ }
+ }
+ }
+ }
+
+ private void ensureAuthScheme(final AuthScheme authScheme) {
+ Asserts.notNull(authScheme, "Auth scheme");
+ }
+
+ @SuppressWarnings("deprecation")
+ private Header doAuth(
+ final AuthScheme authScheme,
+ final Credentials creds,
+ final HttpRequest request,
+ final HttpContext context) throws AuthenticationException {
+ if (authScheme instanceof ContextAwareAuthScheme) {
+ return ((ContextAwareAuthScheme) authScheme).authenticate(creds, request, context);
+ } else {
+ return authScheme.authenticate(creds, request);
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/HttpEntityDigester.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/HttpEntityDigester.java
new file mode 100644
index 000000000..053951587
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/HttpEntityDigester.java
@@ -0,0 +1,75 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.auth;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.security.MessageDigest;
+
+class HttpEntityDigester extends OutputStream {
+
+ private final MessageDigest digester;
+ private boolean closed;
+ private byte[] digest;
+
+ HttpEntityDigester(final MessageDigest digester) {
+ super();
+ this.digester = digester;
+ this.digester.reset();
+ }
+
+ @Override
+ public void write(final int b) throws IOException {
+ if (this.closed) {
+ throw new IOException("Stream has been already closed");
+ }
+ this.digester.update((byte) b);
+ }
+
+ @Override
+ public void write(final byte[] b, final int off, final int len) throws IOException {
+ if (this.closed) {
+ throw new IOException("Stream has been already closed");
+ }
+ this.digester.update(b, off, len);
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (this.closed) {
+ return;
+ }
+ this.closed = true;
+ this.digest = this.digester.digest();
+ super.close();
+ }
+
+ public byte[] getDigest() {
+ return this.digest;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/NTLMEngine.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/NTLMEngine.java
new file mode 100644
index 000000000..ce2457000
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/NTLMEngine.java
@@ -0,0 +1,70 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.auth;
+
+/**
+ * Abstract NTLM authentication engine. The engine can be used to
+ * generate Type1 messages and Type3 messages in response to a
+ * Type2 challenge.
+ *
+ * @since 4.0
+ */
+public interface NTLMEngine {
+
+ /**
+ * Generates a Type1 message given the domain and workstation.
+ *
+ * @param domain Optional Windows domain name. Can be null.
+ * @param workstation Optional Windows workstation name. Can be
+ * null.
+ * @return Type1 message
+ * @throws NTLMEngineException
+ */
+ String generateType1Msg(
+ String domain,
+ String workstation) throws NTLMEngineException;
+
+ /**
+ * Generates a Type3 message given the user credentials and the
+ * authentication challenge.
+ *
+ * @param username Windows user name
+ * @param password Password
+ * @param domain Windows domain name
+ * @param workstation Windows workstation name
+ * @param challenge Type2 challenge.
+ * @return Type3 response.
+ * @throws NTLMEngineException
+ */
+ String generateType3Msg(
+ String username,
+ String password,
+ String domain,
+ String workstation,
+ String challenge) throws NTLMEngineException;
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/NTLMEngineException.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/NTLMEngineException.java
new file mode 100644
index 000000000..88ef96912
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/NTLMEngineException.java
@@ -0,0 +1,67 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.auth;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.auth.AuthenticationException;
+
+/**
+ * Signals NTLM protocol failure.
+ *
+ *
+ * @since 4.0
+ */
+@Immutable
+public class NTLMEngineException extends AuthenticationException {
+
+ private static final long serialVersionUID = 6027981323731768824L;
+
+ public NTLMEngineException() {
+ super();
+ }
+
+ /**
+ * Creates a new NTLMEngineException with the specified message.
+ *
+ * @param message the exception detail message
+ */
+ public NTLMEngineException(final String message) {
+ super(message);
+ }
+
+ /**
+ * Creates a new NTLMEngineException with the specified detail message and cause.
+ *
+ * @param message the exception detail message
+ * @param cause the Throwable that caused this exception, or null
+ * if the cause is unavailable, unknown, or not a Throwable
+ */
+ public NTLMEngineException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/NTLMEngineImpl.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/NTLMEngineImpl.java
new file mode 100644
index 000000000..195148f6b
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/NTLMEngineImpl.java
@@ -0,0 +1,1672 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.auth;
+
+import java.io.UnsupportedEncodingException;
+import java.security.Key;
+import java.security.MessageDigest;
+import java.util.Arrays;
+import java.util.Locale;
+
+import javax.crypto.Cipher;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.mozilla.apache.commons.codec.binary.Base64;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.util.EncodingUtils;
+
+/**
+ * Provides an implementation for NTLMv1, NTLMv2, and NTLM2 Session forms of the NTLM
+ * authentication protocol.
+ *
+ * @since 4.1
+ */
+@NotThreadSafe
+final class NTLMEngineImpl implements NTLMEngine {
+
+ // Flags we use; descriptions according to:
+ // http://davenport.sourceforge.net/ntlm.html
+ // and
+ // http://msdn.microsoft.com/en-us/library/cc236650%28v=prot.20%29.aspx
+ protected static final int FLAG_REQUEST_UNICODE_ENCODING = 0x00000001; // Unicode string encoding requested
+ protected static final int FLAG_REQUEST_TARGET = 0x00000004; // Requests target field
+ protected static final int FLAG_REQUEST_SIGN = 0x00000010; // Requests all messages have a signature attached, in NEGOTIATE message.
+ protected static final int FLAG_REQUEST_SEAL = 0x00000020; // Request key exchange for message confidentiality in NEGOTIATE message. MUST be used in conjunction with 56BIT.
+ protected static final int FLAG_REQUEST_LAN_MANAGER_KEY = 0x00000080; // Request Lan Manager key instead of user session key
+ protected static final int FLAG_REQUEST_NTLMv1 = 0x00000200; // Request NTLMv1 security. MUST be set in NEGOTIATE and CHALLENGE both
+ protected static final int FLAG_DOMAIN_PRESENT = 0x00001000; // Domain is present in message
+ protected static final int FLAG_WORKSTATION_PRESENT = 0x00002000; // Workstation is present in message
+ protected static final int FLAG_REQUEST_ALWAYS_SIGN = 0x00008000; // Requests a signature block on all messages. Overridden by REQUEST_SIGN and REQUEST_SEAL.
+ protected static final int FLAG_REQUEST_NTLM2_SESSION = 0x00080000; // From server in challenge, requesting NTLM2 session security
+ protected static final int FLAG_REQUEST_VERSION = 0x02000000; // Request protocol version
+ protected static final int FLAG_TARGETINFO_PRESENT = 0x00800000; // From server in challenge message, indicating targetinfo is present
+ protected static final int FLAG_REQUEST_128BIT_KEY_EXCH = 0x20000000; // Request explicit 128-bit key exchange
+ protected static final int FLAG_REQUEST_EXPLICIT_KEY_EXCH = 0x40000000; // Request explicit key exchange
+ protected static final int FLAG_REQUEST_56BIT_ENCRYPTION = 0x80000000; // Must be used in conjunction with SEAL
+
+
+ /** Secure random generator */
+ private static final java.security.SecureRandom RND_GEN;
+ static {
+ java.security.SecureRandom rnd = null;
+ try {
+ rnd = java.security.SecureRandom.getInstance("SHA1PRNG");
+ } catch (final Exception ignore) {
+ }
+ RND_GEN = rnd;
+ }
+
+ /** Character encoding */
+ static final String DEFAULT_CHARSET = "ASCII";
+
+ /** The character set to use for encoding the credentials */
+ private String credentialCharset = DEFAULT_CHARSET;
+
+ /** The signature string as bytes in the default encoding */
+ private static final byte[] SIGNATURE;
+
+ static {
+ final byte[] bytesWithoutNull = EncodingUtils.getBytes("NTLMSSP", "ASCII");
+ SIGNATURE = new byte[bytesWithoutNull.length + 1];
+ System.arraycopy(bytesWithoutNull, 0, SIGNATURE, 0, bytesWithoutNull.length);
+ SIGNATURE[bytesWithoutNull.length] = (byte) 0x00;
+ }
+
+ /**
+ * Returns the response for the given message.
+ *
+ * @param message
+ * the message that was received from the server.
+ * @param username
+ * the username to authenticate with.
+ * @param password
+ * the password to authenticate with.
+ * @param host
+ * The host.
+ * @param domain
+ * the NT domain to authenticate in.
+ * @return The response.
+ * @throws ch.boye.httpclientandroidlib.HttpException
+ * If the messages cannot be retrieved.
+ */
+ final String getResponseFor(final String message, final String username, final String password,
+ final String host, final String domain) throws NTLMEngineException {
+
+ final String response;
+ if (message == null || message.trim().equals("")) {
+ response = getType1Message(host, domain);
+ } else {
+ final Type2Message t2m = new Type2Message(message);
+ response = getType3Message(username, password, host, domain, t2m.getChallenge(), t2m
+ .getFlags(), t2m.getTarget(), t2m.getTargetInfo());
+ }
+ return response;
+ }
+
+ /**
+ * Creates the first message (type 1 message) in the NTLM authentication
+ * sequence. This message includes the user name, domain and host for the
+ * authentication session.
+ *
+ * @param host
+ * the computer name of the host requesting authentication.
+ * @param domain
+ * The domain to authenticate with.
+ * @return String the message to add to the HTTP request header.
+ */
+ String getType1Message(final String host, final String domain) throws NTLMEngineException {
+ return new Type1Message(domain, host).getResponse();
+ }
+
+ /**
+ * Creates the type 3 message using the given server nonce. The type 3
+ * message includes all the information for authentication, host, domain,
+ * username and the result of encrypting the nonce sent by the server using
+ * the user's password as the key.
+ *
+ * @param user
+ * The user name. This should not include the domain name.
+ * @param password
+ * The password.
+ * @param host
+ * The host that is originating the authentication request.
+ * @param domain
+ * The domain to authenticate within.
+ * @param nonce
+ * the 8 byte array the server sent.
+ * @return The type 3 message.
+ * @throws NTLMEngineException
+ * If {@link #RC4(byte[],byte[])} fails.
+ */
+ String getType3Message(final String user, final String password, final String host, final String domain,
+ final byte[] nonce, final int type2Flags, final String target, final byte[] targetInformation)
+ throws NTLMEngineException {
+ return new Type3Message(domain, host, user, password, nonce, type2Flags, target,
+ targetInformation).getResponse();
+ }
+
+ /**
+ * @return Returns the credentialCharset.
+ */
+ String getCredentialCharset() {
+ return credentialCharset;
+ }
+
+ /**
+ * @param credentialCharset
+ * The credentialCharset to set.
+ */
+ void setCredentialCharset(final String credentialCharset) {
+ this.credentialCharset = credentialCharset;
+ }
+
+ /** Strip dot suffix from a name */
+ private static String stripDotSuffix(final String value) {
+ if (value == null) {
+ return null;
+ }
+ final int index = value.indexOf(".");
+ if (index != -1) {
+ return value.substring(0, index);
+ }
+ return value;
+ }
+
+ /** Convert host to standard form */
+ private static String convertHost(final String host) {
+ return stripDotSuffix(host);
+ }
+
+ /** Convert domain to standard form */
+ private static String convertDomain(final String domain) {
+ return stripDotSuffix(domain);
+ }
+
+ private static int readULong(final byte[] src, final int index) throws NTLMEngineException {
+ if (src.length < index + 4) {
+ throw new NTLMEngineException("NTLM authentication - buffer too small for DWORD");
+ }
+ return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8)
+ | ((src[index + 2] & 0xff) << 16) | ((src[index + 3] & 0xff) << 24);
+ }
+
+ private static int readUShort(final byte[] src, final int index) throws NTLMEngineException {
+ if (src.length < index + 2) {
+ throw new NTLMEngineException("NTLM authentication - buffer too small for WORD");
+ }
+ return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8);
+ }
+
+ private static byte[] readSecurityBuffer(final byte[] src, final int index) throws NTLMEngineException {
+ final int length = readUShort(src, index);
+ final int offset = readULong(src, index + 4);
+ if (src.length < offset + length) {
+ throw new NTLMEngineException(
+ "NTLM authentication - buffer too small for data item");
+ }
+ final byte[] buffer = new byte[length];
+ System.arraycopy(src, offset, buffer, 0, length);
+ return buffer;
+ }
+
+ /** Calculate a challenge block */
+ private static byte[] makeRandomChallenge() throws NTLMEngineException {
+ if (RND_GEN == null) {
+ throw new NTLMEngineException("Random generator not available");
+ }
+ final byte[] rval = new byte[8];
+ synchronized (RND_GEN) {
+ RND_GEN.nextBytes(rval);
+ }
+ return rval;
+ }
+
+ /** Calculate a 16-byte secondary key */
+ private static byte[] makeSecondaryKey() throws NTLMEngineException {
+ if (RND_GEN == null) {
+ throw new NTLMEngineException("Random generator not available");
+ }
+ final byte[] rval = new byte[16];
+ synchronized (RND_GEN) {
+ RND_GEN.nextBytes(rval);
+ }
+ return rval;
+ }
+
+ protected static class CipherGen {
+
+ protected final String domain;
+ protected final String user;
+ protected final String password;
+ protected final byte[] challenge;
+ protected final String target;
+ protected final byte[] targetInformation;
+
+ // Information we can generate but may be passed in (for testing)
+ protected byte[] clientChallenge;
+ protected byte[] clientChallenge2;
+ protected byte[] secondaryKey;
+ protected byte[] timestamp;
+
+ // Stuff we always generate
+ protected byte[] lmHash = null;
+ protected byte[] lmResponse = null;
+ protected byte[] ntlmHash = null;
+ protected byte[] ntlmResponse = null;
+ protected byte[] ntlmv2Hash = null;
+ protected byte[] lmv2Hash = null;
+ protected byte[] lmv2Response = null;
+ protected byte[] ntlmv2Blob = null;
+ protected byte[] ntlmv2Response = null;
+ protected byte[] ntlm2SessionResponse = null;
+ protected byte[] lm2SessionResponse = null;
+ protected byte[] lmUserSessionKey = null;
+ protected byte[] ntlmUserSessionKey = null;
+ protected byte[] ntlmv2UserSessionKey = null;
+ protected byte[] ntlm2SessionResponseUserSessionKey = null;
+ protected byte[] lanManagerSessionKey = null;
+
+ public CipherGen(final String domain, final String user, final String password,
+ final byte[] challenge, final String target, final byte[] targetInformation,
+ final byte[] clientChallenge, final byte[] clientChallenge2,
+ final byte[] secondaryKey, final byte[] timestamp) {
+ this.domain = domain;
+ this.target = target;
+ this.user = user;
+ this.password = password;
+ this.challenge = challenge;
+ this.targetInformation = targetInformation;
+ this.clientChallenge = clientChallenge;
+ this.clientChallenge2 = clientChallenge2;
+ this.secondaryKey = secondaryKey;
+ this.timestamp = timestamp;
+ }
+
+ public CipherGen(final String domain, final String user, final String password,
+ final byte[] challenge, final String target, final byte[] targetInformation) {
+ this(domain, user, password, challenge, target, targetInformation, null, null, null, null);
+ }
+
+ /** Calculate and return client challenge */
+ public byte[] getClientChallenge()
+ throws NTLMEngineException {
+ if (clientChallenge == null) {
+ clientChallenge = makeRandomChallenge();
+ }
+ return clientChallenge;
+ }
+
+ /** Calculate and return second client challenge */
+ public byte[] getClientChallenge2()
+ throws NTLMEngineException {
+ if (clientChallenge2 == null) {
+ clientChallenge2 = makeRandomChallenge();
+ }
+ return clientChallenge2;
+ }
+
+ /** Calculate and return random secondary key */
+ public byte[] getSecondaryKey()
+ throws NTLMEngineException {
+ if (secondaryKey == null) {
+ secondaryKey = makeSecondaryKey();
+ }
+ return secondaryKey;
+ }
+
+ /** Calculate and return the LMHash */
+ public byte[] getLMHash()
+ throws NTLMEngineException {
+ if (lmHash == null) {
+ lmHash = lmHash(password);
+ }
+ return lmHash;
+ }
+
+ /** Calculate and return the LMResponse */
+ public byte[] getLMResponse()
+ throws NTLMEngineException {
+ if (lmResponse == null) {
+ lmResponse = lmResponse(getLMHash(),challenge);
+ }
+ return lmResponse;
+ }
+
+ /** Calculate and return the NTLMHash */
+ public byte[] getNTLMHash()
+ throws NTLMEngineException {
+ if (ntlmHash == null) {
+ ntlmHash = ntlmHash(password);
+ }
+ return ntlmHash;
+ }
+
+ /** Calculate and return the NTLMResponse */
+ public byte[] getNTLMResponse()
+ throws NTLMEngineException {
+ if (ntlmResponse == null) {
+ ntlmResponse = lmResponse(getNTLMHash(),challenge);
+ }
+ return ntlmResponse;
+ }
+
+ /** Calculate the LMv2 hash */
+ public byte[] getLMv2Hash()
+ throws NTLMEngineException {
+ if (lmv2Hash == null) {
+ lmv2Hash = lmv2Hash(domain, user, getNTLMHash());
+ }
+ return lmv2Hash;
+ }
+
+ /** Calculate the NTLMv2 hash */
+ public byte[] getNTLMv2Hash()
+ throws NTLMEngineException {
+ if (ntlmv2Hash == null) {
+ ntlmv2Hash = ntlmv2Hash(domain, user, getNTLMHash());
+ }
+ return ntlmv2Hash;
+ }
+
+ /** Calculate a timestamp */
+ public byte[] getTimestamp() {
+ if (timestamp == null) {
+ long time = System.currentTimeMillis();
+ time += 11644473600000l; // milliseconds from January 1, 1601 -> epoch.
+ time *= 10000; // tenths of a microsecond.
+ // convert to little-endian byte array.
+ timestamp = new byte[8];
+ for (int i = 0; i < 8; i++) {
+ timestamp[i] = (byte) time;
+ time >>>= 8;
+ }
+ }
+ return timestamp;
+ }
+
+ /** Calculate the NTLMv2Blob */
+ public byte[] getNTLMv2Blob()
+ throws NTLMEngineException {
+ if (ntlmv2Blob == null) {
+ ntlmv2Blob = createBlob(getClientChallenge2(), targetInformation, getTimestamp());
+ }
+ return ntlmv2Blob;
+ }
+
+ /** Calculate the NTLMv2Response */
+ public byte[] getNTLMv2Response()
+ throws NTLMEngineException {
+ if (ntlmv2Response == null) {
+ ntlmv2Response = lmv2Response(getNTLMv2Hash(),challenge,getNTLMv2Blob());
+ }
+ return ntlmv2Response;
+ }
+
+ /** Calculate the LMv2Response */
+ public byte[] getLMv2Response()
+ throws NTLMEngineException {
+ if (lmv2Response == null) {
+ lmv2Response = lmv2Response(getLMv2Hash(),challenge,getClientChallenge());
+ }
+ return lmv2Response;
+ }
+
+ /** Get NTLM2SessionResponse */
+ public byte[] getNTLM2SessionResponse()
+ throws NTLMEngineException {
+ if (ntlm2SessionResponse == null) {
+ ntlm2SessionResponse = ntlm2SessionResponse(getNTLMHash(),challenge,getClientChallenge());
+ }
+ return ntlm2SessionResponse;
+ }
+
+ /** Calculate and return LM2 session response */
+ public byte[] getLM2SessionResponse()
+ throws NTLMEngineException {
+ if (lm2SessionResponse == null) {
+ final byte[] clChallenge = getClientChallenge();
+ lm2SessionResponse = new byte[24];
+ System.arraycopy(clChallenge, 0, lm2SessionResponse, 0, clChallenge.length);
+ Arrays.fill(lm2SessionResponse, clChallenge.length, lm2SessionResponse.length, (byte) 0x00);
+ }
+ return lm2SessionResponse;
+ }
+
+ /** Get LMUserSessionKey */
+ public byte[] getLMUserSessionKey()
+ throws NTLMEngineException {
+ if (lmUserSessionKey == null) {
+ lmUserSessionKey = new byte[16];
+ System.arraycopy(getLMHash(), 0, lmUserSessionKey, 0, 8);
+ Arrays.fill(lmUserSessionKey, 8, 16, (byte) 0x00);
+ }
+ return lmUserSessionKey;
+ }
+
+ /** Get NTLMUserSessionKey */
+ public byte[] getNTLMUserSessionKey()
+ throws NTLMEngineException {
+ if (ntlmUserSessionKey == null) {
+ final MD4 md4 = new MD4();
+ md4.update(getNTLMHash());
+ ntlmUserSessionKey = md4.getOutput();
+ }
+ return ntlmUserSessionKey;
+ }
+
+ /** GetNTLMv2UserSessionKey */
+ public byte[] getNTLMv2UserSessionKey()
+ throws NTLMEngineException {
+ if (ntlmv2UserSessionKey == null) {
+ final byte[] ntlmv2hash = getNTLMv2Hash();
+ final byte[] truncatedResponse = new byte[16];
+ System.arraycopy(getNTLMv2Response(), 0, truncatedResponse, 0, 16);
+ ntlmv2UserSessionKey = hmacMD5(truncatedResponse, ntlmv2hash);
+ }
+ return ntlmv2UserSessionKey;
+ }
+
+ /** Get NTLM2SessionResponseUserSessionKey */
+ public byte[] getNTLM2SessionResponseUserSessionKey()
+ throws NTLMEngineException {
+ if (ntlm2SessionResponseUserSessionKey == null) {
+ final byte[] ntlm2SessionResponseNonce = getLM2SessionResponse();
+ final byte[] sessionNonce = new byte[challenge.length + ntlm2SessionResponseNonce.length];
+ System.arraycopy(challenge, 0, sessionNonce, 0, challenge.length);
+ System.arraycopy(ntlm2SessionResponseNonce, 0, sessionNonce, challenge.length, ntlm2SessionResponseNonce.length);
+ ntlm2SessionResponseUserSessionKey = hmacMD5(sessionNonce,getNTLMUserSessionKey());
+ }
+ return ntlm2SessionResponseUserSessionKey;
+ }
+
+ /** Get LAN Manager session key */
+ public byte[] getLanManagerSessionKey()
+ throws NTLMEngineException {
+ if (lanManagerSessionKey == null) {
+ try {
+ final byte[] keyBytes = new byte[14];
+ System.arraycopy(getLMHash(), 0, keyBytes, 0, 8);
+ Arrays.fill(keyBytes, 8, keyBytes.length, (byte)0xbd);
+ final Key lowKey = createDESKey(keyBytes, 0);
+ final Key highKey = createDESKey(keyBytes, 7);
+ final byte[] truncatedResponse = new byte[8];
+ System.arraycopy(getLMResponse(), 0, truncatedResponse, 0, truncatedResponse.length);
+ Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
+ des.init(Cipher.ENCRYPT_MODE, lowKey);
+ final byte[] lowPart = des.doFinal(truncatedResponse);
+ des = Cipher.getInstance("DES/ECB/NoPadding");
+ des.init(Cipher.ENCRYPT_MODE, highKey);
+ final byte[] highPart = des.doFinal(truncatedResponse);
+ lanManagerSessionKey = new byte[16];
+ System.arraycopy(lowPart, 0, lanManagerSessionKey, 0, lowPart.length);
+ System.arraycopy(highPart, 0, lanManagerSessionKey, lowPart.length, highPart.length);
+ } catch (final Exception e) {
+ throw new NTLMEngineException(e.getMessage(), e);
+ }
+ }
+ return lanManagerSessionKey;
+ }
+ }
+
+ /** Calculates HMAC-MD5 */
+ static byte[] hmacMD5(final byte[] value, final byte[] key)
+ throws NTLMEngineException {
+ final HMACMD5 hmacMD5 = new HMACMD5(key);
+ hmacMD5.update(value);
+ return hmacMD5.getOutput();
+ }
+
+ /** Calculates RC4 */
+ static byte[] RC4(final byte[] value, final byte[] key)
+ throws NTLMEngineException {
+ try {
+ final Cipher rc4 = Cipher.getInstance("RC4");
+ rc4.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "RC4"));
+ return rc4.doFinal(value);
+ } catch (final Exception e) {
+ throw new NTLMEngineException(e.getMessage(), e);
+ }
+ }
+
+ /**
+ * Calculates the NTLM2 Session Response for the given challenge, using the
+ * specified password and client challenge.
+ *
+ * @return The NTLM2 Session Response. This is placed in the NTLM response
+ * field of the Type 3 message; the LM response field contains the
+ * client challenge, null-padded to 24 bytes.
+ */
+ static byte[] ntlm2SessionResponse(final byte[] ntlmHash, final byte[] challenge,
+ final byte[] clientChallenge) throws NTLMEngineException {
+ try {
+ // Look up MD5 algorithm (was necessary on jdk 1.4.2)
+ // This used to be needed, but java 1.5.0_07 includes the MD5
+ // algorithm (finally)
+ // Class x = Class.forName("gnu.crypto.hash.MD5");
+ // Method updateMethod = x.getMethod("update",new
+ // Class[]{byte[].class});
+ // Method digestMethod = x.getMethod("digest",new Class[0]);
+ // Object mdInstance = x.newInstance();
+ // updateMethod.invoke(mdInstance,new Object[]{challenge});
+ // updateMethod.invoke(mdInstance,new Object[]{clientChallenge});
+ // byte[] digest = (byte[])digestMethod.invoke(mdInstance,new
+ // Object[0]);
+
+ final MessageDigest md5 = MessageDigest.getInstance("MD5");
+ md5.update(challenge);
+ md5.update(clientChallenge);
+ final byte[] digest = md5.digest();
+
+ final byte[] sessionHash = new byte[8];
+ System.arraycopy(digest, 0, sessionHash, 0, 8);
+ return lmResponse(ntlmHash, sessionHash);
+ } catch (final Exception e) {
+ if (e instanceof NTLMEngineException) {
+ throw (NTLMEngineException) e;
+ }
+ throw new NTLMEngineException(e.getMessage(), e);
+ }
+ }
+
+ /**
+ * Creates the LM Hash of the user's password.
+ *
+ * @param password
+ * The password.
+ *
+ * @return The LM Hash of the given password, used in the calculation of the
+ * LM Response.
+ */
+ private static byte[] lmHash(final String password) throws NTLMEngineException {
+ try {
+ final byte[] oemPassword = password.toUpperCase(Locale.ENGLISH).getBytes("US-ASCII");
+ final int length = Math.min(oemPassword.length, 14);
+ final byte[] keyBytes = new byte[14];
+ System.arraycopy(oemPassword, 0, keyBytes, 0, length);
+ final Key lowKey = createDESKey(keyBytes, 0);
+ final Key highKey = createDESKey(keyBytes, 7);
+ final byte[] magicConstant = "KGS!@#$%".getBytes("US-ASCII");
+ final Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
+ des.init(Cipher.ENCRYPT_MODE, lowKey);
+ final byte[] lowHash = des.doFinal(magicConstant);
+ des.init(Cipher.ENCRYPT_MODE, highKey);
+ final byte[] highHash = des.doFinal(magicConstant);
+ final byte[] lmHash = new byte[16];
+ System.arraycopy(lowHash, 0, lmHash, 0, 8);
+ System.arraycopy(highHash, 0, lmHash, 8, 8);
+ return lmHash;
+ } catch (final Exception e) {
+ throw new NTLMEngineException(e.getMessage(), e);
+ }
+ }
+
+ /**
+ * Creates the NTLM Hash of the user's password.
+ *
+ * @param password
+ * The password.
+ *
+ * @return The NTLM Hash of the given password, used in the calculation of
+ * the NTLM Response and the NTLMv2 and LMv2 Hashes.
+ */
+ private static byte[] ntlmHash(final String password) throws NTLMEngineException {
+ try {
+ final byte[] unicodePassword = password.getBytes("UnicodeLittleUnmarked");
+ final MD4 md4 = new MD4();
+ md4.update(unicodePassword);
+ return md4.getOutput();
+ } catch (final UnsupportedEncodingException e) {
+ throw new NTLMEngineException("Unicode not supported: " + e.getMessage(), e);
+ }
+ }
+
+ /**
+ * Creates the LMv2 Hash of the user's password.
+ *
+ * @return The LMv2 Hash, used in the calculation of the NTLMv2 and LMv2
+ * Responses.
+ */
+ private static byte[] lmv2Hash(final String domain, final String user, final byte[] ntlmHash)
+ throws NTLMEngineException {
+ try {
+ final HMACMD5 hmacMD5 = new HMACMD5(ntlmHash);
+ // Upper case username, upper case domain!
+ hmacMD5.update(user.toUpperCase(Locale.ENGLISH).getBytes("UnicodeLittleUnmarked"));
+ if (domain != null) {
+ hmacMD5.update(domain.toUpperCase(Locale.ENGLISH).getBytes("UnicodeLittleUnmarked"));
+ }
+ return hmacMD5.getOutput();
+ } catch (final UnsupportedEncodingException e) {
+ throw new NTLMEngineException("Unicode not supported! " + e.getMessage(), e);
+ }
+ }
+
+ /**
+ * Creates the NTLMv2 Hash of the user's password.
+ *
+ * @return The NTLMv2 Hash, used in the calculation of the NTLMv2 and LMv2
+ * Responses.
+ */
+ private static byte[] ntlmv2Hash(final String domain, final String user, final byte[] ntlmHash)
+ throws NTLMEngineException {
+ try {
+ final HMACMD5 hmacMD5 = new HMACMD5(ntlmHash);
+ // Upper case username, mixed case target!!
+ hmacMD5.update(user.toUpperCase(Locale.ENGLISH).getBytes("UnicodeLittleUnmarked"));
+ if (domain != null) {
+ hmacMD5.update(domain.getBytes("UnicodeLittleUnmarked"));
+ }
+ return hmacMD5.getOutput();
+ } catch (final UnsupportedEncodingException e) {
+ throw new NTLMEngineException("Unicode not supported! " + e.getMessage(), e);
+ }
+ }
+
+ /**
+ * Creates the LM Response from the given hash and Type 2 challenge.
+ *
+ * @param hash
+ * The LM or NTLM Hash.
+ * @param challenge
+ * The server challenge from the Type 2 message.
+ *
+ * @return The response (either LM or NTLM, depending on the provided hash).
+ */
+ private static byte[] lmResponse(final byte[] hash, final byte[] challenge) throws NTLMEngineException {
+ try {
+ final byte[] keyBytes = new byte[21];
+ System.arraycopy(hash, 0, keyBytes, 0, 16);
+ final Key lowKey = createDESKey(keyBytes, 0);
+ final Key middleKey = createDESKey(keyBytes, 7);
+ final Key highKey = createDESKey(keyBytes, 14);
+ final Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
+ des.init(Cipher.ENCRYPT_MODE, lowKey);
+ final byte[] lowResponse = des.doFinal(challenge);
+ des.init(Cipher.ENCRYPT_MODE, middleKey);
+ final byte[] middleResponse = des.doFinal(challenge);
+ des.init(Cipher.ENCRYPT_MODE, highKey);
+ final byte[] highResponse = des.doFinal(challenge);
+ final byte[] lmResponse = new byte[24];
+ System.arraycopy(lowResponse, 0, lmResponse, 0, 8);
+ System.arraycopy(middleResponse, 0, lmResponse, 8, 8);
+ System.arraycopy(highResponse, 0, lmResponse, 16, 8);
+ return lmResponse;
+ } catch (final Exception e) {
+ throw new NTLMEngineException(e.getMessage(), e);
+ }
+ }
+
+ /**
+ * Creates the LMv2 Response from the given hash, client data, and Type 2
+ * challenge.
+ *
+ * @param hash
+ * The NTLMv2 Hash.
+ * @param clientData
+ * The client data (blob or client challenge).
+ * @param challenge
+ * The server challenge from the Type 2 message.
+ *
+ * @return The response (either NTLMv2 or LMv2, depending on the client
+ * data).
+ */
+ private static byte[] lmv2Response(final byte[] hash, final byte[] challenge, final byte[] clientData)
+ throws NTLMEngineException {
+ final HMACMD5 hmacMD5 = new HMACMD5(hash);
+ hmacMD5.update(challenge);
+ hmacMD5.update(clientData);
+ final byte[] mac = hmacMD5.getOutput();
+ final byte[] lmv2Response = new byte[mac.length + clientData.length];
+ System.arraycopy(mac, 0, lmv2Response, 0, mac.length);
+ System.arraycopy(clientData, 0, lmv2Response, mac.length, clientData.length);
+ return lmv2Response;
+ }
+
+ /**
+ * Creates the NTLMv2 blob from the given target information block and
+ * client challenge.
+ *
+ * @param targetInformation
+ * The target information block from the Type 2 message.
+ * @param clientChallenge
+ * The random 8-byte client challenge.
+ *
+ * @return The blob, used in the calculation of the NTLMv2 Response.
+ */
+ private static byte[] createBlob(final byte[] clientChallenge, final byte[] targetInformation, final byte[] timestamp) {
+ final byte[] blobSignature = new byte[] { (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00 };
+ final byte[] reserved = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
+ final byte[] unknown1 = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
+ final byte[] unknown2 = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
+ final byte[] blob = new byte[blobSignature.length + reserved.length + timestamp.length + 8
+ + unknown1.length + targetInformation.length + unknown2.length];
+ int offset = 0;
+ System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length);
+ offset += blobSignature.length;
+ System.arraycopy(reserved, 0, blob, offset, reserved.length);
+ offset += reserved.length;
+ System.arraycopy(timestamp, 0, blob, offset, timestamp.length);
+ offset += timestamp.length;
+ System.arraycopy(clientChallenge, 0, blob, offset, 8);
+ offset += 8;
+ System.arraycopy(unknown1, 0, blob, offset, unknown1.length);
+ offset += unknown1.length;
+ System.arraycopy(targetInformation, 0, blob, offset, targetInformation.length);
+ offset += targetInformation.length;
+ System.arraycopy(unknown2, 0, blob, offset, unknown2.length);
+ offset += unknown2.length;
+ return blob;
+ }
+
+ /**
+ * Creates a DES encryption key from the given key material.
+ *
+ * @param bytes
+ * A byte array containing the DES key material.
+ * @param offset
+ * The offset in the given byte array at which the 7-byte key
+ * material starts.
+ *
+ * @return A DES encryption key created from the key material starting at
+ * the specified offset in the given byte array.
+ */
+ private static Key createDESKey(final byte[] bytes, final int offset) {
+ final byte[] keyBytes = new byte[7];
+ System.arraycopy(bytes, offset, keyBytes, 0, 7);
+ final byte[] material = new byte[8];
+ material[0] = keyBytes[0];
+ material[1] = (byte) (keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1);
+ material[2] = (byte) (keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2);
+ material[3] = (byte) (keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3);
+ material[4] = (byte) (keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4);
+ material[5] = (byte) (keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5);
+ material[6] = (byte) (keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6);
+ material[7] = (byte) (keyBytes[6] << 1);
+ oddParity(material);
+ return new SecretKeySpec(material, "DES");
+ }
+
+ /**
+ * Applies odd parity to the given byte array.
+ *
+ * @param bytes
+ * The data whose parity bits are to be adjusted for odd parity.
+ */
+ private static void oddParity(final byte[] bytes) {
+ for (int i = 0; i < bytes.length; i++) {
+ final byte b = bytes[i];
+ final boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^ (b >>> 4) ^ (b >>> 3)
+ ^ (b >>> 2) ^ (b >>> 1)) & 0x01) == 0;
+ if (needsParity) {
+ bytes[i] |= (byte) 0x01;
+ } else {
+ bytes[i] &= (byte) 0xfe;
+ }
+ }
+ }
+
+ /** NTLM message generation, base class */
+ static class NTLMMessage {
+ /** The current response */
+ private byte[] messageContents = null;
+
+ /** The current output position */
+ private int currentOutputPosition = 0;
+
+ /** Constructor to use when message contents are not yet known */
+ NTLMMessage() {
+ }
+
+ /** Constructor to use when message contents are known */
+ NTLMMessage(final String messageBody, final int expectedType) throws NTLMEngineException {
+ messageContents = Base64.decodeBase64(EncodingUtils.getBytes(messageBody,
+ DEFAULT_CHARSET));
+ // Look for NTLM message
+ if (messageContents.length < SIGNATURE.length) {
+ throw new NTLMEngineException("NTLM message decoding error - packet too short");
+ }
+ int i = 0;
+ while (i < SIGNATURE.length) {
+ if (messageContents[i] != SIGNATURE[i]) {
+ throw new NTLMEngineException(
+ "NTLM message expected - instead got unrecognized bytes");
+ }
+ i++;
+ }
+
+ // Check to be sure there's a type 2 message indicator next
+ final int type = readULong(SIGNATURE.length);
+ if (type != expectedType) {
+ throw new NTLMEngineException("NTLM type " + Integer.toString(expectedType)
+ + " message expected - instead got type " + Integer.toString(type));
+ }
+
+ currentOutputPosition = messageContents.length;
+ }
+
+ /**
+ * Get the length of the signature and flags, so calculations can adjust
+ * offsets accordingly.
+ */
+ protected int getPreambleLength() {
+ return SIGNATURE.length + 4;
+ }
+
+ /** Get the message length */
+ protected int getMessageLength() {
+ return currentOutputPosition;
+ }
+
+ /** Read a byte from a position within the message buffer */
+ protected byte readByte(final int position) throws NTLMEngineException {
+ if (messageContents.length < position + 1) {
+ throw new NTLMEngineException("NTLM: Message too short");
+ }
+ return messageContents[position];
+ }
+
+ /** Read a bunch of bytes from a position in the message buffer */
+ protected void readBytes(final byte[] buffer, final int position) throws NTLMEngineException {
+ if (messageContents.length < position + buffer.length) {
+ throw new NTLMEngineException("NTLM: Message too short");
+ }
+ System.arraycopy(messageContents, position, buffer, 0, buffer.length);
+ }
+
+ /** Read a ushort from a position within the message buffer */
+ protected int readUShort(final int position) throws NTLMEngineException {
+ return NTLMEngineImpl.readUShort(messageContents, position);
+ }
+
+ /** Read a ulong from a position within the message buffer */
+ protected int readULong(final int position) throws NTLMEngineException {
+ return NTLMEngineImpl.readULong(messageContents, position);
+ }
+
+ /** Read a security buffer from a position within the message buffer */
+ protected byte[] readSecurityBuffer(final int position) throws NTLMEngineException {
+ return NTLMEngineImpl.readSecurityBuffer(messageContents, position);
+ }
+
+ /**
+ * Prepares the object to create a response of the given length.
+ *
+ * @param maxlength
+ * the maximum length of the response to prepare, not
+ * including the type and the signature (which this method
+ * adds).
+ */
+ protected void prepareResponse(final int maxlength, final int messageType) {
+ messageContents = new byte[maxlength];
+ currentOutputPosition = 0;
+ addBytes(SIGNATURE);
+ addULong(messageType);
+ }
+
+ /**
+ * Adds the given byte to the response.
+ *
+ * @param b
+ * the byte to add.
+ */
+ protected void addByte(final byte b) {
+ messageContents[currentOutputPosition] = b;
+ currentOutputPosition++;
+ }
+
+ /**
+ * Adds the given bytes to the response.
+ *
+ * @param bytes
+ * the bytes to add.
+ */
+ protected void addBytes(final byte[] bytes) {
+ if (bytes == null) {
+ return;
+ }
+ for (final byte b : bytes) {
+ messageContents[currentOutputPosition] = b;
+ currentOutputPosition++;
+ }
+ }
+
+ /** Adds a USHORT to the response */
+ protected void addUShort(final int value) {
+ addByte((byte) (value & 0xff));
+ addByte((byte) (value >> 8 & 0xff));
+ }
+
+ /** Adds a ULong to the response */
+ protected void addULong(final int value) {
+ addByte((byte) (value & 0xff));
+ addByte((byte) (value >> 8 & 0xff));
+ addByte((byte) (value >> 16 & 0xff));
+ addByte((byte) (value >> 24 & 0xff));
+ }
+
+ /**
+ * Returns the response that has been generated after shrinking the
+ * array if required and base64 encodes the response.
+ *
+ * @return The response as above.
+ */
+ String getResponse() {
+ final byte[] resp;
+ if (messageContents.length > currentOutputPosition) {
+ final byte[] tmp = new byte[currentOutputPosition];
+ System.arraycopy(messageContents, 0, tmp, 0, currentOutputPosition);
+ resp = tmp;
+ } else {
+ resp = messageContents;
+ }
+ return EncodingUtils.getAsciiString(Base64.encodeBase64(resp));
+ }
+
+ }
+
+ /** Type 1 message assembly class */
+ static class Type1Message extends NTLMMessage {
+ protected byte[] hostBytes;
+ protected byte[] domainBytes;
+
+ /** Constructor. Include the arguments the message will need */
+ Type1Message(final String domain, final String host) throws NTLMEngineException {
+ super();
+ try {
+ // Strip off domain name from the host!
+ final String unqualifiedHost = convertHost(host);
+ // Use only the base domain name!
+ final String unqualifiedDomain = convertDomain(domain);
+
+ hostBytes = unqualifiedHost != null? unqualifiedHost.getBytes("ASCII") : null;
+ domainBytes = unqualifiedDomain != null ? unqualifiedDomain
+ .toUpperCase(Locale.ENGLISH).getBytes("ASCII") : null;
+ } catch (final UnsupportedEncodingException e) {
+ throw new NTLMEngineException("Unicode unsupported: " + e.getMessage(), e);
+ }
+ }
+
+ /**
+ * Getting the response involves building the message before returning
+ * it
+ */
+ @Override
+ String getResponse() {
+ // Now, build the message. Calculate its length first, including
+ // signature or type.
+ final int finalLength = 32 + 8 /*+ hostBytes.length + domainBytes.length */;
+
+ // Set up the response. This will initialize the signature, message
+ // type, and flags.
+ prepareResponse(finalLength, 1);
+
+ // Flags. These are the complete set of flags we support.
+ addULong(
+ //FLAG_WORKSTATION_PRESENT |
+ //FLAG_DOMAIN_PRESENT |
+
+ // Required flags
+ //FLAG_REQUEST_LAN_MANAGER_KEY |
+ FLAG_REQUEST_NTLMv1 |
+ FLAG_REQUEST_NTLM2_SESSION |
+
+ // Protocol version request
+ FLAG_REQUEST_VERSION |
+
+ // Recommended privacy settings
+ FLAG_REQUEST_ALWAYS_SIGN |
+ //FLAG_REQUEST_SEAL |
+ //FLAG_REQUEST_SIGN |
+
+ // These must be set according to documentation, based on use of SEAL above
+ FLAG_REQUEST_128BIT_KEY_EXCH |
+ FLAG_REQUEST_56BIT_ENCRYPTION |
+ //FLAG_REQUEST_EXPLICIT_KEY_EXCH |
+
+ FLAG_REQUEST_UNICODE_ENCODING);
+
+ // Domain length (two times).
+ addUShort(/*domainBytes.length*/0);
+ addUShort(/*domainBytes.length*/0);
+
+ // Domain offset.
+ addULong(/*hostBytes.length +*/ 32 + 8);
+
+ // Host length (two times).
+ addUShort(/*hostBytes.length*/0);
+ addUShort(/*hostBytes.length*/0);
+
+ // Host offset (always 32 + 8).
+ addULong(32 + 8);
+
+ // Version
+ addUShort(0x0105);
+ // Build
+ addULong(2600);
+ // NTLM revision
+ addUShort(0x0f00);
+
+
+ // Host (workstation) String.
+ //addBytes(hostBytes);
+
+ // Domain String.
+ //addBytes(domainBytes);
+
+
+ return super.getResponse();
+ }
+
+ }
+
+ /** Type 2 message class */
+ static class Type2Message extends NTLMMessage {
+ protected byte[] challenge;
+ protected String target;
+ protected byte[] targetInfo;
+ protected int flags;
+
+ Type2Message(final String message) throws NTLMEngineException {
+ super(message, 2);
+
+ // Type 2 message is laid out as follows:
+ // First 8 bytes: NTLMSSP[0]
+ // Next 4 bytes: Ulong, value 2
+ // Next 8 bytes, starting at offset 12: target field (2 ushort lengths, 1 ulong offset)
+ // Next 4 bytes, starting at offset 20: Flags, e.g. 0x22890235
+ // Next 8 bytes, starting at offset 24: Challenge
+ // Next 8 bytes, starting at offset 32: ??? (8 bytes of zeros)
+ // Next 8 bytes, starting at offset 40: targetinfo field (2 ushort lengths, 1 ulong offset)
+ // Next 2 bytes, major/minor version number (e.g. 0x05 0x02)
+ // Next 8 bytes, build number
+ // Next 2 bytes, protocol version number (e.g. 0x00 0x0f)
+ // Next, various text fields, and a ushort of value 0 at the end
+
+ // Parse out the rest of the info we need from the message
+ // The nonce is the 8 bytes starting from the byte in position 24.
+ challenge = new byte[8];
+ readBytes(challenge, 24);
+
+ flags = readULong(20);
+
+ if ((flags & FLAG_REQUEST_UNICODE_ENCODING) == 0) {
+ throw new NTLMEngineException(
+ "NTLM type 2 message has flags that make no sense: "
+ + Integer.toString(flags));
+ }
+
+ // Do the target!
+ target = null;
+ // The TARGET_DESIRED flag is said to not have understood semantics
+ // in Type2 messages, so use the length of the packet to decide
+ // how to proceed instead
+ if (getMessageLength() >= 12 + 8) {
+ final byte[] bytes = readSecurityBuffer(12);
+ if (bytes.length != 0) {
+ try {
+ target = new String(bytes, "UnicodeLittleUnmarked");
+ } catch (final UnsupportedEncodingException e) {
+ throw new NTLMEngineException(e.getMessage(), e);
+ }
+ }
+ }
+
+ // Do the target info!
+ targetInfo = null;
+ // TARGET_DESIRED flag cannot be relied on, so use packet length
+ if (getMessageLength() >= 40 + 8) {
+ final byte[] bytes = readSecurityBuffer(40);
+ if (bytes.length != 0) {
+ targetInfo = bytes;
+ }
+ }
+ }
+
+ /** Retrieve the challenge */
+ byte[] getChallenge() {
+ return challenge;
+ }
+
+ /** Retrieve the target */
+ String getTarget() {
+ return target;
+ }
+
+ /** Retrieve the target info */
+ byte[] getTargetInfo() {
+ return targetInfo;
+ }
+
+ /** Retrieve the response flags */
+ int getFlags() {
+ return flags;
+ }
+
+ }
+
+ /** Type 3 message assembly class */
+ static class Type3Message extends NTLMMessage {
+ // Response flags from the type2 message
+ protected int type2Flags;
+
+ protected byte[] domainBytes;
+ protected byte[] hostBytes;
+ protected byte[] userBytes;
+
+ protected byte[] lmResp;
+ protected byte[] ntResp;
+ protected byte[] sessionKey;
+
+
+ /** Constructor. Pass the arguments we will need */
+ Type3Message(final String domain, final String host, final String user, final String password, final byte[] nonce,
+ final int type2Flags, final String target, final byte[] targetInformation)
+ throws NTLMEngineException {
+ // Save the flags
+ this.type2Flags = type2Flags;
+
+ // Strip off domain name from the host!
+ final String unqualifiedHost = convertHost(host);
+ // Use only the base domain name!
+ final String unqualifiedDomain = convertDomain(domain);
+
+ // Create a cipher generator class. Use domain BEFORE it gets modified!
+ final CipherGen gen = new CipherGen(unqualifiedDomain, user, password, nonce, target, targetInformation);
+
+ // Use the new code to calculate the responses, including v2 if that
+ // seems warranted.
+ byte[] userSessionKey;
+ try {
+ // This conditional may not work on Windows Server 2008 R2 and above, where it has not yet
+ // been tested
+ if (((type2Flags & FLAG_TARGETINFO_PRESENT) != 0) &&
+ targetInformation != null && target != null) {
+ // NTLMv2
+ ntResp = gen.getNTLMv2Response();
+ lmResp = gen.getLMv2Response();
+ if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) {
+ userSessionKey = gen.getLanManagerSessionKey();
+ } else {
+ userSessionKey = gen.getNTLMv2UserSessionKey();
+ }
+ } else {
+ // NTLMv1
+ if ((type2Flags & FLAG_REQUEST_NTLM2_SESSION) != 0) {
+ // NTLM2 session stuff is requested
+ ntResp = gen.getNTLM2SessionResponse();
+ lmResp = gen.getLM2SessionResponse();
+ if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) {
+ userSessionKey = gen.getLanManagerSessionKey();
+ } else {
+ userSessionKey = gen.getNTLM2SessionResponseUserSessionKey();
+ }
+ } else {
+ ntResp = gen.getNTLMResponse();
+ lmResp = gen.getLMResponse();
+ if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) {
+ userSessionKey = gen.getLanManagerSessionKey();
+ } else {
+ userSessionKey = gen.getNTLMUserSessionKey();
+ }
+ }
+ }
+ } catch (final NTLMEngineException e) {
+ // This likely means we couldn't find the MD4 hash algorithm -
+ // fail back to just using LM
+ ntResp = new byte[0];
+ lmResp = gen.getLMResponse();
+ if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) {
+ userSessionKey = gen.getLanManagerSessionKey();
+ } else {
+ userSessionKey = gen.getLMUserSessionKey();
+ }
+ }
+
+ if ((type2Flags & FLAG_REQUEST_SIGN) != 0) {
+ if ((type2Flags & FLAG_REQUEST_EXPLICIT_KEY_EXCH) != 0) {
+ sessionKey = RC4(gen.getSecondaryKey(), userSessionKey);
+ } else {
+ sessionKey = userSessionKey;
+ }
+ } else {
+ sessionKey = null;
+ }
+
+ try {
+ hostBytes = unqualifiedHost != null ? unqualifiedHost
+ .getBytes("UnicodeLittleUnmarked") : null;
+ domainBytes = unqualifiedDomain != null ? unqualifiedDomain
+ .toUpperCase(Locale.ENGLISH).getBytes("UnicodeLittleUnmarked") : null;
+ userBytes = user.getBytes("UnicodeLittleUnmarked");
+ } catch (final UnsupportedEncodingException e) {
+ throw new NTLMEngineException("Unicode not supported: " + e.getMessage(), e);
+ }
+ }
+
+ /** Assemble the response */
+ @Override
+ String getResponse() {
+ final int ntRespLen = ntResp.length;
+ final int lmRespLen = lmResp.length;
+
+ final int domainLen = domainBytes != null ? domainBytes.length : 0;
+ final int hostLen = hostBytes != null ? hostBytes.length: 0;
+ final int userLen = userBytes.length;
+ final int sessionKeyLen;
+ if (sessionKey != null) {
+ sessionKeyLen = sessionKey.length;
+ } else {
+ sessionKeyLen = 0;
+ }
+
+ // Calculate the layout within the packet
+ final int lmRespOffset = 72; // allocate space for the version
+ final int ntRespOffset = lmRespOffset + lmRespLen;
+ final int domainOffset = ntRespOffset + ntRespLen;
+ final int userOffset = domainOffset + domainLen;
+ final int hostOffset = userOffset + userLen;
+ final int sessionKeyOffset = hostOffset + hostLen;
+ final int finalLength = sessionKeyOffset + sessionKeyLen;
+
+ // Start the response. Length includes signature and type
+ prepareResponse(finalLength, 3);
+
+ // LM Resp Length (twice)
+ addUShort(lmRespLen);
+ addUShort(lmRespLen);
+
+ // LM Resp Offset
+ addULong(lmRespOffset);
+
+ // NT Resp Length (twice)
+ addUShort(ntRespLen);
+ addUShort(ntRespLen);
+
+ // NT Resp Offset
+ addULong(ntRespOffset);
+
+ // Domain length (twice)
+ addUShort(domainLen);
+ addUShort(domainLen);
+
+ // Domain offset.
+ addULong(domainOffset);
+
+ // User Length (twice)
+ addUShort(userLen);
+ addUShort(userLen);
+
+ // User offset
+ addULong(userOffset);
+
+ // Host length (twice)
+ addUShort(hostLen);
+ addUShort(hostLen);
+
+ // Host offset
+ addULong(hostOffset);
+
+ // Session key length (twice)
+ addUShort(sessionKeyLen);
+ addUShort(sessionKeyLen);
+
+ // Session key offset
+ addULong(sessionKeyOffset);
+
+ // Flags.
+ addULong(
+ //FLAG_WORKSTATION_PRESENT |
+ //FLAG_DOMAIN_PRESENT |
+
+ // Required flags
+ (type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) |
+ (type2Flags & FLAG_REQUEST_NTLMv1) |
+ (type2Flags & FLAG_REQUEST_NTLM2_SESSION) |
+
+ // Protocol version request
+ FLAG_REQUEST_VERSION |
+
+ // Recommended privacy settings
+ (type2Flags & FLAG_REQUEST_ALWAYS_SIGN) |
+ (type2Flags & FLAG_REQUEST_SEAL) |
+ (type2Flags & FLAG_REQUEST_SIGN) |
+
+ // These must be set according to documentation, based on use of SEAL above
+ (type2Flags & FLAG_REQUEST_128BIT_KEY_EXCH) |
+ (type2Flags & FLAG_REQUEST_56BIT_ENCRYPTION) |
+ (type2Flags & FLAG_REQUEST_EXPLICIT_KEY_EXCH) |
+
+ (type2Flags & FLAG_TARGETINFO_PRESENT) |
+ (type2Flags & FLAG_REQUEST_UNICODE_ENCODING) |
+ (type2Flags & FLAG_REQUEST_TARGET)
+ );
+
+ // Version
+ addUShort(0x0105);
+ // Build
+ addULong(2600);
+ // NTLM revision
+ addUShort(0x0f00);
+
+ // Add the actual data
+ addBytes(lmResp);
+ addBytes(ntResp);
+ addBytes(domainBytes);
+ addBytes(userBytes);
+ addBytes(hostBytes);
+ if (sessionKey != null) {
+ addBytes(sessionKey);
+ }
+
+ return super.getResponse();
+ }
+ }
+
+ static void writeULong(final byte[] buffer, final int value, final int offset) {
+ buffer[offset] = (byte) (value & 0xff);
+ buffer[offset + 1] = (byte) (value >> 8 & 0xff);
+ buffer[offset + 2] = (byte) (value >> 16 & 0xff);
+ buffer[offset + 3] = (byte) (value >> 24 & 0xff);
+ }
+
+ static int F(final int x, final int y, final int z) {
+ return ((x & y) | (~x & z));
+ }
+
+ static int G(final int x, final int y, final int z) {
+ return ((x & y) | (x & z) | (y & z));
+ }
+
+ static int H(final int x, final int y, final int z) {
+ return (x ^ y ^ z);
+ }
+
+ static int rotintlft(final int val, final int numbits) {
+ return ((val << numbits) | (val >>> (32 - numbits)));
+ }
+
+ /**
+ * Cryptography support - MD4. The following class was based loosely on the
+ * RFC and on code found at http://www.cs.umd.edu/~harry/jotp/src/md.java.
+ * Code correctness was verified by looking at MD4.java from the jcifs
+ * library (http://jcifs.samba.org). It was massaged extensively to the
+ * final form found here by Karl Wright (kwright@metacarta.com).
+ */
+ static class MD4 {
+ protected int A = 0x67452301;
+ protected int B = 0xefcdab89;
+ protected int C = 0x98badcfe;
+ protected int D = 0x10325476;
+ protected long count = 0L;
+ protected byte[] dataBuffer = new byte[64];
+
+ MD4() {
+ }
+
+ void update(final byte[] input) {
+ // We always deal with 512 bits at a time. Correspondingly, there is
+ // a buffer 64 bytes long that we write data into until it gets
+ // full.
+ int curBufferPos = (int) (count & 63L);
+ int inputIndex = 0;
+ while (input.length - inputIndex + curBufferPos >= dataBuffer.length) {
+ // We have enough data to do the next step. Do a partial copy
+ // and a transform, updating inputIndex and curBufferPos
+ // accordingly
+ final int transferAmt = dataBuffer.length - curBufferPos;
+ System.arraycopy(input, inputIndex, dataBuffer, curBufferPos, transferAmt);
+ count += transferAmt;
+ curBufferPos = 0;
+ inputIndex += transferAmt;
+ processBuffer();
+ }
+
+ // If there's anything left, copy it into the buffer and leave it.
+ // We know there's not enough left to process.
+ if (inputIndex < input.length) {
+ final int transferAmt = input.length - inputIndex;
+ System.arraycopy(input, inputIndex, dataBuffer, curBufferPos, transferAmt);
+ count += transferAmt;
+ curBufferPos += transferAmt;
+ }
+ }
+
+ byte[] getOutput() {
+ // Feed pad/length data into engine. This must round out the input
+ // to a multiple of 512 bits.
+ final int bufferIndex = (int) (count & 63L);
+ final int padLen = (bufferIndex < 56) ? (56 - bufferIndex) : (120 - bufferIndex);
+ final byte[] postBytes = new byte[padLen + 8];
+ // Leading 0x80, specified amount of zero padding, then length in
+ // bits.
+ postBytes[0] = (byte) 0x80;
+ // Fill out the last 8 bytes with the length
+ for (int i = 0; i < 8; i++) {
+ postBytes[padLen + i] = (byte) ((count * 8) >>> (8 * i));
+ }
+
+ // Update the engine
+ update(postBytes);
+
+ // Calculate final result
+ final byte[] result = new byte[16];
+ writeULong(result, A, 0);
+ writeULong(result, B, 4);
+ writeULong(result, C, 8);
+ writeULong(result, D, 12);
+ return result;
+ }
+
+ protected void processBuffer() {
+ // Convert current buffer to 16 ulongs
+ final int[] d = new int[16];
+
+ for (int i = 0; i < 16; i++) {
+ d[i] = (dataBuffer[i * 4] & 0xff) + ((dataBuffer[i * 4 + 1] & 0xff) << 8)
+ + ((dataBuffer[i * 4 + 2] & 0xff) << 16)
+ + ((dataBuffer[i * 4 + 3] & 0xff) << 24);
+ }
+
+ // Do a round of processing
+ final int AA = A;
+ final int BB = B;
+ final int CC = C;
+ final int DD = D;
+ round1(d);
+ round2(d);
+ round3(d);
+ A += AA;
+ B += BB;
+ C += CC;
+ D += DD;
+
+ }
+
+ protected void round1(final int[] d) {
+ A = rotintlft((A + F(B, C, D) + d[0]), 3);
+ D = rotintlft((D + F(A, B, C) + d[1]), 7);
+ C = rotintlft((C + F(D, A, B) + d[2]), 11);
+ B = rotintlft((B + F(C, D, A) + d[3]), 19);
+
+ A = rotintlft((A + F(B, C, D) + d[4]), 3);
+ D = rotintlft((D + F(A, B, C) + d[5]), 7);
+ C = rotintlft((C + F(D, A, B) + d[6]), 11);
+ B = rotintlft((B + F(C, D, A) + d[7]), 19);
+
+ A = rotintlft((A + F(B, C, D) + d[8]), 3);
+ D = rotintlft((D + F(A, B, C) + d[9]), 7);
+ C = rotintlft((C + F(D, A, B) + d[10]), 11);
+ B = rotintlft((B + F(C, D, A) + d[11]), 19);
+
+ A = rotintlft((A + F(B, C, D) + d[12]), 3);
+ D = rotintlft((D + F(A, B, C) + d[13]), 7);
+ C = rotintlft((C + F(D, A, B) + d[14]), 11);
+ B = rotintlft((B + F(C, D, A) + d[15]), 19);
+ }
+
+ protected void round2(final int[] d) {
+ A = rotintlft((A + G(B, C, D) + d[0] + 0x5a827999), 3);
+ D = rotintlft((D + G(A, B, C) + d[4] + 0x5a827999), 5);
+ C = rotintlft((C + G(D, A, B) + d[8] + 0x5a827999), 9);
+ B = rotintlft((B + G(C, D, A) + d[12] + 0x5a827999), 13);
+
+ A = rotintlft((A + G(B, C, D) + d[1] + 0x5a827999), 3);
+ D = rotintlft((D + G(A, B, C) + d[5] + 0x5a827999), 5);
+ C = rotintlft((C + G(D, A, B) + d[9] + 0x5a827999), 9);
+ B = rotintlft((B + G(C, D, A) + d[13] + 0x5a827999), 13);
+
+ A = rotintlft((A + G(B, C, D) + d[2] + 0x5a827999), 3);
+ D = rotintlft((D + G(A, B, C) + d[6] + 0x5a827999), 5);
+ C = rotintlft((C + G(D, A, B) + d[10] + 0x5a827999), 9);
+ B = rotintlft((B + G(C, D, A) + d[14] + 0x5a827999), 13);
+
+ A = rotintlft((A + G(B, C, D) + d[3] + 0x5a827999), 3);
+ D = rotintlft((D + G(A, B, C) + d[7] + 0x5a827999), 5);
+ C = rotintlft((C + G(D, A, B) + d[11] + 0x5a827999), 9);
+ B = rotintlft((B + G(C, D, A) + d[15] + 0x5a827999), 13);
+
+ }
+
+ protected void round3(final int[] d) {
+ A = rotintlft((A + H(B, C, D) + d[0] + 0x6ed9eba1), 3);
+ D = rotintlft((D + H(A, B, C) + d[8] + 0x6ed9eba1), 9);
+ C = rotintlft((C + H(D, A, B) + d[4] + 0x6ed9eba1), 11);
+ B = rotintlft((B + H(C, D, A) + d[12] + 0x6ed9eba1), 15);
+
+ A = rotintlft((A + H(B, C, D) + d[2] + 0x6ed9eba1), 3);
+ D = rotintlft((D + H(A, B, C) + d[10] + 0x6ed9eba1), 9);
+ C = rotintlft((C + H(D, A, B) + d[6] + 0x6ed9eba1), 11);
+ B = rotintlft((B + H(C, D, A) + d[14] + 0x6ed9eba1), 15);
+
+ A = rotintlft((A + H(B, C, D) + d[1] + 0x6ed9eba1), 3);
+ D = rotintlft((D + H(A, B, C) + d[9] + 0x6ed9eba1), 9);
+ C = rotintlft((C + H(D, A, B) + d[5] + 0x6ed9eba1), 11);
+ B = rotintlft((B + H(C, D, A) + d[13] + 0x6ed9eba1), 15);
+
+ A = rotintlft((A + H(B, C, D) + d[3] + 0x6ed9eba1), 3);
+ D = rotintlft((D + H(A, B, C) + d[11] + 0x6ed9eba1), 9);
+ C = rotintlft((C + H(D, A, B) + d[7] + 0x6ed9eba1), 11);
+ B = rotintlft((B + H(C, D, A) + d[15] + 0x6ed9eba1), 15);
+
+ }
+
+ }
+
+ /**
+ * Cryptography support - HMACMD5 - algorithmically based on various web
+ * resources by Karl Wright
+ */
+ static class HMACMD5 {
+ protected byte[] ipad;
+ protected byte[] opad;
+ protected MessageDigest md5;
+
+ HMACMD5(final byte[] input) throws NTLMEngineException {
+ byte[] key = input;
+ try {
+ md5 = MessageDigest.getInstance("MD5");
+ } catch (final Exception ex) {
+ // Umm, the algorithm doesn't exist - throw an
+ // NTLMEngineException!
+ throw new NTLMEngineException(
+ "Error getting md5 message digest implementation: " + ex.getMessage(), ex);
+ }
+
+ // Initialize the pad buffers with the key
+ ipad = new byte[64];
+ opad = new byte[64];
+
+ int keyLength = key.length;
+ if (keyLength > 64) {
+ // Use MD5 of the key instead, as described in RFC 2104
+ md5.update(key);
+ key = md5.digest();
+ keyLength = key.length;
+ }
+ int i = 0;
+ while (i < keyLength) {
+ ipad[i] = (byte) (key[i] ^ (byte) 0x36);
+ opad[i] = (byte) (key[i] ^ (byte) 0x5c);
+ i++;
+ }
+ while (i < 64) {
+ ipad[i] = (byte) 0x36;
+ opad[i] = (byte) 0x5c;
+ i++;
+ }
+
+ // Very important: update the digest with the ipad buffer
+ md5.reset();
+ md5.update(ipad);
+
+ }
+
+ /** Grab the current digest. This is the "answer". */
+ byte[] getOutput() {
+ final byte[] digest = md5.digest();
+ md5.update(opad);
+ return md5.digest(digest);
+ }
+
+ /** Update by adding a complete array */
+ void update(final byte[] input) {
+ md5.update(input);
+ }
+
+ /** Update the algorithm */
+ void update(final byte[] input, final int offset, final int length) {
+ md5.update(input, offset, length);
+ }
+
+ }
+
+ public String generateType1Msg(
+ final String domain,
+ final String workstation) throws NTLMEngineException {
+ return getType1Message(workstation, domain);
+ }
+
+ public String generateType3Msg(
+ final String username,
+ final String password,
+ final String domain,
+ final String workstation,
+ final String challenge) throws NTLMEngineException {
+ final Type2Message t2m = new Type2Message(challenge);
+ return getType3Message(
+ username,
+ password,
+ workstation,
+ domain,
+ t2m.getChallenge(),
+ t2m.getFlags(),
+ t2m.getTarget(),
+ t2m.getTargetInfo());
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/NTLMScheme.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/NTLMScheme.java
new file mode 100644
index 000000000..68873954b
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/NTLMScheme.java
@@ -0,0 +1,164 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.auth;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.auth.AUTH;
+import ch.boye.httpclientandroidlib.auth.AuthenticationException;
+import ch.boye.httpclientandroidlib.auth.Credentials;
+import ch.boye.httpclientandroidlib.auth.InvalidCredentialsException;
+import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
+import ch.boye.httpclientandroidlib.auth.NTCredentials;
+import ch.boye.httpclientandroidlib.message.BufferedHeader;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
+
+/**
+ * NTLM is a proprietary authentication scheme developed by Microsoft
+ * and optimized for Windows platforms.
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class NTLMScheme extends AuthSchemeBase {
+
+ enum State {
+ UNINITIATED,
+ CHALLENGE_RECEIVED,
+ MSG_TYPE1_GENERATED,
+ MSG_TYPE2_RECEVIED,
+ MSG_TYPE3_GENERATED,
+ FAILED,
+ }
+
+ private final NTLMEngine engine;
+
+ private State state;
+ private String challenge;
+
+ public NTLMScheme(final NTLMEngine engine) {
+ super();
+ Args.notNull(engine, "NTLM engine");
+ this.engine = engine;
+ this.state = State.UNINITIATED;
+ this.challenge = null;
+ }
+
+ /**
+ * @since 4.3
+ */
+ public NTLMScheme() {
+ this(new NTLMEngineImpl());
+ }
+
+ public String getSchemeName() {
+ return "ntlm";
+ }
+
+ public String getParameter(final String name) {
+ // String parameters not supported
+ return null;
+ }
+
+ public String getRealm() {
+ // NTLM does not support the concept of an authentication realm
+ return null;
+ }
+
+ public boolean isConnectionBased() {
+ return true;
+ }
+
+ @Override
+ protected void parseChallenge(
+ final CharArrayBuffer buffer,
+ final int beginIndex, final int endIndex) throws MalformedChallengeException {
+ this.challenge = buffer.substringTrimmed(beginIndex, endIndex);
+ if (this.challenge.length() == 0) {
+ if (this.state == State.UNINITIATED) {
+ this.state = State.CHALLENGE_RECEIVED;
+ } else {
+ this.state = State.FAILED;
+ }
+ } else {
+ if (this.state.compareTo(State.MSG_TYPE1_GENERATED) < 0) {
+ this.state = State.FAILED;
+ throw new MalformedChallengeException("Out of sequence NTLM response message");
+ } else if (this.state == State.MSG_TYPE1_GENERATED) {
+ this.state = State.MSG_TYPE2_RECEVIED;
+ }
+ }
+ }
+
+ public Header authenticate(
+ final Credentials credentials,
+ final HttpRequest request) throws AuthenticationException {
+ NTCredentials ntcredentials = null;
+ try {
+ ntcredentials = (NTCredentials) credentials;
+ } catch (final ClassCastException e) {
+ throw new InvalidCredentialsException(
+ "Credentials cannot be used for NTLM authentication: "
+ + credentials.getClass().getName());
+ }
+ String response = null;
+ if (this.state == State.FAILED) {
+ throw new AuthenticationException("NTLM authentication failed");
+ } else if (this.state == State.CHALLENGE_RECEIVED) {
+ response = this.engine.generateType1Msg(
+ ntcredentials.getDomain(),
+ ntcredentials.getWorkstation());
+ this.state = State.MSG_TYPE1_GENERATED;
+ } else if (this.state == State.MSG_TYPE2_RECEVIED) {
+ response = this.engine.generateType3Msg(
+ ntcredentials.getUserName(),
+ ntcredentials.getPassword(),
+ ntcredentials.getDomain(),
+ ntcredentials.getWorkstation(),
+ this.challenge);
+ this.state = State.MSG_TYPE3_GENERATED;
+ } else {
+ throw new AuthenticationException("Unexpected state: " + this.state);
+ }
+ final CharArrayBuffer buffer = new CharArrayBuffer(32);
+ if (isProxy()) {
+ buffer.append(AUTH.PROXY_AUTH_RESP);
+ } else {
+ buffer.append(AUTH.WWW_AUTH_RESP);
+ }
+ buffer.append(": NTLM ");
+ buffer.append(response);
+ return new BufferedHeader(buffer);
+ }
+
+ public boolean isComplete() {
+ return this.state == State.MSG_TYPE3_GENERATED || this.state == State.FAILED;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/NTLMSchemeFactory.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/NTLMSchemeFactory.java
new file mode 100644
index 000000000..0484df643
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/NTLMSchemeFactory.java
@@ -0,0 +1,56 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.auth;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.auth.AuthScheme;
+import ch.boye.httpclientandroidlib.auth.AuthSchemeFactory;
+import ch.boye.httpclientandroidlib.auth.AuthSchemeProvider;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+/**
+ * {@link AuthSchemeProvider} implementation that creates and initializes
+ * {@link NTLMScheme} instances configured to use the default {@link NTLMEngine}
+ * implementation.
+ *
+ * @since 4.1
+ */
+@Immutable
+@SuppressWarnings("deprecation")
+public class NTLMSchemeFactory implements AuthSchemeFactory, AuthSchemeProvider {
+
+ public AuthScheme newInstance(final HttpParams params) {
+ return new NTLMScheme();
+ }
+
+ public AuthScheme create(final HttpContext context) {
+ return new NTLMScheme();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/RFC2617Scheme.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/RFC2617Scheme.java
new file mode 100644
index 000000000..93d1bf843
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/RFC2617Scheme.java
@@ -0,0 +1,151 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.auth;
+
+import java.nio.charset.Charset;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+
+import ch.boye.httpclientandroidlib.Consts;
+import ch.boye.httpclientandroidlib.HeaderElement;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.auth.ChallengeState;
+import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
+import ch.boye.httpclientandroidlib.auth.params.AuthPNames;
+import ch.boye.httpclientandroidlib.message.BasicHeaderValueParser;
+import ch.boye.httpclientandroidlib.message.HeaderValueParser;
+import ch.boye.httpclientandroidlib.message.ParserCursor;
+import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
+
+/**
+ * Abstract authentication scheme class that lays foundation for all
+ * RFC 2617 compliant authentication schemes and provides capabilities common
+ * to all authentication schemes defined in RFC 2617.
+ *
+ * @since 4.0
+ */
+@SuppressWarnings("deprecation")
+@NotThreadSafe // AuthSchemeBase, params
+public abstract class RFC2617Scheme extends AuthSchemeBase {
+
+ private final Map params;
+ private final Charset credentialsCharset;
+
+ /**
+ * Creates an instance of RFC2617Scheme with the given challenge
+ * state.
+ *
+ * @since 4.2
+ *
+ * @deprecated (4.3) do not use.
+ */
+ @Deprecated
+ public RFC2617Scheme(final ChallengeState challengeState) {
+ super(challengeState);
+ this.params = new HashMap();
+ this.credentialsCharset = Consts.ASCII;
+ }
+
+ /**
+ * @since 4.3
+ */
+ public RFC2617Scheme(final Charset credentialsCharset) {
+ super();
+ this.params = new HashMap();
+ this.credentialsCharset = credentialsCharset != null ? credentialsCharset : Consts.ASCII;
+ }
+
+ public RFC2617Scheme() {
+ this(Consts.ASCII);
+ }
+
+
+ /**
+ * @since 4.3
+ */
+ public Charset getCredentialsCharset() {
+ return credentialsCharset;
+ }
+
+ String getCredentialsCharset(final HttpRequest request) {
+ String charset = (String) request.getParams().getParameter(AuthPNames.CREDENTIAL_CHARSET);
+ if (charset == null) {
+ charset = getCredentialsCharset().name();
+ }
+ return charset;
+ }
+
+ @Override
+ protected void parseChallenge(
+ final CharArrayBuffer buffer, final int pos, final int len) throws MalformedChallengeException {
+ final HeaderValueParser parser = BasicHeaderValueParser.INSTANCE;
+ final ParserCursor cursor = new ParserCursor(pos, buffer.length());
+ final HeaderElement[] elements = parser.parseElements(buffer, cursor);
+ if (elements.length == 0) {
+ throw new MalformedChallengeException("Authentication challenge is empty");
+ }
+ this.params.clear();
+ for (final HeaderElement element : elements) {
+ this.params.put(element.getName().toLowerCase(Locale.ENGLISH), element.getValue());
+ }
+ }
+
+ /**
+ * Returns authentication parameters map. Keys in the map are lower-cased.
+ *
+ * @return the map of authentication parameters
+ */
+ protected Map getParameters() {
+ return this.params;
+ }
+
+ /**
+ * Returns authentication parameter with the given name, if available.
+ *
+ * @param name The name of the parameter to be returned
+ *
+ * @return the parameter with the given name
+ */
+ public String getParameter(final String name) {
+ if (name == null) {
+ return null;
+ }
+ return this.params.get(name.toLowerCase(Locale.ENGLISH));
+ }
+
+ /**
+ * Returns authentication realm. The realm may not be null.
+ *
+ * @return the authentication realm
+ */
+ public String getRealm() {
+ return getParameter("realm");
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/SpnegoTokenGenerator.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/SpnegoTokenGenerator.java
new file mode 100644
index 000000000..5ab0348ad
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/SpnegoTokenGenerator.java
@@ -0,0 +1,47 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.auth;
+
+import java.io.IOException;
+
+/**
+ * Abstract SPNEGO token generator. Implementations should take an Kerberos ticket and transform
+ * into a SPNEGO token.
+ *
+ * Implementations of this interface are expected to be thread-safe.
+ *
+ * @since 4.1
+ *
+ * @deprecated (4.2) subclass {@link KerberosScheme} and override
+ * {@link KerberosScheme#generateGSSToken(byte[], org.ietf.jgss.Oid, String)}
+ */
+@Deprecated
+public interface SpnegoTokenGenerator {
+
+ byte [] generateSpnegoDERObject(byte [] kerberosTicket) throws IOException;
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/UnsupportedDigestAlgorithmException.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/UnsupportedDigestAlgorithmException.java
new file mode 100644
index 000000000..71a6f892f
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/UnsupportedDigestAlgorithmException.java
@@ -0,0 +1,69 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.auth;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+
+/**
+ * Authentication credentials required to respond to a authentication
+ * challenge are invalid
+ *
+ *
+ * @since 4.0
+ */
+@Immutable
+public class UnsupportedDigestAlgorithmException extends RuntimeException {
+
+ private static final long serialVersionUID = 319558534317118022L;
+
+ /**
+ * Creates a new UnsupportedAuthAlgoritmException with a null detail message.
+ */
+ public UnsupportedDigestAlgorithmException() {
+ super();
+ }
+
+ /**
+ * Creates a new UnsupportedAuthAlgoritmException with the specified message.
+ *
+ * @param message the exception detail message
+ */
+ public UnsupportedDigestAlgorithmException(final String message) {
+ super(message);
+ }
+
+ /**
+ * Creates a new UnsupportedAuthAlgoritmException with the specified detail message and cause.
+ *
+ * @param message the exception detail message
+ * @param cause the Throwable that caused this exception, or null
+ * if the cause is unavailable, unknown, or not a Throwable
+ */
+ public UnsupportedDigestAlgorithmException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/package-info.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/package-info.java
new file mode 100644
index 000000000..9e35c852d
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/auth/package-info.java
@@ -0,0 +1,32 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+/**
+ * Default implementations of standard and common HTTP authentication
+ * schemes.
+ */
+package ch.boye.httpclientandroidlib.impl.auth;
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AIMDBackoffManager.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AIMDBackoffManager.java
new file mode 100644
index 000000000..67798a683
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AIMDBackoffManager.java
@@ -0,0 +1,164 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import ch.boye.httpclientandroidlib.client.BackoffManager;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.pool.ConnPoolControl;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ *
The AIMDBackoffManager applies an additive increase,
+ * multiplicative decrease (AIMD) to managing a dynamic limit to
+ * the number of connections allowed to a given host. You may want
+ * to experiment with the settings for the cooldown periods and the
+ * backoff factor to get the adaptive behavior you want.
+ *
+ *
Generally speaking, shorter cooldowns will lead to more steady-state
+ * variability but faster reaction times, while longer cooldowns
+ * will lead to more stable equilibrium behavior but slower reaction
+ * times.
+ *
+ *
Similarly, higher backoff factors promote greater
+ * utilization of available capacity at the expense of fairness
+ * among clients. Lower backoff factors allow equal distribution of
+ * capacity among clients (fairness) to happen faster, at the
+ * expense of having more server capacity unused in the short term.
+ *
+ * @since 4.2
+ */
+public class AIMDBackoffManager implements BackoffManager {
+
+ private final ConnPoolControl connPerRoute;
+ private final Clock clock;
+ private final Map lastRouteProbes;
+ private final Map lastRouteBackoffs;
+ private long coolDown = 5 * 1000L;
+ private double backoffFactor = 0.5;
+ private int cap = 2; // Per RFC 2616 sec 8.1.4
+
+ /**
+ * Creates an AIMDBackoffManager to manage
+ * per-host connection pool sizes represented by the
+ * given {@link ConnPoolControl}.
+ * @param connPerRoute per-host routing maximums to
+ * be managed
+ */
+ public AIMDBackoffManager(final ConnPoolControl connPerRoute) {
+ this(connPerRoute, new SystemClock());
+ }
+
+ AIMDBackoffManager(final ConnPoolControl connPerRoute, final Clock clock) {
+ this.clock = clock;
+ this.connPerRoute = connPerRoute;
+ this.lastRouteProbes = new HashMap();
+ this.lastRouteBackoffs = new HashMap();
+ }
+
+ public void backOff(final HttpRoute route) {
+ synchronized(connPerRoute) {
+ final int curr = connPerRoute.getMaxPerRoute(route);
+ final Long lastUpdate = getLastUpdate(lastRouteBackoffs, route);
+ final long now = clock.getCurrentTime();
+ if (now - lastUpdate.longValue() < coolDown) {
+ return;
+ }
+ connPerRoute.setMaxPerRoute(route, getBackedOffPoolSize(curr));
+ lastRouteBackoffs.put(route, Long.valueOf(now));
+ }
+ }
+
+ private int getBackedOffPoolSize(final int curr) {
+ if (curr <= 1) {
+ return 1;
+ }
+ return (int)(Math.floor(backoffFactor * curr));
+ }
+
+ public void probe(final HttpRoute route) {
+ synchronized(connPerRoute) {
+ final int curr = connPerRoute.getMaxPerRoute(route);
+ final int max = (curr >= cap) ? cap : curr + 1;
+ final Long lastProbe = getLastUpdate(lastRouteProbes, route);
+ final Long lastBackoff = getLastUpdate(lastRouteBackoffs, route);
+ final long now = clock.getCurrentTime();
+ if (now - lastProbe.longValue() < coolDown || now - lastBackoff.longValue() < coolDown) {
+ return;
+ }
+ connPerRoute.setMaxPerRoute(route, max);
+ lastRouteProbes.put(route, Long.valueOf(now));
+ }
+ }
+
+ private Long getLastUpdate(final Map updates, final HttpRoute route) {
+ Long lastUpdate = updates.get(route);
+ if (lastUpdate == null) {
+ lastUpdate = Long.valueOf(0L);
+ }
+ return lastUpdate;
+ }
+
+ /**
+ * Sets the factor to use when backing off; the new
+ * per-host limit will be roughly the current max times
+ * this factor. Math.floor is applied in the
+ * case of non-integer outcomes to ensure we actually
+ * decrease the pool size. Pool sizes are never decreased
+ * below 1, however. Defaults to 0.5.
+ * @param d must be between 0.0 and 1.0, exclusive.
+ */
+ public void setBackoffFactor(final double d) {
+ Args.check(d > 0.0 && d < 1.0, "Backoff factor must be 0.0 < f < 1.0");
+ backoffFactor = d;
+ }
+
+ /**
+ * Sets the amount of time, in milliseconds, to wait between
+ * adjustments in pool sizes for a given host, to allow
+ * enough time for the adjustments to take effect. Defaults
+ * to 5000L (5 seconds).
+ * @param l must be positive
+ */
+ public void setCooldownMillis(final long l) {
+ Args.positive(coolDown, "Cool down");
+ coolDown = l;
+ }
+
+ /**
+ * Sets the absolute maximum per-host connection pool size to
+ * probe up to; defaults to 2 (the default per-host max).
+ * @param cap must be >= 1
+ */
+ public void setPerHostConnectionCap(final int cap) {
+ Args.positive(cap, "Per host connection cap");
+ this.cap = cap;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AbstractAuthenticationHandler.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AbstractAuthenticationHandler.java
new file mode 100644
index 000000000..a02c1a03b
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AbstractAuthenticationHandler.java
@@ -0,0 +1,189 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.FormattedHeader;
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.auth.AuthScheme;
+import ch.boye.httpclientandroidlib.auth.AuthSchemeRegistry;
+import ch.boye.httpclientandroidlib.auth.AuthenticationException;
+import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
+import ch.boye.httpclientandroidlib.client.AuthenticationHandler;
+import ch.boye.httpclientandroidlib.client.params.AuthPolicy;
+import ch.boye.httpclientandroidlib.client.protocol.ClientContext;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Asserts;
+import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
+
+/**
+ * Base class for {@link AuthenticationHandler} implementations.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.2) use {@link ch.boye.httpclientandroidlib.client.AuthenticationStrategy}
+ */
+@Deprecated
+@Immutable
+public abstract class AbstractAuthenticationHandler implements AuthenticationHandler {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ private static final List DEFAULT_SCHEME_PRIORITY =
+ Collections.unmodifiableList(Arrays.asList(new String[] {
+ AuthPolicy.SPNEGO,
+ AuthPolicy.NTLM,
+ AuthPolicy.DIGEST,
+ AuthPolicy.BASIC
+ }));
+
+ public AbstractAuthenticationHandler() {
+ super();
+ }
+
+ protected Map parseChallenges(
+ final Header[] headers) throws MalformedChallengeException {
+
+ final Map map = new HashMap(headers.length);
+ for (final Header header : headers) {
+ final CharArrayBuffer buffer;
+ int pos;
+ if (header instanceof FormattedHeader) {
+ buffer = ((FormattedHeader) header).getBuffer();
+ pos = ((FormattedHeader) header).getValuePos();
+ } else {
+ final String s = header.getValue();
+ if (s == null) {
+ throw new MalformedChallengeException("Header value is null");
+ }
+ buffer = new CharArrayBuffer(s.length());
+ buffer.append(s);
+ pos = 0;
+ }
+ while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) {
+ pos++;
+ }
+ final int beginIndex = pos;
+ while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) {
+ pos++;
+ }
+ final int endIndex = pos;
+ final String s = buffer.substring(beginIndex, endIndex);
+ map.put(s.toLowerCase(Locale.ENGLISH), header);
+ }
+ return map;
+ }
+
+ /**
+ * Returns default list of auth scheme names in their order of preference.
+ *
+ * @return list of auth scheme names
+ */
+ protected List getAuthPreferences() {
+ return DEFAULT_SCHEME_PRIORITY;
+ }
+
+ /**
+ * Returns default list of auth scheme names in their order of preference
+ * based on the HTTP response and the current execution context.
+ *
+ * @param response HTTP response.
+ * @param context HTTP execution context.
+ *
+ * @since 4.1
+ */
+ protected List getAuthPreferences(
+ final HttpResponse response,
+ final HttpContext context) {
+ return getAuthPreferences();
+ }
+
+ public AuthScheme selectScheme(
+ final Map challenges,
+ final HttpResponse response,
+ final HttpContext context) throws AuthenticationException {
+
+ final AuthSchemeRegistry registry = (AuthSchemeRegistry) context.getAttribute(
+ ClientContext.AUTHSCHEME_REGISTRY);
+ Asserts.notNull(registry, "AuthScheme registry");
+ Collection authPrefs = getAuthPreferences(response, context);
+ if (authPrefs == null) {
+ authPrefs = DEFAULT_SCHEME_PRIORITY;
+ }
+
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Authentication schemes in the order of preference: "
+ + authPrefs);
+ }
+
+ AuthScheme authScheme = null;
+ for (final String id: authPrefs) {
+ final Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
+
+ if (challenge != null) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug(id + " authentication scheme selected");
+ }
+ try {
+ authScheme = registry.getAuthScheme(id, response.getParams());
+ break;
+ } catch (final IllegalStateException e) {
+ if (this.log.isWarnEnabled()) {
+ this.log.warn("Authentication scheme " + id + " not supported");
+ // Try again
+ }
+ }
+ } else {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Challenge for " + id + " authentication scheme not available");
+ // Try again
+ }
+ }
+ }
+ if (authScheme == null) {
+ // If none selected, something is wrong
+ throw new AuthenticationException(
+ "Unable to respond to any of these challenges: "
+ + challenges);
+ }
+ return authScheme;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AbstractHttpClient.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AbstractHttpClient.java
new file mode 100644
index 000000000..f862c9886
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AbstractHttpClient.java
@@ -0,0 +1,990 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.io.IOException;
+import java.lang.reflect.UndeclaredThrowableException;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.ConnectionReuseStrategy;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpRequestInterceptor;
+import ch.boye.httpclientandroidlib.HttpResponseInterceptor;
+import ch.boye.httpclientandroidlib.annotation.GuardedBy;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.auth.AuthSchemeRegistry;
+import ch.boye.httpclientandroidlib.client.AuthenticationHandler;
+import ch.boye.httpclientandroidlib.client.AuthenticationStrategy;
+import ch.boye.httpclientandroidlib.client.BackoffManager;
+import ch.boye.httpclientandroidlib.client.ClientProtocolException;
+import ch.boye.httpclientandroidlib.client.ConnectionBackoffStrategy;
+import ch.boye.httpclientandroidlib.client.CookieStore;
+import ch.boye.httpclientandroidlib.client.CredentialsProvider;
+import ch.boye.httpclientandroidlib.client.HttpRequestRetryHandler;
+import ch.boye.httpclientandroidlib.client.RedirectHandler;
+import ch.boye.httpclientandroidlib.client.RedirectStrategy;
+import ch.boye.httpclientandroidlib.client.RequestDirector;
+import ch.boye.httpclientandroidlib.client.UserTokenHandler;
+import ch.boye.httpclientandroidlib.client.config.RequestConfig;
+import ch.boye.httpclientandroidlib.client.methods.CloseableHttpResponse;
+import ch.boye.httpclientandroidlib.client.params.AuthPolicy;
+import ch.boye.httpclientandroidlib.client.params.ClientPNames;
+import ch.boye.httpclientandroidlib.client.params.CookiePolicy;
+import ch.boye.httpclientandroidlib.client.params.HttpClientParamConfig;
+import ch.boye.httpclientandroidlib.client.protocol.ClientContext;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionManagerFactory;
+import ch.boye.httpclientandroidlib.conn.ConnectionKeepAliveStrategy;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoutePlanner;
+import ch.boye.httpclientandroidlib.conn.scheme.SchemeRegistry;
+import ch.boye.httpclientandroidlib.cookie.CookieSpecRegistry;
+import ch.boye.httpclientandroidlib.impl.DefaultConnectionReuseStrategy;
+import ch.boye.httpclientandroidlib.impl.auth.BasicSchemeFactory;
+import ch.boye.httpclientandroidlib.impl.auth.DigestSchemeFactory;
+/* KerberosSchemeFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.impl.auth.NTLMSchemeFactory;
+/* SPNegoSchemeFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.impl.conn.BasicClientConnectionManager;
+import ch.boye.httpclientandroidlib.impl.conn.DefaultHttpRoutePlanner;
+import ch.boye.httpclientandroidlib.impl.conn.SchemeRegistryFactory;
+import ch.boye.httpclientandroidlib.impl.cookie.BestMatchSpecFactory;
+import ch.boye.httpclientandroidlib.impl.cookie.BrowserCompatSpecFactory;
+import ch.boye.httpclientandroidlib.impl.cookie.IgnoreSpecFactory;
+import ch.boye.httpclientandroidlib.impl.cookie.NetscapeDraftSpecFactory;
+import ch.boye.httpclientandroidlib.impl.cookie.RFC2109SpecFactory;
+import ch.boye.httpclientandroidlib.impl.cookie.RFC2965SpecFactory;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.BasicHttpContext;
+import ch.boye.httpclientandroidlib.protocol.BasicHttpProcessor;
+import ch.boye.httpclientandroidlib.protocol.DefaultedHttpContext;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.protocol.HttpProcessor;
+import ch.boye.httpclientandroidlib.protocol.HttpRequestExecutor;
+import ch.boye.httpclientandroidlib.protocol.ImmutableHttpProcessor;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Base class for {@link ch.boye.httpclientandroidlib.client.HttpClient} implementations.
+ * This class acts as a facade to a number of special purpose handler or
+ * strategy implementations responsible for handling of a particular aspect
+ * of the HTTP protocol such as redirect or authentication handling or
+ * making decision about connection persistence and keep alive duration.
+ * This enables the users to selectively replace default implementation
+ * of those aspects with custom, application specific ones. This class
+ * also provides factory methods to instantiate those objects:
+ *
+ *
{@link HttpRequestExecutor}
object used to transmit messages
+ * over HTTP connections. The {@link #createRequestExecutor()} must be
+ * implemented by concrete super classes to instantiate this object.
+ *
{@link BasicHttpProcessor}
object to manage a list of protocol
+ * interceptors and apply cross-cutting protocol logic to all incoming
+ * and outgoing HTTP messages. The {@link #createHttpProcessor()} must be
+ * implemented by concrete super classes to instantiate this object.
+ *
{@link HttpRequestRetryHandler}
object used to decide whether
+ * or not a failed HTTP request is safe to retry automatically.
+ * The {@link #createHttpRequestRetryHandler()} must be
+ * implemented by concrete super classes to instantiate this object.
+ *
{@link ClientConnectionManager}
object used to manage
+ * persistent HTTP connections.
+ *
{@link ConnectionReuseStrategy}
object used to decide whether
+ * or not a HTTP connection can be kept alive and re-used for subsequent
+ * HTTP requests. The {@link #createConnectionReuseStrategy()} must be
+ * implemented by concrete super classes to instantiate this object.
+ *
{@link ConnectionKeepAliveStrategy}
object used to decide how
+ * long a persistent HTTP connection can be kept alive.
+ * The {@link #createConnectionKeepAliveStrategy()} must be
+ * implemented by concrete super classes to instantiate this object.
+ *
{@link CookieSpecRegistry}
object used to maintain a list of
+ * supported cookie specifications.
+ * The {@link #createCookieSpecRegistry()} must be implemented by concrete
+ * super classes to instantiate this object.
+ *
{@link CookieStore}
object used to maintain a collection of
+ * cookies. The {@link #createCookieStore()} must be implemented by
+ * concrete super classes to instantiate this object.
+ *
{@link AuthSchemeRegistry}
object used to maintain a list of
+ * supported authentication schemes.
+ * The {@link #createAuthSchemeRegistry()} must be implemented by concrete
+ * super classes to instantiate this object.
+ *
{@link CredentialsProvider}
object used to maintain
+ * a collection user credentials. The {@link #createCredentialsProvider()}
+ * must be implemented by concrete super classes to instantiate
+ * this object.
+ *
{@link AuthenticationStrategy}
object used to authenticate
+ * against the target host.
+ * The {@link #createTargetAuthenticationStrategy()} must be implemented
+ * by concrete super classes to instantiate this object.
+ *
{@link AuthenticationStrategy}
object used to authenticate
+ * against the proxy host.
+ * The {@link #createProxyAuthenticationStrategy()} must be implemented
+ * by concrete super classes to instantiate this object.
+ *
{@link HttpRoutePlanner}
object used to calculate a route
+ * for establishing a connection to the target host. The route
+ * may involve multiple intermediate hops.
+ * The {@link #createHttpRoutePlanner()} must be implemented
+ * by concrete super classes to instantiate this object.
+ *
{@link RedirectStrategy}
object used to determine if an HTTP
+ * request should be redirected to a new location in response to an HTTP
+ * response received from the target server.
+ *
{@link UserTokenHandler}
object used to determine if the
+ * execution context is user identity specific.
+ * The {@link #createUserTokenHandler()} must be implemented by
+ * concrete super classes to instantiate this object.
+ *
+ *
+ * This class also maintains a list of protocol interceptors intended
+ * for processing outgoing requests and incoming responses and provides
+ * methods for managing those interceptors. New protocol interceptors can be
+ * introduced to the protocol processor chain or removed from it if needed.
+ * Internally protocol interceptors are stored in a simple
+ * {@link java.util.ArrayList}. They are executed in the same natural order
+ * as they are added to the list.
+ *
+ * AbstractHttpClient is thread safe. It is recommended that the same
+ * instance of this class is reused for multiple request executions.
+ * When an instance of DefaultHttpClient is no longer needed and is about
+ * to go out of scope the connection manager associated with it must be
+ * shut down by calling {@link ClientConnectionManager#shutdown()}!
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link HttpClientBuilder}.
+ */
+@ThreadSafe
+@Deprecated
+public abstract class AbstractHttpClient extends CloseableHttpClient {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ /** The parameters. */
+ @GuardedBy("this")
+ private HttpParams defaultParams;
+
+ /** The request executor. */
+ @GuardedBy("this")
+ private HttpRequestExecutor requestExec;
+
+ /** The connection manager. */
+ @GuardedBy("this")
+ private ClientConnectionManager connManager;
+
+ /** The connection re-use strategy. */
+ @GuardedBy("this")
+ private ConnectionReuseStrategy reuseStrategy;
+
+ /** The connection keep-alive strategy. */
+ @GuardedBy("this")
+ private ConnectionKeepAliveStrategy keepAliveStrategy;
+
+ /** The cookie spec registry. */
+ @GuardedBy("this")
+ private CookieSpecRegistry supportedCookieSpecs;
+
+ /** The authentication scheme registry. */
+ @GuardedBy("this")
+ private AuthSchemeRegistry supportedAuthSchemes;
+
+ /** The HTTP protocol processor and its immutable copy. */
+ @GuardedBy("this")
+ private BasicHttpProcessor mutableProcessor;
+
+ @GuardedBy("this")
+ private ImmutableHttpProcessor protocolProcessor;
+
+ /** The request retry handler. */
+ @GuardedBy("this")
+ private HttpRequestRetryHandler retryHandler;
+
+ /** The redirect handler. */
+ @GuardedBy("this")
+ private RedirectStrategy redirectStrategy;
+
+ /** The target authentication handler. */
+ @GuardedBy("this")
+ private AuthenticationStrategy targetAuthStrategy;
+
+ /** The proxy authentication handler. */
+ @GuardedBy("this")
+ private AuthenticationStrategy proxyAuthStrategy;
+
+ /** The cookie store. */
+ @GuardedBy("this")
+ private CookieStore cookieStore;
+
+ /** The credentials provider. */
+ @GuardedBy("this")
+ private CredentialsProvider credsProvider;
+
+ /** The route planner. */
+ @GuardedBy("this")
+ private HttpRoutePlanner routePlanner;
+
+ /** The user token handler. */
+ @GuardedBy("this")
+ private UserTokenHandler userTokenHandler;
+
+ /** The connection backoff strategy. */
+ @GuardedBy("this")
+ private ConnectionBackoffStrategy connectionBackoffStrategy;
+
+ /** The backoff manager. */
+ @GuardedBy("this")
+ private BackoffManager backoffManager;
+
+ /**
+ * Creates a new HTTP client.
+ *
+ * @param conman the connection manager
+ * @param params the parameters
+ */
+ protected AbstractHttpClient(
+ final ClientConnectionManager conman,
+ final HttpParams params) {
+ super();
+ defaultParams = params;
+ connManager = conman;
+ } // constructor
+
+
+ protected abstract HttpParams createHttpParams();
+
+
+ protected abstract BasicHttpProcessor createHttpProcessor();
+
+
+ protected HttpContext createHttpContext() {
+ final HttpContext context = new BasicHttpContext();
+ context.setAttribute(
+ ClientContext.SCHEME_REGISTRY,
+ getConnectionManager().getSchemeRegistry());
+ context.setAttribute(
+ ClientContext.AUTHSCHEME_REGISTRY,
+ getAuthSchemes());
+ context.setAttribute(
+ ClientContext.COOKIESPEC_REGISTRY,
+ getCookieSpecs());
+ context.setAttribute(
+ ClientContext.COOKIE_STORE,
+ getCookieStore());
+ context.setAttribute(
+ ClientContext.CREDS_PROVIDER,
+ getCredentialsProvider());
+ return context;
+ }
+
+
+ protected ClientConnectionManager createClientConnectionManager() {
+ final SchemeRegistry registry = SchemeRegistryFactory.createDefault();
+
+ ClientConnectionManager connManager = null;
+ final HttpParams params = getParams();
+
+ ClientConnectionManagerFactory factory = null;
+
+ final String className = (String) params.getParameter(
+ ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME);
+ if (className != null) {
+ try {
+ final Class> clazz = Class.forName(className);
+ factory = (ClientConnectionManagerFactory) clazz.newInstance();
+ } catch (final ClassNotFoundException ex) {
+ throw new IllegalStateException("Invalid class name: " + className);
+ } catch (final IllegalAccessException ex) {
+ throw new IllegalAccessError(ex.getMessage());
+ } catch (final InstantiationException ex) {
+ throw new InstantiationError(ex.getMessage());
+ }
+ }
+ if (factory != null) {
+ connManager = factory.newInstance(params, registry);
+ } else {
+ connManager = new BasicClientConnectionManager(registry);
+ }
+
+ return connManager;
+ }
+
+
+ protected AuthSchemeRegistry createAuthSchemeRegistry() {
+ final AuthSchemeRegistry registry = new AuthSchemeRegistry();
+ registry.register(
+ AuthPolicy.BASIC,
+ new BasicSchemeFactory());
+ registry.register(
+ AuthPolicy.DIGEST,
+ new DigestSchemeFactory());
+ registry.register(
+ AuthPolicy.NTLM,
+ new NTLMSchemeFactory());
+ /* SPNegoSchemeFactory removed by HttpClient for Android script. */
+ /* KerberosSchemeFactory removed by HttpClient for Android script. */
+ return registry;
+ }
+
+
+ protected CookieSpecRegistry createCookieSpecRegistry() {
+ final CookieSpecRegistry registry = new CookieSpecRegistry();
+ registry.register(
+ CookiePolicy.BEST_MATCH,
+ new BestMatchSpecFactory());
+ registry.register(
+ CookiePolicy.BROWSER_COMPATIBILITY,
+ new BrowserCompatSpecFactory());
+ registry.register(
+ CookiePolicy.NETSCAPE,
+ new NetscapeDraftSpecFactory());
+ registry.register(
+ CookiePolicy.RFC_2109,
+ new RFC2109SpecFactory());
+ registry.register(
+ CookiePolicy.RFC_2965,
+ new RFC2965SpecFactory());
+ registry.register(
+ CookiePolicy.IGNORE_COOKIES,
+ new IgnoreSpecFactory());
+ return registry;
+ }
+
+ protected HttpRequestExecutor createRequestExecutor() {
+ return new HttpRequestExecutor();
+ }
+
+ protected ConnectionReuseStrategy createConnectionReuseStrategy() {
+ return new DefaultConnectionReuseStrategy();
+ }
+
+ protected ConnectionKeepAliveStrategy createConnectionKeepAliveStrategy() {
+ return new DefaultConnectionKeepAliveStrategy();
+ }
+
+ protected HttpRequestRetryHandler createHttpRequestRetryHandler() {
+ return new DefaultHttpRequestRetryHandler();
+ }
+
+ /**
+ * @deprecated (4.1) do not use
+ */
+ @Deprecated
+ protected RedirectHandler createRedirectHandler() {
+ return new DefaultRedirectHandler();
+ }
+
+ protected AuthenticationStrategy createTargetAuthenticationStrategy() {
+ return new TargetAuthenticationStrategy();
+ }
+
+ /**
+ * @deprecated (4.2) do not use
+ */
+ @Deprecated
+ protected AuthenticationHandler createTargetAuthenticationHandler() {
+ return new DefaultTargetAuthenticationHandler();
+ }
+
+ protected AuthenticationStrategy createProxyAuthenticationStrategy() {
+ return new ProxyAuthenticationStrategy();
+ }
+
+ /**
+ * @deprecated (4.2) do not use
+ */
+ @Deprecated
+ protected AuthenticationHandler createProxyAuthenticationHandler() {
+ return new DefaultProxyAuthenticationHandler();
+ }
+
+ protected CookieStore createCookieStore() {
+ return new BasicCookieStore();
+ }
+
+ protected CredentialsProvider createCredentialsProvider() {
+ return new BasicCredentialsProvider();
+ }
+
+ protected HttpRoutePlanner createHttpRoutePlanner() {
+ return new DefaultHttpRoutePlanner(getConnectionManager().getSchemeRegistry());
+ }
+
+ protected UserTokenHandler createUserTokenHandler() {
+ return new DefaultUserTokenHandler();
+ }
+
+ // non-javadoc, see interface HttpClient
+ public synchronized final HttpParams getParams() {
+ if (defaultParams == null) {
+ defaultParams = createHttpParams();
+ }
+ return defaultParams;
+ }
+
+ /**
+ * Replaces the parameters.
+ * The implementation here does not update parameters of dependent objects.
+ *
+ * @param params the new default parameters
+ */
+ public synchronized void setParams(final HttpParams params) {
+ defaultParams = params;
+ }
+
+
+ public synchronized final ClientConnectionManager getConnectionManager() {
+ if (connManager == null) {
+ connManager = createClientConnectionManager();
+ }
+ return connManager;
+ }
+
+
+ public synchronized final HttpRequestExecutor getRequestExecutor() {
+ if (requestExec == null) {
+ requestExec = createRequestExecutor();
+ }
+ return requestExec;
+ }
+
+
+ public synchronized final AuthSchemeRegistry getAuthSchemes() {
+ if (supportedAuthSchemes == null) {
+ supportedAuthSchemes = createAuthSchemeRegistry();
+ }
+ return supportedAuthSchemes;
+ }
+
+ public synchronized void setAuthSchemes(final AuthSchemeRegistry registry) {
+ supportedAuthSchemes = registry;
+ }
+
+ public synchronized final ConnectionBackoffStrategy getConnectionBackoffStrategy() {
+ return connectionBackoffStrategy;
+ }
+
+ public synchronized void setConnectionBackoffStrategy(final ConnectionBackoffStrategy strategy) {
+ connectionBackoffStrategy = strategy;
+ }
+
+ public synchronized final CookieSpecRegistry getCookieSpecs() {
+ if (supportedCookieSpecs == null) {
+ supportedCookieSpecs = createCookieSpecRegistry();
+ }
+ return supportedCookieSpecs;
+ }
+
+ public synchronized final BackoffManager getBackoffManager() {
+ return backoffManager;
+ }
+
+ public synchronized void setBackoffManager(final BackoffManager manager) {
+ backoffManager = manager;
+ }
+
+ public synchronized void setCookieSpecs(final CookieSpecRegistry registry) {
+ supportedCookieSpecs = registry;
+ }
+
+ public synchronized final ConnectionReuseStrategy getConnectionReuseStrategy() {
+ if (reuseStrategy == null) {
+ reuseStrategy = createConnectionReuseStrategy();
+ }
+ return reuseStrategy;
+ }
+
+
+ public synchronized void setReuseStrategy(final ConnectionReuseStrategy strategy) {
+ this.reuseStrategy = strategy;
+ }
+
+
+ public synchronized final ConnectionKeepAliveStrategy getConnectionKeepAliveStrategy() {
+ if (keepAliveStrategy == null) {
+ keepAliveStrategy = createConnectionKeepAliveStrategy();
+ }
+ return keepAliveStrategy;
+ }
+
+
+ public synchronized void setKeepAliveStrategy(final ConnectionKeepAliveStrategy strategy) {
+ this.keepAliveStrategy = strategy;
+ }
+
+
+ public synchronized final HttpRequestRetryHandler getHttpRequestRetryHandler() {
+ if (retryHandler == null) {
+ retryHandler = createHttpRequestRetryHandler();
+ }
+ return retryHandler;
+ }
+
+ public synchronized void setHttpRequestRetryHandler(final HttpRequestRetryHandler handler) {
+ this.retryHandler = handler;
+ }
+
+ /**
+ * @deprecated (4.1) do not use
+ */
+ @Deprecated
+ public synchronized final RedirectHandler getRedirectHandler() {
+ return createRedirectHandler();
+ }
+
+ /**
+ * @deprecated (4.1) do not use
+ */
+ @Deprecated
+ public synchronized void setRedirectHandler(final RedirectHandler handler) {
+ this.redirectStrategy = new DefaultRedirectStrategyAdaptor(handler);
+ }
+
+ /**
+ * @since 4.1
+ */
+ public synchronized final RedirectStrategy getRedirectStrategy() {
+ if (redirectStrategy == null) {
+ redirectStrategy = new DefaultRedirectStrategy();
+ }
+ return redirectStrategy;
+ }
+
+ /**
+ * @since 4.1
+ */
+ public synchronized void setRedirectStrategy(final RedirectStrategy strategy) {
+ this.redirectStrategy = strategy;
+ }
+
+ /**
+ * @deprecated (4.2) do not use
+ */
+ @Deprecated
+ public synchronized final AuthenticationHandler getTargetAuthenticationHandler() {
+ return createTargetAuthenticationHandler();
+ }
+
+ /**
+ * @deprecated (4.2) do not use
+ */
+ @Deprecated
+ public synchronized void setTargetAuthenticationHandler(final AuthenticationHandler handler) {
+ this.targetAuthStrategy = new AuthenticationStrategyAdaptor(handler);
+ }
+
+ /**
+ * @since 4.2
+ */
+ public synchronized final AuthenticationStrategy getTargetAuthenticationStrategy() {
+ if (targetAuthStrategy == null) {
+ targetAuthStrategy = createTargetAuthenticationStrategy();
+ }
+ return targetAuthStrategy;
+ }
+
+ /**
+ * @since 4.2
+ */
+ public synchronized void setTargetAuthenticationStrategy(final AuthenticationStrategy strategy) {
+ this.targetAuthStrategy = strategy;
+ }
+
+ /**
+ * @deprecated (4.2) do not use
+ */
+ @Deprecated
+ public synchronized final AuthenticationHandler getProxyAuthenticationHandler() {
+ return createProxyAuthenticationHandler();
+ }
+
+ /**
+ * @deprecated (4.2) do not use
+ */
+ @Deprecated
+ public synchronized void setProxyAuthenticationHandler(final AuthenticationHandler handler) {
+ this.proxyAuthStrategy = new AuthenticationStrategyAdaptor(handler);
+ }
+
+ /**
+ * @since 4.2
+ */
+ public synchronized final AuthenticationStrategy getProxyAuthenticationStrategy() {
+ if (proxyAuthStrategy == null) {
+ proxyAuthStrategy = createProxyAuthenticationStrategy();
+ }
+ return proxyAuthStrategy;
+ }
+
+ /**
+ * @since 4.2
+ */
+ public synchronized void setProxyAuthenticationStrategy(final AuthenticationStrategy strategy) {
+ this.proxyAuthStrategy = strategy;
+ }
+
+ public synchronized final CookieStore getCookieStore() {
+ if (cookieStore == null) {
+ cookieStore = createCookieStore();
+ }
+ return cookieStore;
+ }
+
+ public synchronized void setCookieStore(final CookieStore cookieStore) {
+ this.cookieStore = cookieStore;
+ }
+
+ public synchronized final CredentialsProvider getCredentialsProvider() {
+ if (credsProvider == null) {
+ credsProvider = createCredentialsProvider();
+ }
+ return credsProvider;
+ }
+
+ public synchronized void setCredentialsProvider(final CredentialsProvider credsProvider) {
+ this.credsProvider = credsProvider;
+ }
+
+ public synchronized final HttpRoutePlanner getRoutePlanner() {
+ if (this.routePlanner == null) {
+ this.routePlanner = createHttpRoutePlanner();
+ }
+ return this.routePlanner;
+ }
+
+ public synchronized void setRoutePlanner(final HttpRoutePlanner routePlanner) {
+ this.routePlanner = routePlanner;
+ }
+
+ public synchronized final UserTokenHandler getUserTokenHandler() {
+ if (this.userTokenHandler == null) {
+ this.userTokenHandler = createUserTokenHandler();
+ }
+ return this.userTokenHandler;
+ }
+
+ public synchronized void setUserTokenHandler(final UserTokenHandler handler) {
+ this.userTokenHandler = handler;
+ }
+
+ protected synchronized final BasicHttpProcessor getHttpProcessor() {
+ if (mutableProcessor == null) {
+ mutableProcessor = createHttpProcessor();
+ }
+ return mutableProcessor;
+ }
+
+ private synchronized HttpProcessor getProtocolProcessor() {
+ if (protocolProcessor == null) {
+ // Get mutable HTTP processor
+ final BasicHttpProcessor proc = getHttpProcessor();
+ // and create an immutable copy of it
+ final int reqc = proc.getRequestInterceptorCount();
+ final HttpRequestInterceptor[] reqinterceptors = new HttpRequestInterceptor[reqc];
+ for (int i = 0; i < reqc; i++) {
+ reqinterceptors[i] = proc.getRequestInterceptor(i);
+ }
+ final int resc = proc.getResponseInterceptorCount();
+ final HttpResponseInterceptor[] resinterceptors = new HttpResponseInterceptor[resc];
+ for (int i = 0; i < resc; i++) {
+ resinterceptors[i] = proc.getResponseInterceptor(i);
+ }
+ protocolProcessor = new ImmutableHttpProcessor(reqinterceptors, resinterceptors);
+ }
+ return protocolProcessor;
+ }
+
+ public synchronized int getResponseInterceptorCount() {
+ return getHttpProcessor().getResponseInterceptorCount();
+ }
+
+ public synchronized HttpResponseInterceptor getResponseInterceptor(final int index) {
+ return getHttpProcessor().getResponseInterceptor(index);
+ }
+
+ public synchronized HttpRequestInterceptor getRequestInterceptor(final int index) {
+ return getHttpProcessor().getRequestInterceptor(index);
+ }
+
+ public synchronized int getRequestInterceptorCount() {
+ return getHttpProcessor().getRequestInterceptorCount();
+ }
+
+ public synchronized void addResponseInterceptor(final HttpResponseInterceptor itcp) {
+ getHttpProcessor().addInterceptor(itcp);
+ protocolProcessor = null;
+ }
+
+ public synchronized void addResponseInterceptor(final HttpResponseInterceptor itcp, final int index) {
+ getHttpProcessor().addInterceptor(itcp, index);
+ protocolProcessor = null;
+ }
+
+ public synchronized void clearResponseInterceptors() {
+ getHttpProcessor().clearResponseInterceptors();
+ protocolProcessor = null;
+ }
+
+ public synchronized void removeResponseInterceptorByClass(final Class extends HttpResponseInterceptor> clazz) {
+ getHttpProcessor().removeResponseInterceptorByClass(clazz);
+ protocolProcessor = null;
+ }
+
+ public synchronized void addRequestInterceptor(final HttpRequestInterceptor itcp) {
+ getHttpProcessor().addInterceptor(itcp);
+ protocolProcessor = null;
+ }
+
+ public synchronized void addRequestInterceptor(final HttpRequestInterceptor itcp, final int index) {
+ getHttpProcessor().addInterceptor(itcp, index);
+ protocolProcessor = null;
+ }
+
+ public synchronized void clearRequestInterceptors() {
+ getHttpProcessor().clearRequestInterceptors();
+ protocolProcessor = null;
+ }
+
+ public synchronized void removeRequestInterceptorByClass(final Class extends HttpRequestInterceptor> clazz) {
+ getHttpProcessor().removeRequestInterceptorByClass(clazz);
+ protocolProcessor = null;
+ }
+
+ @Override
+ protected final CloseableHttpResponse doExecute(final HttpHost target, final HttpRequest request,
+ final HttpContext context)
+ throws IOException, ClientProtocolException {
+
+ Args.notNull(request, "HTTP request");
+ // a null target may be acceptable, this depends on the route planner
+ // a null context is acceptable, default context created below
+
+ HttpContext execContext = null;
+ RequestDirector director = null;
+ HttpRoutePlanner routePlanner = null;
+ ConnectionBackoffStrategy connectionBackoffStrategy = null;
+ BackoffManager backoffManager = null;
+
+ // Initialize the request execution context making copies of
+ // all shared objects that are potentially threading unsafe.
+ synchronized (this) {
+
+ final HttpContext defaultContext = createHttpContext();
+ if (context == null) {
+ execContext = defaultContext;
+ } else {
+ execContext = new DefaultedHttpContext(context, defaultContext);
+ }
+ final HttpParams params = determineParams(request);
+ final RequestConfig config = HttpClientParamConfig.getRequestConfig(params);
+ execContext.setAttribute(ClientContext.REQUEST_CONFIG, config);
+
+ // Create a director for this request
+ director = createClientRequestDirector(
+ getRequestExecutor(),
+ getConnectionManager(),
+ getConnectionReuseStrategy(),
+ getConnectionKeepAliveStrategy(),
+ getRoutePlanner(),
+ getProtocolProcessor(),
+ getHttpRequestRetryHandler(),
+ getRedirectStrategy(),
+ getTargetAuthenticationStrategy(),
+ getProxyAuthenticationStrategy(),
+ getUserTokenHandler(),
+ params);
+ routePlanner = getRoutePlanner();
+ connectionBackoffStrategy = getConnectionBackoffStrategy();
+ backoffManager = getBackoffManager();
+ }
+
+ try {
+ if (connectionBackoffStrategy != null && backoffManager != null) {
+ final HttpHost targetForRoute = (target != null) ? target
+ : (HttpHost) determineParams(request).getParameter(
+ ClientPNames.DEFAULT_HOST);
+ final HttpRoute route = routePlanner.determineRoute(targetForRoute, request, execContext);
+
+ final CloseableHttpResponse out;
+ try {
+ out = CloseableHttpResponseProxy.newProxy(
+ director.execute(target, request, execContext));
+ } catch (final RuntimeException re) {
+ if (connectionBackoffStrategy.shouldBackoff(re)) {
+ backoffManager.backOff(route);
+ }
+ throw re;
+ } catch (final Exception e) {
+ if (connectionBackoffStrategy.shouldBackoff(e)) {
+ backoffManager.backOff(route);
+ }
+ if (e instanceof HttpException) {
+ throw (HttpException)e;
+ }
+ if (e instanceof IOException) {
+ throw (IOException)e;
+ }
+ throw new UndeclaredThrowableException(e);
+ }
+ if (connectionBackoffStrategy.shouldBackoff(out)) {
+ backoffManager.backOff(route);
+ } else {
+ backoffManager.probe(route);
+ }
+ return out;
+ } else {
+ return CloseableHttpResponseProxy.newProxy(
+ director.execute(target, request, execContext));
+ }
+ } catch(final HttpException httpException) {
+ throw new ClientProtocolException(httpException);
+ }
+ }
+
+ /**
+ * @deprecated (4.1) do not use
+ */
+ @Deprecated
+ protected RequestDirector createClientRequestDirector(
+ final HttpRequestExecutor requestExec,
+ final ClientConnectionManager conman,
+ final ConnectionReuseStrategy reustrat,
+ final ConnectionKeepAliveStrategy kastrat,
+ final HttpRoutePlanner rouplan,
+ final HttpProcessor httpProcessor,
+ final HttpRequestRetryHandler retryHandler,
+ final RedirectHandler redirectHandler,
+ final AuthenticationHandler targetAuthHandler,
+ final AuthenticationHandler proxyAuthHandler,
+ final UserTokenHandler userTokenHandler,
+ final HttpParams params) {
+ return new DefaultRequestDirector(
+ requestExec,
+ conman,
+ reustrat,
+ kastrat,
+ rouplan,
+ httpProcessor,
+ retryHandler,
+ redirectHandler,
+ targetAuthHandler,
+ proxyAuthHandler,
+ userTokenHandler,
+ params);
+ }
+
+ /**
+ * @deprecated (4.2) do not use
+ */
+ @Deprecated
+ protected RequestDirector createClientRequestDirector(
+ final HttpRequestExecutor requestExec,
+ final ClientConnectionManager conman,
+ final ConnectionReuseStrategy reustrat,
+ final ConnectionKeepAliveStrategy kastrat,
+ final HttpRoutePlanner rouplan,
+ final HttpProcessor httpProcessor,
+ final HttpRequestRetryHandler retryHandler,
+ final RedirectStrategy redirectStrategy,
+ final AuthenticationHandler targetAuthHandler,
+ final AuthenticationHandler proxyAuthHandler,
+ final UserTokenHandler userTokenHandler,
+ final HttpParams params) {
+ return new DefaultRequestDirector(
+ log,
+ requestExec,
+ conman,
+ reustrat,
+ kastrat,
+ rouplan,
+ httpProcessor,
+ retryHandler,
+ redirectStrategy,
+ targetAuthHandler,
+ proxyAuthHandler,
+ userTokenHandler,
+ params);
+ }
+
+
+ /**
+ * @since 4.2
+ */
+ protected RequestDirector createClientRequestDirector(
+ final HttpRequestExecutor requestExec,
+ final ClientConnectionManager conman,
+ final ConnectionReuseStrategy reustrat,
+ final ConnectionKeepAliveStrategy kastrat,
+ final HttpRoutePlanner rouplan,
+ final HttpProcessor httpProcessor,
+ final HttpRequestRetryHandler retryHandler,
+ final RedirectStrategy redirectStrategy,
+ final AuthenticationStrategy targetAuthStrategy,
+ final AuthenticationStrategy proxyAuthStrategy,
+ final UserTokenHandler userTokenHandler,
+ final HttpParams params) {
+ return new DefaultRequestDirector(
+ log,
+ requestExec,
+ conman,
+ reustrat,
+ kastrat,
+ rouplan,
+ httpProcessor,
+ retryHandler,
+ redirectStrategy,
+ targetAuthStrategy,
+ proxyAuthStrategy,
+ userTokenHandler,
+ params);
+ }
+
+ /**
+ * Obtains parameters for executing a request.
+ * The default implementation in this class creates a new
+ * {@link ClientParamsStack} from the request parameters
+ * and the client parameters.
+ *
+ * This method is called by the default implementation of
+ * {@link #execute(HttpHost,HttpRequest,HttpContext)}
+ * to obtain the parameters for the
+ * {@link DefaultRequestDirector}.
+ *
+ * @param req the request that will be executed
+ *
+ * @return the parameters to use
+ */
+ protected HttpParams determineParams(final HttpRequest req) {
+ return new ClientParamsStack
+ (null, getParams(), req.getParams(), null);
+ }
+
+
+ public void close() {
+ getConnectionManager().shutdown();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AuthenticationStrategyAdaptor.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AuthenticationStrategyAdaptor.java
new file mode 100644
index 000000000..a65ce7e95
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AuthenticationStrategyAdaptor.java
@@ -0,0 +1,172 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.util.LinkedList;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Queue;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.auth.AuthOption;
+import ch.boye.httpclientandroidlib.auth.AuthScheme;
+import ch.boye.httpclientandroidlib.auth.AuthScope;
+import ch.boye.httpclientandroidlib.auth.AuthenticationException;
+import ch.boye.httpclientandroidlib.auth.Credentials;
+import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
+import ch.boye.httpclientandroidlib.client.AuthCache;
+import ch.boye.httpclientandroidlib.client.AuthenticationHandler;
+import ch.boye.httpclientandroidlib.client.AuthenticationStrategy;
+import ch.boye.httpclientandroidlib.client.CredentialsProvider;
+import ch.boye.httpclientandroidlib.client.params.AuthPolicy;
+import ch.boye.httpclientandroidlib.client.protocol.ClientContext;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * @deprecated (4.2) do not use
+ */
+@Immutable
+@Deprecated
+class AuthenticationStrategyAdaptor implements AuthenticationStrategy {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ private final AuthenticationHandler handler;
+
+ public AuthenticationStrategyAdaptor(final AuthenticationHandler handler) {
+ super();
+ this.handler = handler;
+ }
+
+ public boolean isAuthenticationRequested(
+ final HttpHost authhost,
+ final HttpResponse response,
+ final HttpContext context) {
+ return this.handler.isAuthenticationRequested(response, context);
+ }
+
+ public Map getChallenges(
+ final HttpHost authhost,
+ final HttpResponse response,
+ final HttpContext context) throws MalformedChallengeException {
+ return this.handler.getChallenges(response, context);
+ }
+
+ public Queue select(
+ final Map challenges,
+ final HttpHost authhost,
+ final HttpResponse response,
+ final HttpContext context) throws MalformedChallengeException {
+ Args.notNull(challenges, "Map of auth challenges");
+ Args.notNull(authhost, "Host");
+ Args.notNull(response, "HTTP response");
+ Args.notNull(context, "HTTP context");
+
+ final Queue options = new LinkedList();
+ final CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
+ ClientContext.CREDS_PROVIDER);
+ if (credsProvider == null) {
+ this.log.debug("Credentials provider not set in the context");
+ return options;
+ }
+
+ final AuthScheme authScheme;
+ try {
+ authScheme = this.handler.selectScheme(challenges, response, context);
+ } catch (final AuthenticationException ex) {
+ if (this.log.isWarnEnabled()) {
+ this.log.warn(ex.getMessage(), ex);
+ }
+ return options;
+ }
+ final String id = authScheme.getSchemeName();
+ final Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
+ authScheme.processChallenge(challenge);
+
+ final AuthScope authScope = new AuthScope(
+ authhost.getHostName(),
+ authhost.getPort(),
+ authScheme.getRealm(),
+ authScheme.getSchemeName());
+
+ final Credentials credentials = credsProvider.getCredentials(authScope);
+ if (credentials != null) {
+ options.add(new AuthOption(authScheme, credentials));
+ }
+ return options;
+ }
+
+ public void authSucceeded(
+ final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
+ AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);
+ if (isCachable(authScheme)) {
+ if (authCache == null) {
+ authCache = new BasicAuthCache();
+ context.setAttribute(ClientContext.AUTH_CACHE, authCache);
+ }
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Caching '" + authScheme.getSchemeName() +
+ "' auth scheme for " + authhost);
+ }
+ authCache.put(authhost, authScheme);
+ }
+ }
+
+ public void authFailed(
+ final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
+ final AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);
+ if (authCache == null) {
+ return;
+ }
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Removing from cache '" + authScheme.getSchemeName() +
+ "' auth scheme for " + authhost);
+ }
+ authCache.remove(authhost);
+ }
+
+ private boolean isCachable(final AuthScheme authScheme) {
+ if (authScheme == null || !authScheme.isComplete()) {
+ return false;
+ }
+ final String schemeName = authScheme.getSchemeName();
+ return schemeName.equalsIgnoreCase(AuthPolicy.BASIC) ||
+ schemeName.equalsIgnoreCase(AuthPolicy.DIGEST);
+ }
+
+ public AuthenticationHandler getHandler() {
+ return this.handler;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AuthenticationStrategyImpl.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AuthenticationStrategyImpl.java
new file mode 100644
index 000000000..38b7df6d2
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AuthenticationStrategyImpl.java
@@ -0,0 +1,245 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Queue;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.FormattedHeader;
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.auth.AuthOption;
+import ch.boye.httpclientandroidlib.auth.AuthScheme;
+import ch.boye.httpclientandroidlib.auth.AuthSchemeProvider;
+import ch.boye.httpclientandroidlib.auth.AuthScope;
+import ch.boye.httpclientandroidlib.auth.Credentials;
+import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
+import ch.boye.httpclientandroidlib.client.AuthCache;
+import ch.boye.httpclientandroidlib.client.AuthenticationStrategy;
+import ch.boye.httpclientandroidlib.client.CredentialsProvider;
+import ch.boye.httpclientandroidlib.client.config.AuthSchemes;
+import ch.boye.httpclientandroidlib.client.config.RequestConfig;
+import ch.boye.httpclientandroidlib.client.protocol.HttpClientContext;
+import ch.boye.httpclientandroidlib.config.Lookup;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
+
+@Immutable
+abstract class AuthenticationStrategyImpl implements AuthenticationStrategy {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ private static final List DEFAULT_SCHEME_PRIORITY =
+ Collections.unmodifiableList(Arrays.asList(AuthSchemes.SPNEGO,
+ AuthSchemes.KERBEROS,
+ AuthSchemes.NTLM,
+ AuthSchemes.DIGEST,
+ AuthSchemes.BASIC));
+
+ private final int challengeCode;
+ private final String headerName;
+
+ AuthenticationStrategyImpl(final int challengeCode, final String headerName) {
+ super();
+ this.challengeCode = challengeCode;
+ this.headerName = headerName;
+ }
+
+ public boolean isAuthenticationRequested(
+ final HttpHost authhost,
+ final HttpResponse response,
+ final HttpContext context) {
+ Args.notNull(response, "HTTP response");
+ final int status = response.getStatusLine().getStatusCode();
+ return status == this.challengeCode;
+ }
+
+ public Map getChallenges(
+ final HttpHost authhost,
+ final HttpResponse response,
+ final HttpContext context) throws MalformedChallengeException {
+ Args.notNull(response, "HTTP response");
+ final Header[] headers = response.getHeaders(this.headerName);
+ final Map map = new HashMap(headers.length);
+ for (final Header header : headers) {
+ final CharArrayBuffer buffer;
+ int pos;
+ if (header instanceof FormattedHeader) {
+ buffer = ((FormattedHeader) header).getBuffer();
+ pos = ((FormattedHeader) header).getValuePos();
+ } else {
+ final String s = header.getValue();
+ if (s == null) {
+ throw new MalformedChallengeException("Header value is null");
+ }
+ buffer = new CharArrayBuffer(s.length());
+ buffer.append(s);
+ pos = 0;
+ }
+ while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) {
+ pos++;
+ }
+ final int beginIndex = pos;
+ while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) {
+ pos++;
+ }
+ final int endIndex = pos;
+ final String s = buffer.substring(beginIndex, endIndex);
+ map.put(s.toLowerCase(Locale.ENGLISH), header);
+ }
+ return map;
+ }
+
+ abstract Collection getPreferredAuthSchemes(RequestConfig config);
+
+ public Queue select(
+ final Map challenges,
+ final HttpHost authhost,
+ final HttpResponse response,
+ final HttpContext context) throws MalformedChallengeException {
+ Args.notNull(challenges, "Map of auth challenges");
+ Args.notNull(authhost, "Host");
+ Args.notNull(response, "HTTP response");
+ Args.notNull(context, "HTTP context");
+ final HttpClientContext clientContext = HttpClientContext.adapt(context);
+
+ final Queue options = new LinkedList();
+ final Lookup registry = clientContext.getAuthSchemeRegistry();
+ if (registry == null) {
+ this.log.debug("Auth scheme registry not set in the context");
+ return options;
+ }
+ final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
+ if (credsProvider == null) {
+ this.log.debug("Credentials provider not set in the context");
+ return options;
+ }
+ final RequestConfig config = clientContext.getRequestConfig();
+ Collection authPrefs = getPreferredAuthSchemes(config);
+ if (authPrefs == null) {
+ authPrefs = DEFAULT_SCHEME_PRIORITY;
+ }
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Authentication schemes in the order of preference: " + authPrefs);
+ }
+
+ for (final String id: authPrefs) {
+ final Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
+ if (challenge != null) {
+ final AuthSchemeProvider authSchemeProvider = registry.lookup(id);
+ if (authSchemeProvider == null) {
+ if (this.log.isWarnEnabled()) {
+ this.log.warn("Authentication scheme " + id + " not supported");
+ // Try again
+ }
+ continue;
+ }
+ final AuthScheme authScheme = authSchemeProvider.create(context);
+ authScheme.processChallenge(challenge);
+
+ final AuthScope authScope = new AuthScope(
+ authhost.getHostName(),
+ authhost.getPort(),
+ authScheme.getRealm(),
+ authScheme.getSchemeName());
+
+ final Credentials credentials = credsProvider.getCredentials(authScope);
+ if (credentials != null) {
+ options.add(new AuthOption(authScheme, credentials));
+ }
+ } else {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Challenge for " + id + " authentication scheme not available");
+ // Try again
+ }
+ }
+ }
+ return options;
+ }
+
+ public void authSucceeded(
+ final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
+ Args.notNull(authhost, "Host");
+ Args.notNull(authScheme, "Auth scheme");
+ Args.notNull(context, "HTTP context");
+
+ final HttpClientContext clientContext = HttpClientContext.adapt(context);
+
+ if (isCachable(authScheme)) {
+ AuthCache authCache = clientContext.getAuthCache();
+ if (authCache == null) {
+ authCache = new BasicAuthCache();
+ clientContext.setAuthCache(authCache);
+ }
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Caching '" + authScheme.getSchemeName() +
+ "' auth scheme for " + authhost);
+ }
+ authCache.put(authhost, authScheme);
+ }
+ }
+
+ protected boolean isCachable(final AuthScheme authScheme) {
+ if (authScheme == null || !authScheme.isComplete()) {
+ return false;
+ }
+ final String schemeName = authScheme.getSchemeName();
+ return schemeName.equalsIgnoreCase(AuthSchemes.BASIC) ||
+ schemeName.equalsIgnoreCase(AuthSchemes.DIGEST);
+ }
+
+ public void authFailed(
+ final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
+ Args.notNull(authhost, "Host");
+ Args.notNull(context, "HTTP context");
+
+ final HttpClientContext clientContext = HttpClientContext.adapt(context);
+
+ final AuthCache authCache = clientContext.getAuthCache();
+ if (authCache != null) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Clearing cached auth scheme for " + authhost);
+ }
+ authCache.remove(authhost);
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AutoRetryHttpClient.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AutoRetryHttpClient.java
new file mode 100644
index 000000000..70c0e3404
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/AutoRetryHttpClient.java
@@ -0,0 +1,190 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.URI;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.client.HttpClient;
+import ch.boye.httpclientandroidlib.client.ResponseHandler;
+import ch.boye.httpclientandroidlib.client.ServiceUnavailableRetryStrategy;
+import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.EntityUtils;
+
+/**
+ * {@link HttpClient} implementation that can automatically retry the request in case of
+ * a non-2xx response using the {@link ServiceUnavailableRetryStrategy} interface.
+ *
+ * @since 4.2
+ *
+ * @deprecated (4.3) use {@link HttpClientBuilder}.
+ */
+@Deprecated
+@ThreadSafe
+public class AutoRetryHttpClient implements HttpClient {
+
+ private final HttpClient backend;
+
+ private final ServiceUnavailableRetryStrategy retryStrategy;
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ public AutoRetryHttpClient(
+ final HttpClient client, final ServiceUnavailableRetryStrategy retryStrategy) {
+ super();
+ Args.notNull(client, "HttpClient");
+ Args.notNull(retryStrategy, "ServiceUnavailableRetryStrategy");
+ this.backend = client;
+ this.retryStrategy = retryStrategy;
+ }
+
+ /**
+ * Constructs a {@code AutoRetryHttpClient} with default caching settings that
+ * stores cache entries in memory and uses a vanilla
+ * {@link DefaultHttpClient} for backend requests.
+ */
+ public AutoRetryHttpClient() {
+ this(new DefaultHttpClient(), new DefaultServiceUnavailableRetryStrategy());
+ }
+
+ /**
+ * Constructs a {@code AutoRetryHttpClient} with the given caching options that
+ * stores cache entries in memory and uses a vanilla
+ * {@link DefaultHttpClient} for backend requests.
+ *
+ * @param config
+ * retry configuration module options
+ */
+ public AutoRetryHttpClient(final ServiceUnavailableRetryStrategy config) {
+ this(new DefaultHttpClient(), config);
+ }
+
+ /**
+ * Constructs a {@code AutoRetryHttpClient} with default caching settings that
+ * stores cache entries in memory and uses the given {@link HttpClient} for
+ * backend requests.
+ *
+ * @param client
+ * used to make origin requests
+ */
+ public AutoRetryHttpClient(final HttpClient client) {
+ this(client, new DefaultServiceUnavailableRetryStrategy());
+ }
+
+ public HttpResponse execute(final HttpHost target, final HttpRequest request)
+ throws IOException {
+ final HttpContext defaultContext = null;
+ return execute(target, request, defaultContext);
+ }
+
+ public T execute(final HttpHost target, final HttpRequest request,
+ final ResponseHandler extends T> responseHandler) throws IOException {
+ return execute(target, request, responseHandler, null);
+ }
+
+ public T execute(final HttpHost target, final HttpRequest request,
+ final ResponseHandler extends T> responseHandler, final HttpContext context)
+ throws IOException {
+ final HttpResponse resp = execute(target, request, context);
+ return responseHandler.handleResponse(resp);
+ }
+
+ public HttpResponse execute(final HttpUriRequest request) throws IOException {
+ final HttpContext context = null;
+ return execute(request, context);
+ }
+
+ public HttpResponse execute(final HttpUriRequest request, final HttpContext context)
+ throws IOException {
+ final URI uri = request.getURI();
+ final HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort(),
+ uri.getScheme());
+ return execute(httpHost, request, context);
+ }
+
+ public T execute(final HttpUriRequest request,
+ final ResponseHandler extends T> responseHandler) throws IOException {
+ return execute(request, responseHandler, null);
+ }
+
+ public T execute(final HttpUriRequest request,
+ final ResponseHandler extends T> responseHandler, final HttpContext context)
+ throws IOException {
+ final HttpResponse resp = execute(request, context);
+ return responseHandler.handleResponse(resp);
+ }
+
+ public HttpResponse execute(final HttpHost target, final HttpRequest request,
+ final HttpContext context) throws IOException {
+ for (int c = 1;; c++) {
+ final HttpResponse response = backend.execute(target, request, context);
+ try {
+ if (retryStrategy.retryRequest(response, c, context)) {
+ EntityUtils.consume(response.getEntity());
+ final long nextInterval = retryStrategy.getRetryInterval();
+ try {
+ log.trace("Wait for " + nextInterval);
+ Thread.sleep(nextInterval);
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException();
+ }
+ } else {
+ return response;
+ }
+ } catch (final RuntimeException ex) {
+ try {
+ EntityUtils.consume(response.getEntity());
+ } catch (final IOException ioex) {
+ log.warn("I/O error consuming response content", ioex);
+ }
+ throw ex;
+ }
+ }
+ }
+
+ public ClientConnectionManager getConnectionManager() {
+ return backend.getConnectionManager();
+ }
+
+ public HttpParams getParams() {
+ return backend.getParams();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/BasicAuthCache.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/BasicAuthCache.java
new file mode 100644
index 000000000..810f73a0a
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/BasicAuthCache.java
@@ -0,0 +1,105 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.util.HashMap;
+
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.auth.AuthScheme;
+import ch.boye.httpclientandroidlib.client.AuthCache;
+import ch.boye.httpclientandroidlib.conn.SchemePortResolver;
+import ch.boye.httpclientandroidlib.conn.UnsupportedSchemeException;
+import ch.boye.httpclientandroidlib.impl.conn.DefaultSchemePortResolver;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Default implementation of {@link AuthCache}.
+ *
+ * @since 4.0
+ */
+@NotThreadSafe
+public class BasicAuthCache implements AuthCache {
+
+ private final HashMap map;
+ private final SchemePortResolver schemePortResolver;
+
+ /**
+ * Default constructor.
+ *
+ * @since 4.3
+ */
+ public BasicAuthCache(final SchemePortResolver schemePortResolver) {
+ super();
+ this.map = new HashMap();
+ this.schemePortResolver = schemePortResolver != null ? schemePortResolver :
+ DefaultSchemePortResolver.INSTANCE;
+ }
+
+ public BasicAuthCache() {
+ this(null);
+ }
+
+ protected HttpHost getKey(final HttpHost host) {
+ if (host.getPort() <= 0) {
+ final int port;
+ try {
+ port = schemePortResolver.resolve(host);
+ } catch (final UnsupportedSchemeException ignore) {
+ return host;
+ }
+ return new HttpHost(host.getHostName(), port, host.getSchemeName());
+ } else {
+ return host;
+ }
+ }
+
+ public void put(final HttpHost host, final AuthScheme authScheme) {
+ Args.notNull(host, "HTTP host");
+ this.map.put(getKey(host), authScheme);
+ }
+
+ public AuthScheme get(final HttpHost host) {
+ Args.notNull(host, "HTTP host");
+ return this.map.get(getKey(host));
+ }
+
+ public void remove(final HttpHost host) {
+ Args.notNull(host, "HTTP host");
+ this.map.remove(getKey(host));
+ }
+
+ public void clear() {
+ this.map.clear();
+ }
+
+ @Override
+ public String toString() {
+ return this.map.toString();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/BasicCookieStore.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/BasicCookieStore.java
new file mode 100644
index 000000000..624a8f81d
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/BasicCookieStore.java
@@ -0,0 +1,144 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import java.util.TreeSet;
+
+import ch.boye.httpclientandroidlib.annotation.GuardedBy;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.client.CookieStore;
+import ch.boye.httpclientandroidlib.cookie.Cookie;
+import ch.boye.httpclientandroidlib.cookie.CookieIdentityComparator;
+
+/**
+ * Default implementation of {@link CookieStore}
+ *
+ *
+ * @since 4.0
+ */
+@ThreadSafe
+public class BasicCookieStore implements CookieStore, Serializable {
+
+ private static final long serialVersionUID = -7581093305228232025L;
+
+ @GuardedBy("this")
+ private final TreeSet cookies;
+
+ public BasicCookieStore() {
+ super();
+ this.cookies = new TreeSet(new CookieIdentityComparator());
+ }
+
+ /**
+ * Adds an {@link Cookie HTTP cookie}, replacing any existing equivalent cookies.
+ * If the given cookie has already expired it will not be added, but existing
+ * values will still be removed.
+ *
+ * @param cookie the {@link Cookie cookie} to be added
+ *
+ * @see #addCookies(Cookie[])
+ *
+ */
+ public synchronized void addCookie(final Cookie cookie) {
+ if (cookie != null) {
+ // first remove any old cookie that is equivalent
+ cookies.remove(cookie);
+ if (!cookie.isExpired(new Date())) {
+ cookies.add(cookie);
+ }
+ }
+ }
+
+ /**
+ * Adds an array of {@link Cookie HTTP cookies}. Cookies are added individually and
+ * in the given array order. If any of the given cookies has already expired it will
+ * not be added, but existing values will still be removed.
+ *
+ * @param cookies the {@link Cookie cookies} to be added
+ *
+ * @see #addCookie(Cookie)
+ *
+ */
+ public synchronized void addCookies(final Cookie[] cookies) {
+ if (cookies != null) {
+ for (final Cookie cooky : cookies) {
+ this.addCookie(cooky);
+ }
+ }
+ }
+
+ /**
+ * Returns an immutable array of {@link Cookie cookies} that this HTTP
+ * state currently contains.
+ *
+ * @return an array of {@link Cookie cookies}.
+ */
+ public synchronized List getCookies() {
+ //create defensive copy so it won't be concurrently modified
+ return new ArrayList(cookies);
+ }
+
+ /**
+ * Removes all of {@link Cookie cookies} in this HTTP state
+ * that have expired by the specified {@link java.util.Date date}.
+ *
+ * @return true if any cookies were purged.
+ *
+ * @see Cookie#isExpired(Date)
+ */
+ public synchronized boolean clearExpired(final Date date) {
+ if (date == null) {
+ return false;
+ }
+ boolean removed = false;
+ for (final Iterator it = cookies.iterator(); it.hasNext();) {
+ if (it.next().isExpired(date)) {
+ it.remove();
+ removed = true;
+ }
+ }
+ return removed;
+ }
+
+ /**
+ * Clears all cookies.
+ */
+ public synchronized void clear() {
+ cookies.clear();
+ }
+
+ @Override
+ public synchronized String toString() {
+ return cookies.toString();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/BasicCredentialsProvider.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/BasicCredentialsProvider.java
new file mode 100644
index 000000000..99c5cccc2
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/BasicCredentialsProvider.java
@@ -0,0 +1,109 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.auth.AuthScope;
+import ch.boye.httpclientandroidlib.auth.Credentials;
+import ch.boye.httpclientandroidlib.client.CredentialsProvider;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Default implementation of {@link CredentialsProvider}.
+ *
+ * @since 4.0
+ */
+@ThreadSafe
+public class BasicCredentialsProvider implements CredentialsProvider {
+
+ private final ConcurrentHashMap credMap;
+
+ /**
+ * Default constructor.
+ */
+ public BasicCredentialsProvider() {
+ super();
+ this.credMap = new ConcurrentHashMap();
+ }
+
+ public void setCredentials(
+ final AuthScope authscope,
+ final Credentials credentials) {
+ Args.notNull(authscope, "Authentication scope");
+ credMap.put(authscope, credentials);
+ }
+
+ /**
+ * Find matching {@link Credentials credentials} for the given authentication scope.
+ *
+ * @param map the credentials hash map
+ * @param authscope the {@link AuthScope authentication scope}
+ * @return the credentials
+ *
+ */
+ private static Credentials matchCredentials(
+ final Map map,
+ final AuthScope authscope) {
+ // see if we get a direct hit
+ Credentials creds = map.get(authscope);
+ if (creds == null) {
+ // Nope.
+ // Do a full scan
+ int bestMatchFactor = -1;
+ AuthScope bestMatch = null;
+ for (final AuthScope current: map.keySet()) {
+ final int factor = authscope.match(current);
+ if (factor > bestMatchFactor) {
+ bestMatchFactor = factor;
+ bestMatch = current;
+ }
+ }
+ if (bestMatch != null) {
+ creds = map.get(bestMatch);
+ }
+ }
+ return creds;
+ }
+
+ public Credentials getCredentials(final AuthScope authscope) {
+ Args.notNull(authscope, "Authentication scope");
+ return matchCredentials(this.credMap, authscope);
+ }
+
+ public void clear() {
+ this.credMap.clear();
+ }
+
+ @Override
+ public String toString() {
+ return credMap.toString();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/BasicResponseHandler.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/BasicResponseHandler.java
new file mode 100644
index 000000000..13ae4f856
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/BasicResponseHandler.java
@@ -0,0 +1,73 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.StatusLine;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.HttpResponseException;
+import ch.boye.httpclientandroidlib.client.ResponseHandler;
+import ch.boye.httpclientandroidlib.util.EntityUtils;
+
+/**
+ * A {@link ResponseHandler} that returns the response body as a String
+ * for successful (2xx) responses. If the response code was >= 300, the response
+ * body is consumed and an {@link HttpResponseException} is thrown.
+ *
+ * If this is used with
+ * {@link ch.boye.httpclientandroidlib.client.HttpClient#execute(
+ * ch.boye.httpclientandroidlib.client.methods.HttpUriRequest, ResponseHandler)},
+ * HttpClient may handle redirects (3xx responses) internally.
+ *
+ * @since 4.0
+ */
+@Immutable
+public class BasicResponseHandler implements ResponseHandler {
+
+ /**
+ * Returns the response body as a String if the response was successful (a
+ * 2xx status code). If no response body exists, this returns null. If the
+ * response was unsuccessful (>= 300 status code), throws an
+ * {@link HttpResponseException}.
+ */
+ public String handleResponse(final HttpResponse response)
+ throws HttpResponseException, IOException {
+ final StatusLine statusLine = response.getStatusLine();
+ final HttpEntity entity = response.getEntity();
+ if (statusLine.getStatusCode() >= 300) {
+ EntityUtils.consume(entity);
+ throw new HttpResponseException(statusLine.getStatusCode(),
+ statusLine.getReasonPhrase());
+ }
+ return entity == null ? null : EntityUtils.toString(entity);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/ClientParamsStack.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/ClientParamsStack.java
new file mode 100644
index 000000000..37f5daedd
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/ClientParamsStack.java
@@ -0,0 +1,269 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.params.AbstractHttpParams;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Represents a stack of parameter collections.
+ * When retrieving a parameter, the stack is searched in a fixed order
+ * and the first match returned. Setting parameters via the stack is
+ * not supported. To minimize overhead, the stack has a fixed size and
+ * does not maintain an internal array.
+ * The supported stack entries, sorted by increasing priority, are:
+ *
+ *
Application parameters:
+ * expected to be the same for all clients used by an application.
+ * These provide "global", that is application-wide, defaults.
+ *
+ *
Client parameters:
+ * specific to an instance of
+ * {@link ch.boye.httpclientandroidlib.client.HttpClient HttpClient}.
+ * These provide client specific defaults.
+ *
+ *
Request parameters:
+ * specific to a single request execution.
+ * For overriding client and global defaults.
+ *
+ *
Override parameters:
+ * specific to an instance of
+ * {@link ch.boye.httpclientandroidlib.client.HttpClient HttpClient}.
+ * These can be used to set parameters that cannot be overridden
+ * on a per-request basis.
+ *
+ *
+ * Each stack entry may be null. That is preferable over
+ * an empty params collection, since it avoids searching the empty collection
+ * when looking up parameters.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use configuration classes provided 'ch.boye.httpclientandroidlib.config'
+ * and 'ch.boye.httpclientandroidlib.client.config'
+ */
+@NotThreadSafe
+@Deprecated
+public class ClientParamsStack extends AbstractHttpParams {
+
+ /** The application parameter collection, or null. */
+ protected final HttpParams applicationParams;
+
+ /** The client parameter collection, or null. */
+ protected final HttpParams clientParams;
+
+ /** The request parameter collection, or null. */
+ protected final HttpParams requestParams;
+
+ /** The override parameter collection, or null. */
+ protected final HttpParams overrideParams;
+
+
+ /**
+ * Creates a new parameter stack from elements.
+ * The arguments will be stored as-is, there is no copying to
+ * prevent modification.
+ *
+ * @param aparams application parameters, or null
+ * @param cparams client parameters, or null
+ * @param rparams request parameters, or null
+ * @param oparams override parameters, or null
+ */
+ public ClientParamsStack(final HttpParams aparams, final HttpParams cparams,
+ final HttpParams rparams, final HttpParams oparams) {
+ applicationParams = aparams;
+ clientParams = cparams;
+ requestParams = rparams;
+ overrideParams = oparams;
+ }
+
+
+ /**
+ * Creates a copy of a parameter stack.
+ * The new stack will have the exact same entries as the argument stack.
+ * There is no copying of parameters.
+ *
+ * @param stack the stack to copy
+ */
+ public ClientParamsStack(final ClientParamsStack stack) {
+ this(stack.getApplicationParams(),
+ stack.getClientParams(),
+ stack.getRequestParams(),
+ stack.getOverrideParams());
+ }
+
+
+ /**
+ * Creates a modified copy of a parameter stack.
+ * The new stack will contain the explicitly passed elements.
+ * For elements where the explicit argument is null,
+ * the corresponding element from the argument stack is used.
+ * There is no copying of parameters.
+ *
+ * @param stack the stack to modify
+ * @param aparams application parameters, or null
+ * @param cparams client parameters, or null
+ * @param rparams request parameters, or null
+ * @param oparams override parameters, or null
+ */
+ public ClientParamsStack(final ClientParamsStack stack,
+ final HttpParams aparams, final HttpParams cparams,
+ final HttpParams rparams, final HttpParams oparams) {
+ this((aparams != null) ? aparams : stack.getApplicationParams(),
+ (cparams != null) ? cparams : stack.getClientParams(),
+ (rparams != null) ? rparams : stack.getRequestParams(),
+ (oparams != null) ? oparams : stack.getOverrideParams());
+ }
+
+
+ /**
+ * Obtains the application parameters of this stack.
+ *
+ * @return the application parameters, or null
+ */
+ public final HttpParams getApplicationParams() {
+ return applicationParams;
+ }
+
+ /**
+ * Obtains the client parameters of this stack.
+ *
+ * @return the client parameters, or null
+ */
+ public final HttpParams getClientParams() {
+ return clientParams;
+ }
+
+ /**
+ * Obtains the request parameters of this stack.
+ *
+ * @return the request parameters, or null
+ */
+ public final HttpParams getRequestParams() {
+ return requestParams;
+ }
+
+ /**
+ * Obtains the override parameters of this stack.
+ *
+ * @return the override parameters, or null
+ */
+ public final HttpParams getOverrideParams() {
+ return overrideParams;
+ }
+
+
+ /**
+ * Obtains a parameter from this stack.
+ * See class comment for search order.
+ *
+ * @param name the name of the parameter to obtain
+ *
+ * @return the highest-priority value for that parameter, or
+ * null if it is not set anywhere in this stack
+ */
+ public Object getParameter(final String name) {
+ Args.notNull(name, "Parameter name");
+
+ Object result = null;
+
+ if (overrideParams != null) {
+ result = overrideParams.getParameter(name);
+ }
+ if ((result == null) && (requestParams != null)) {
+ result = requestParams.getParameter(name);
+ }
+ if ((result == null) && (clientParams != null)) {
+ result = clientParams.getParameter(name);
+ }
+ if ((result == null) && (applicationParams != null)) {
+ result = applicationParams.getParameter(name);
+ }
+ return result;
+ }
+
+ /**
+ * Does not set a parameter.
+ * Parameter stacks are read-only. It is possible, though discouraged,
+ * to access and modify specific stack entries.
+ * Derived classes may change this behavior.
+ *
+ * @param name ignored
+ * @param value ignored
+ *
+ * @return nothing
+ *
+ * @throws UnsupportedOperationException always
+ */
+ public HttpParams setParameter(final String name, final Object value)
+ throws UnsupportedOperationException {
+
+ throw new UnsupportedOperationException
+ ("Setting parameters in a stack is not supported.");
+ }
+
+
+ /**
+ * Does not remove a parameter.
+ * Parameter stacks are read-only. It is possible, though discouraged,
+ * to access and modify specific stack entries.
+ * Derived classes may change this behavior.
+ *
+ * @param name ignored
+ *
+ * @return nothing
+ *
+ * @throws UnsupportedOperationException always
+ */
+ public boolean removeParameter(final String name) {
+ throw new UnsupportedOperationException
+ ("Removing parameters in a stack is not supported.");
+ }
+
+
+ /**
+ * Does not copy parameters.
+ * Parameter stacks are lightweight objects, expected to be instantiated
+ * as needed and to be used only in a very specific context. On top of
+ * that, they are read-only. The typical copy operation to prevent
+ * accidental modification of parameters passed by the application to
+ * a framework object is therefore pointless and disabled.
+ * Create a new stack if you really need a copy.
+ *
+ * Derived classes may change this behavior.
+ *
+ * @return this parameter stack
+ */
+ public HttpParams copy() {
+ return this;
+ }
+
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/Clock.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/Clock.java
new file mode 100644
index 000000000..14eeec4a0
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/Clock.java
@@ -0,0 +1,43 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+/**
+ * Interface used to enable easier testing of time-related behavior.
+ *
+ * @since 4.2
+ *
+ */
+interface Clock {
+
+ /**
+ * Returns the current time, expressed as the number of
+ * milliseconds since the epoch.
+ * @return current time
+ */
+ long getCurrentTime();
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/CloseableHttpClient.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/CloseableHttpClient.java
new file mode 100644
index 000000000..c2fc5a5de
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/CloseableHttpClient.java
@@ -0,0 +1,244 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.lang.reflect.UndeclaredThrowableException;
+import java.net.URI;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.client.ClientProtocolException;
+import ch.boye.httpclientandroidlib.client.HttpClient;
+import ch.boye.httpclientandroidlib.client.ResponseHandler;
+import ch.boye.httpclientandroidlib.client.methods.CloseableHttpResponse;
+import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest;
+import ch.boye.httpclientandroidlib.client.utils.URIUtils;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.EntityUtils;
+
+/**
+ * Base implementation of {@link HttpClient} that also implements {@link Closeable}.
+ *
+ * @since 4.3
+ */
+@ThreadSafe
+public abstract class CloseableHttpClient implements HttpClient, Closeable {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ protected abstract CloseableHttpResponse doExecute(HttpHost target, HttpRequest request,
+ HttpContext context) throws IOException, ClientProtocolException;
+
+ /**
+ * {@inheritDoc}
+ */
+ public CloseableHttpResponse execute(
+ final HttpHost target,
+ final HttpRequest request,
+ final HttpContext context) throws IOException, ClientProtocolException {
+ return doExecute(target, request, context);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public CloseableHttpResponse execute(
+ final HttpUriRequest request,
+ final HttpContext context) throws IOException, ClientProtocolException {
+ Args.notNull(request, "HTTP request");
+ return doExecute(determineTarget(request), request, context);
+ }
+
+ private static HttpHost determineTarget(final HttpUriRequest request) throws ClientProtocolException {
+ // A null target may be acceptable if there is a default target.
+ // Otherwise, the null target is detected in the director.
+ HttpHost target = null;
+
+ final URI requestURI = request.getURI();
+ if (requestURI.isAbsolute()) {
+ target = URIUtils.extractHost(requestURI);
+ if (target == null) {
+ throw new ClientProtocolException("URI does not specify a valid host name: "
+ + requestURI);
+ }
+ }
+ return target;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public CloseableHttpResponse execute(
+ final HttpUriRequest request) throws IOException, ClientProtocolException {
+ return execute(request, (HttpContext) null);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public CloseableHttpResponse execute(
+ final HttpHost target,
+ final HttpRequest request) throws IOException, ClientProtocolException {
+ return doExecute(target, request, (HttpContext) null);
+ }
+
+ /**
+ * Executes a request using the default context and processes the
+ * response using the given response handler. The content entity associated
+ * with the response is fully consumed and the underlying connection is
+ * released back to the connection manager automatically in all cases
+ * relieving individual {@link ResponseHandler}s from having to manage
+ * resource deallocation internally.
+ *
+ * @param request the request to execute
+ * @param responseHandler the response handler
+ *
+ * @return the response object as generated by the response handler.
+ * @throws IOException in case of a problem or the connection was aborted
+ * @throws ClientProtocolException in case of an http protocol error
+ */
+ public T execute(final HttpUriRequest request,
+ final ResponseHandler extends T> responseHandler) throws IOException,
+ ClientProtocolException {
+ return execute(request, responseHandler, null);
+ }
+
+ /**
+ * Executes a request using the default context and processes the
+ * response using the given response handler. The content entity associated
+ * with the response is fully consumed and the underlying connection is
+ * released back to the connection manager automatically in all cases
+ * relieving individual {@link ResponseHandler}s from having to manage
+ * resource deallocation internally.
+ *
+ * @param request the request to execute
+ * @param responseHandler the response handler
+ * @param context the context to use for the execution, or
+ * null to use the default context
+ *
+ * @return the response object as generated by the response handler.
+ * @throws IOException in case of a problem or the connection was aborted
+ * @throws ClientProtocolException in case of an http protocol error
+ */
+ public T execute(final HttpUriRequest request,
+ final ResponseHandler extends T> responseHandler, final HttpContext context)
+ throws IOException, ClientProtocolException {
+ final HttpHost target = determineTarget(request);
+ return execute(target, request, responseHandler, context);
+ }
+
+ /**
+ * Executes a request using the default context and processes the
+ * response using the given response handler. The content entity associated
+ * with the response is fully consumed and the underlying connection is
+ * released back to the connection manager automatically in all cases
+ * relieving individual {@link ResponseHandler}s from having to manage
+ * resource deallocation internally.
+ *
+ * @param target the target host for the request.
+ * Implementations may accept null
+ * if they can still determine a route, for example
+ * to a default target or by inspecting the request.
+ * @param request the request to execute
+ * @param responseHandler the response handler
+ *
+ * @return the response object as generated by the response handler.
+ * @throws IOException in case of a problem or the connection was aborted
+ * @throws ClientProtocolException in case of an http protocol error
+ */
+ public T execute(final HttpHost target, final HttpRequest request,
+ final ResponseHandler extends T> responseHandler) throws IOException,
+ ClientProtocolException {
+ return execute(target, request, responseHandler, null);
+ }
+
+ /**
+ * Executes a request using the default context and processes the
+ * response using the given response handler. The content entity associated
+ * with the response is fully consumed and the underlying connection is
+ * released back to the connection manager automatically in all cases
+ * relieving individual {@link ResponseHandler}s from having to manage
+ * resource deallocation internally.
+ *
+ * @param target the target host for the request.
+ * Implementations may accept null
+ * if they can still determine a route, for example
+ * to a default target or by inspecting the request.
+ * @param request the request to execute
+ * @param responseHandler the response handler
+ * @param context the context to use for the execution, or
+ * null to use the default context
+ *
+ * @return the response object as generated by the response handler.
+ * @throws IOException in case of a problem or the connection was aborted
+ * @throws ClientProtocolException in case of an http protocol error
+ */
+ public T execute(final HttpHost target, final HttpRequest request,
+ final ResponseHandler extends T> responseHandler, final HttpContext context)
+ throws IOException, ClientProtocolException {
+ Args.notNull(responseHandler, "Response handler");
+
+ final HttpResponse response = execute(target, request, context);
+
+ final T result;
+ try {
+ result = responseHandler.handleResponse(response);
+ } catch (final Exception t) {
+ final HttpEntity entity = response.getEntity();
+ try {
+ EntityUtils.consume(entity);
+ } catch (final Exception t2) {
+ // Log this exception. The original exception is more
+ // important and will be thrown to the caller.
+ this.log.warn("Error consuming content after an exception.", t2);
+ }
+ if (t instanceof RuntimeException) {
+ throw (RuntimeException) t;
+ }
+ if (t instanceof IOException) {
+ throw (IOException) t;
+ }
+ throw new UndeclaredThrowableException(t);
+ }
+
+ // Handling the response was successful. Ensure that the content has
+ // been fully consumed.
+ final HttpEntity entity = response.getEntity();
+ EntityUtils.consume(entity);
+ return result;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/CloseableHttpResponseProxy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/CloseableHttpResponseProxy.java
new file mode 100644
index 000000000..9869740df
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/CloseableHttpResponseProxy.java
@@ -0,0 +1,87 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.io.IOException;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.client.methods.CloseableHttpResponse;
+import ch.boye.httpclientandroidlib.util.EntityUtils;
+
+/**
+ * @since 4.3
+ */
+@NotThreadSafe
+class CloseableHttpResponseProxy implements InvocationHandler {
+
+ private final HttpResponse original;
+
+ CloseableHttpResponseProxy(final HttpResponse original) {
+ super();
+ this.original = original;
+ }
+
+ public void close() throws IOException {
+ final HttpEntity entity = this.original.getEntity();
+ EntityUtils.consume(entity);
+ }
+
+ public Object invoke(
+ final Object proxy, final Method method, final Object[] args) throws Throwable {
+ final String mname = method.getName();
+ if (mname.equals("close")) {
+ close();
+ return null;
+ } else {
+ try {
+ return method.invoke(original, args);
+ } catch (final InvocationTargetException ex) {
+ final Throwable cause = ex.getCause();
+ if (cause != null) {
+ throw cause;
+ } else {
+ throw ex;
+ }
+ }
+ }
+ }
+
+ public static CloseableHttpResponse newProxy(final HttpResponse original) {
+ return (CloseableHttpResponse) Proxy.newProxyInstance(
+ CloseableHttpResponseProxy.class.getClassLoader(),
+ new Class>[] { CloseableHttpResponse.class },
+ new CloseableHttpResponseProxy(original));
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/ContentEncodingHttpClient.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/ContentEncodingHttpClient.java
new file mode 100644
index 000000000..f4169225e
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/ContentEncodingHttpClient.java
@@ -0,0 +1,93 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.client.protocol.RequestAcceptEncoding;
+import ch.boye.httpclientandroidlib.client.protocol.ResponseContentEncoding;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.BasicHttpProcessor;
+
+/**
+ * {@link DefaultHttpClient} sub-class which includes a {@link RequestAcceptEncoding}
+ * for the request and response.
+ *
+ * Deprecation note: due to the way this class modifies a response body
+ * without changing the response headers to reflect the entity changes, it cannot
+ * be used as the "backend" for a caching {@link
+ * ch.boye.httpclientandroidlib.client.HttpClient} and still have uncompressed responses be cached.
+ * Users are encouraged to use the {@link DecompressingHttpClient} instead
+ * of this class, which can be wired in either before or after caching, depending on
+ * whether you want to cache responses in compressed or uncompressed form.
+ *
+ * @since 4.1
+ *
+ * @deprecated (4.2) use {@link HttpClientBuilder}
+ */
+@Deprecated
+@ThreadSafe // since DefaultHttpClient is
+public class ContentEncodingHttpClient extends DefaultHttpClient {
+
+ /**
+ * Creates a new HTTP client from parameters and a connection manager.
+ *
+ * @param params the parameters
+ * @param conman the connection manager
+ */
+ public ContentEncodingHttpClient(final ClientConnectionManager conman, final HttpParams params) {
+ super(conman, params);
+ }
+
+ /**
+ * @param params
+ */
+ public ContentEncodingHttpClient(final HttpParams params) {
+ this(null, params);
+ }
+
+ /**
+ *
+ */
+ public ContentEncodingHttpClient() {
+ this(null);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected BasicHttpProcessor createHttpProcessor() {
+ final BasicHttpProcessor result = super.createHttpProcessor();
+
+ result.addRequestInterceptor(new RequestAcceptEncoding());
+ result.addResponseInterceptor(new ResponseContentEncoding());
+
+ return result;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DecompressingHttpClient.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DecompressingHttpClient.java
new file mode 100644
index 000000000..4d55303ad
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DecompressingHttpClient.java
@@ -0,0 +1,214 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.io.IOException;
+import java.net.URI;
+
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpRequestInterceptor;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpResponseInterceptor;
+import ch.boye.httpclientandroidlib.client.ClientProtocolException;
+import ch.boye.httpclientandroidlib.client.HttpClient;
+import ch.boye.httpclientandroidlib.client.ResponseHandler;
+import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest;
+import ch.boye.httpclientandroidlib.client.protocol.RequestAcceptEncoding;
+import ch.boye.httpclientandroidlib.client.protocol.ResponseContentEncoding;
+import ch.boye.httpclientandroidlib.client.utils.URIUtils;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.BasicHttpContext;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.EntityUtils;
+
+/**
+ *
Decorator adding support for compressed responses. This class sets
+ * the Accept-Encoding header on requests to indicate
+ * support for the gzip and deflate
+ * compression schemes; it then checks the Content-Encoding
+ * header on the response to uncompress any compressed response bodies.
+ * The {@link java.io.InputStream} of the entity will contain the uncompressed
+ * content.
+ *
+ *
N.B. Any upstream clients of this class need to be aware that
+ * this effectively obscures visibility into the length of a server
+ * response body, since the Content-Length header will
+ * correspond to the compressed entity length received from the server,
+ * but the content length experienced by reading the response body may
+ * be different (hopefully higher!).
+ *
+ *
That said, this decorator is compatible with the
+ * CachingHttpClient in that the two decorators can be added
+ * in either order and still have cacheable responses be cached.
+ *
+ * @since 4.2
+ *
+ * @deprecated (4.3) use {@link HttpClientBuilder}
+ */
+@Deprecated
+public class DecompressingHttpClient implements HttpClient {
+
+ private final HttpClient backend;
+ private final HttpRequestInterceptor acceptEncodingInterceptor;
+ private final HttpResponseInterceptor contentEncodingInterceptor;
+
+ /**
+ * Constructs a decorator to ask for and handle compressed
+ * entities on the fly.
+ */
+ public DecompressingHttpClient() {
+ this(new DefaultHttpClient());
+ }
+
+ /**
+ * Constructs a decorator to ask for and handle compressed
+ * entities on the fly.
+ * @param backend the {@link HttpClient} to use for actually
+ * issuing requests
+ */
+ public DecompressingHttpClient(final HttpClient backend) {
+ this(backend, new RequestAcceptEncoding(), new ResponseContentEncoding());
+ }
+
+ DecompressingHttpClient(final HttpClient backend,
+ final HttpRequestInterceptor requestInterceptor,
+ final HttpResponseInterceptor responseInterceptor) {
+ this.backend = backend;
+ this.acceptEncodingInterceptor = requestInterceptor;
+ this.contentEncodingInterceptor = responseInterceptor;
+ }
+
+ public HttpParams getParams() {
+ return backend.getParams();
+ }
+
+ public ClientConnectionManager getConnectionManager() {
+ return backend.getConnectionManager();
+ }
+
+ public HttpResponse execute(final HttpUriRequest request) throws IOException,
+ ClientProtocolException {
+ return execute(getHttpHost(request), request, (HttpContext)null);
+ }
+
+ /**
+ * Gets the HttpClient to issue request.
+ *
+ * @return the HttpClient to issue request
+ */
+ public HttpClient getHttpClient() {
+ return this.backend;
+ }
+
+ HttpHost getHttpHost(final HttpUriRequest request) {
+ final URI uri = request.getURI();
+ return URIUtils.extractHost(uri);
+ }
+
+ public HttpResponse execute(final HttpUriRequest request, final HttpContext context)
+ throws IOException, ClientProtocolException {
+ return execute(getHttpHost(request), request, context);
+ }
+
+ public HttpResponse execute(final HttpHost target, final HttpRequest request)
+ throws IOException, ClientProtocolException {
+ return execute(target, request, (HttpContext)null);
+ }
+
+ public HttpResponse execute(final HttpHost target, final HttpRequest request,
+ final HttpContext context) throws IOException, ClientProtocolException {
+ try {
+ final HttpContext localContext = context != null ? context : new BasicHttpContext();
+ final HttpRequest wrapped;
+ if (request instanceof HttpEntityEnclosingRequest) {
+ wrapped = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request);
+ } else {
+ wrapped = new RequestWrapper(request);
+ }
+ acceptEncodingInterceptor.process(wrapped, localContext);
+ final HttpResponse response = backend.execute(target, wrapped, localContext);
+ try {
+ contentEncodingInterceptor.process(response, localContext);
+ if (Boolean.TRUE.equals(localContext.getAttribute(ResponseContentEncoding.UNCOMPRESSED))) {
+ response.removeHeaders("Content-Length");
+ response.removeHeaders("Content-Encoding");
+ response.removeHeaders("Content-MD5");
+ }
+ return response;
+ } catch (final HttpException ex) {
+ EntityUtils.consume(response.getEntity());
+ throw ex;
+ } catch (final IOException ex) {
+ EntityUtils.consume(response.getEntity());
+ throw ex;
+ } catch (final RuntimeException ex) {
+ EntityUtils.consume(response.getEntity());
+ throw ex;
+ }
+ } catch (final HttpException e) {
+ throw new ClientProtocolException(e);
+ }
+ }
+
+ public T execute(final HttpUriRequest request,
+ final ResponseHandler extends T> responseHandler) throws IOException,
+ ClientProtocolException {
+ return execute(getHttpHost(request), request, responseHandler);
+ }
+
+ public T execute(final HttpUriRequest request,
+ final ResponseHandler extends T> responseHandler, final HttpContext context)
+ throws IOException, ClientProtocolException {
+ return execute(getHttpHost(request), request, responseHandler, context);
+ }
+
+ public T execute(final HttpHost target, final HttpRequest request,
+ final ResponseHandler extends T> responseHandler) throws IOException,
+ ClientProtocolException {
+ return execute(target, request, responseHandler, null);
+ }
+
+ public T execute(final HttpHost target, final HttpRequest request,
+ final ResponseHandler extends T> responseHandler, final HttpContext context)
+ throws IOException, ClientProtocolException {
+ final HttpResponse response = execute(target, request, context);
+ try {
+ return responseHandler.handleResponse(response);
+ } finally {
+ final HttpEntity entity = response.getEntity();
+ if (entity != null) {
+ EntityUtils.consume(entity);
+ }
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultBackoffStrategy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultBackoffStrategy.java
new file mode 100644
index 000000000..5a5e67caa
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultBackoffStrategy.java
@@ -0,0 +1,54 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.net.ConnectException;
+import java.net.SocketTimeoutException;
+
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.client.ConnectionBackoffStrategy;
+
+/**
+ * This {@link ConnectionBackoffStrategy} backs off either for a raw
+ * network socket or connection timeout or if the server explicitly
+ * sends a 503 (Service Unavailable) response.
+ *
+ * @since 4.2
+ */
+public class DefaultBackoffStrategy implements ConnectionBackoffStrategy {
+
+ public boolean shouldBackoff(final Throwable t) {
+ return (t instanceof SocketTimeoutException
+ || t instanceof ConnectException);
+ }
+
+ public boolean shouldBackoff(final HttpResponse resp) {
+ return (resp.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultConnectionKeepAliveStrategy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultConnectionKeepAliveStrategy.java
new file mode 100644
index 000000000..a5524bd43
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultConnectionKeepAliveStrategy.java
@@ -0,0 +1,71 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+import ch.boye.httpclientandroidlib.HeaderElement;
+import ch.boye.httpclientandroidlib.HeaderElementIterator;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.conn.ConnectionKeepAliveStrategy;
+import ch.boye.httpclientandroidlib.message.BasicHeaderElementIterator;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Default implementation of a strategy deciding duration
+ * that a connection can remain idle.
+ *
+ * The default implementation looks solely at the 'Keep-Alive'
+ * header's timeout token.
+ *
+ * @since 4.0
+ */
+@Immutable
+public class DefaultConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy {
+
+ public static final DefaultConnectionKeepAliveStrategy INSTANCE = new DefaultConnectionKeepAliveStrategy();
+
+ public long getKeepAliveDuration(final HttpResponse response, final HttpContext context) {
+ Args.notNull(response, "HTTP response");
+ final HeaderElementIterator it = new BasicHeaderElementIterator(
+ response.headerIterator(HTTP.CONN_KEEP_ALIVE));
+ while (it.hasNext()) {
+ final HeaderElement he = it.nextElement();
+ final String param = he.getName();
+ final String value = he.getValue();
+ if (value != null && param.equalsIgnoreCase("timeout")) {
+ try {
+ return Long.parseLong(value) * 1000;
+ } catch(final NumberFormatException ignore) {
+ }
+ }
+ }
+ return -1;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultHttpClient.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultHttpClient.java
new file mode 100644
index 000000000..55e5ab07e
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultHttpClient.java
@@ -0,0 +1,225 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import ch.boye.httpclientandroidlib.HttpVersion;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.client.protocol.RequestAddCookies;
+import ch.boye.httpclientandroidlib.client.protocol.RequestAuthCache;
+import ch.boye.httpclientandroidlib.client.protocol.RequestClientConnControl;
+import ch.boye.httpclientandroidlib.client.protocol.RequestDefaultHeaders;
+import ch.boye.httpclientandroidlib.client.protocol.RequestProxyAuthentication;
+import ch.boye.httpclientandroidlib.client.protocol.RequestTargetAuthentication;
+import ch.boye.httpclientandroidlib.client.protocol.ResponseProcessCookies;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
+import ch.boye.httpclientandroidlib.params.HttpConnectionParams;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.params.HttpProtocolParams;
+import ch.boye.httpclientandroidlib.params.SyncBasicHttpParams;
+import ch.boye.httpclientandroidlib.protocol.BasicHttpProcessor;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+import ch.boye.httpclientandroidlib.protocol.RequestContent;
+import ch.boye.httpclientandroidlib.protocol.RequestExpectContinue;
+import ch.boye.httpclientandroidlib.protocol.RequestTargetHost;
+import ch.boye.httpclientandroidlib.protocol.RequestUserAgent;
+
+/**
+ * Default implementation of {@link ch.boye.httpclientandroidlib.client.HttpClient} pre-configured
+ * for most common use scenarios.
+ *
+ * Please see the Javadoc for {@link #createHttpProcessor()} for the details of the interceptors
+ * that are set up by default.
+ *
+ * Additional interceptors can be added as follows, but
+ * take care not to add the same interceptor more than once.
+ *
+ */
+ public static void setDefaultHttpParams(final HttpParams params) {
+ HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
+ HttpProtocolParams.setContentCharset(params, HTTP.DEF_CONTENT_CHARSET.name());
+ HttpConnectionParams.setTcpNoDelay(params, true);
+ HttpConnectionParams.setSocketBufferSize(params, 8192);
+ HttpProtocolParams.setUserAgent(params, HttpClientBuilder.DEFAULT_USER_AGENT);
+ }
+
+ /**
+ * Create the processor with the following interceptors:
+ *
+ *
{@link RequestDefaultHeaders}
+ *
{@link RequestContent}
+ *
{@link RequestTargetHost}
+ *
{@link RequestClientConnControl}
+ *
{@link RequestUserAgent}
+ *
{@link RequestExpectContinue}
+ *
{@link RequestAddCookies}
+ *
{@link ResponseProcessCookies}
+ *
{@link RequestAuthCache}
+ *
{@link RequestTargetAuthentication}
+ *
{@link RequestProxyAuthentication}
+ *
+ *
+ * @return the processor with the added interceptors.
+ */
+ @Override
+ protected BasicHttpProcessor createHttpProcessor() {
+ final BasicHttpProcessor httpproc = new BasicHttpProcessor();
+ httpproc.addInterceptor(new RequestDefaultHeaders());
+ // Required protocol interceptors
+ httpproc.addInterceptor(new RequestContent());
+ httpproc.addInterceptor(new RequestTargetHost());
+ // Recommended protocol interceptors
+ httpproc.addInterceptor(new RequestClientConnControl());
+ httpproc.addInterceptor(new RequestUserAgent());
+ httpproc.addInterceptor(new RequestExpectContinue());
+ // HTTP state management interceptors
+ httpproc.addInterceptor(new RequestAddCookies());
+ httpproc.addInterceptor(new ResponseProcessCookies());
+ // HTTP authentication interceptors
+ httpproc.addInterceptor(new RequestAuthCache());
+ httpproc.addInterceptor(new RequestTargetAuthentication());
+ httpproc.addInterceptor(new RequestProxyAuthentication());
+ return httpproc;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultHttpRequestRetryHandler.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultHttpRequestRetryHandler.java
new file mode 100644
index 000000000..1721c8e70
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultHttpRequestRetryHandler.java
@@ -0,0 +1,203 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.ConnectException;
+import java.net.UnknownHostException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.net.ssl.SSLException;
+
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.HttpRequestRetryHandler;
+import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest;
+import ch.boye.httpclientandroidlib.client.protocol.HttpClientContext;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * The default {@link HttpRequestRetryHandler} used by request executors.
+ *
+ * @since 4.0
+ */
+@Immutable
+public class DefaultHttpRequestRetryHandler implements HttpRequestRetryHandler {
+
+ public static final DefaultHttpRequestRetryHandler INSTANCE = new DefaultHttpRequestRetryHandler();
+
+ /** the number of times a method will be retried */
+ private final int retryCount;
+
+ /** Whether or not methods that have successfully sent their request will be retried */
+ private final boolean requestSentRetryEnabled;
+
+ private final Set> nonRetriableClasses;
+
+ /**
+ * Create the request retry handler using the specified IOException classes
+ *
+ * @param retryCount how many times to retry; 0 means no retries
+ * @param requestSentRetryEnabled true if it's OK to retry requests that have been sent
+ * @param clazzes the IOException types that should not be retried
+ * @since 4.3
+ */
+ protected DefaultHttpRequestRetryHandler(
+ final int retryCount,
+ final boolean requestSentRetryEnabled,
+ final Collection> clazzes) {
+ super();
+ this.retryCount = retryCount;
+ this.requestSentRetryEnabled = requestSentRetryEnabled;
+ this.nonRetriableClasses = new HashSet>();
+ for (final Class extends IOException> clazz: clazzes) {
+ this.nonRetriableClasses.add(clazz);
+ }
+ }
+
+ /**
+ * Create the request retry handler using the following list of
+ * non-retriable IOException classes:
+ *
+ *
InterruptedIOException
+ *
UnknownHostException
+ *
ConnectException
+ *
SSLException
+ *
+ * @param retryCount how many times to retry; 0 means no retries
+ * @param requestSentRetryEnabled true if it's OK to retry requests that have been sent
+ */
+ @SuppressWarnings("unchecked")
+ public DefaultHttpRequestRetryHandler(final int retryCount, final boolean requestSentRetryEnabled) {
+ this(retryCount, requestSentRetryEnabled, Arrays.asList(
+ InterruptedIOException.class,
+ UnknownHostException.class,
+ ConnectException.class,
+ SSLException.class));
+ }
+
+ /**
+ * Create the request retry handler with a retry count of 3, requestSentRetryEnabled false
+ * and using the following list of non-retriable IOException classes:
+ *
+ *
InterruptedIOException
+ *
UnknownHostException
+ *
ConnectException
+ *
SSLException
+ *
+ */
+ public DefaultHttpRequestRetryHandler() {
+ this(3, false);
+ }
+ /**
+ * Used retryCount and requestSentRetryEnabled to determine
+ * if the given method should be retried.
+ */
+ public boolean retryRequest(
+ final IOException exception,
+ final int executionCount,
+ final HttpContext context) {
+ Args.notNull(exception, "Exception parameter");
+ Args.notNull(context, "HTTP context");
+ if (executionCount > this.retryCount) {
+ // Do not retry if over max retry count
+ return false;
+ }
+ if (this.nonRetriableClasses.contains(exception.getClass())) {
+ return false;
+ } else {
+ for (final Class extends IOException> rejectException : this.nonRetriableClasses) {
+ if (rejectException.isInstance(exception)) {
+ return false;
+ }
+ }
+ }
+ final HttpClientContext clientContext = HttpClientContext.adapt(context);
+ final HttpRequest request = clientContext.getRequest();
+
+ if(requestIsAborted(request)){
+ return false;
+ }
+
+ if (handleAsIdempotent(request)) {
+ // Retry if the request is considered idempotent
+ return true;
+ }
+
+ if (!clientContext.isRequestSent() || this.requestSentRetryEnabled) {
+ // Retry if the request has not been sent fully or
+ // if it's OK to retry methods that have been sent
+ return true;
+ }
+ // otherwise do not retry
+ return false;
+ }
+
+ /**
+ * @return true if this handler will retry methods that have
+ * successfully sent their request, false otherwise
+ */
+ public boolean isRequestSentRetryEnabled() {
+ return requestSentRetryEnabled;
+ }
+
+ /**
+ * @return the maximum number of times a method will be retried
+ */
+ public int getRetryCount() {
+ return retryCount;
+ }
+
+ /**
+ * @since 4.2
+ */
+ protected boolean handleAsIdempotent(final HttpRequest request) {
+ return !(request instanceof HttpEntityEnclosingRequest);
+ }
+
+ /**
+ * @since 4.2
+ *
+ * @deprecated (4.3)
+ */
+ @Deprecated
+ protected boolean requestIsAborted(final HttpRequest request) {
+ HttpRequest req = request;
+ if (request instanceof RequestWrapper) { // does not forward request to original
+ req = ((RequestWrapper) request).getOriginal();
+ }
+ return (req instanceof HttpUriRequest && ((HttpUriRequest)req).isAborted());
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultProxyAuthenticationHandler.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultProxyAuthenticationHandler.java
new file mode 100644
index 000000000..a70057ae5
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultProxyAuthenticationHandler.java
@@ -0,0 +1,90 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.util.List;
+import java.util.Map;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.auth.AUTH;
+import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
+import ch.boye.httpclientandroidlib.auth.params.AuthPNames;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Default {@link ch.boye.httpclientandroidlib.client.AuthenticationHandler} implementation
+ * for proxy host authentication.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.2) use {@link ProxyAuthenticationStrategy}
+ */
+@Deprecated
+@Immutable
+public class DefaultProxyAuthenticationHandler extends AbstractAuthenticationHandler {
+
+ public DefaultProxyAuthenticationHandler() {
+ super();
+ }
+
+ public boolean isAuthenticationRequested(
+ final HttpResponse response,
+ final HttpContext context) {
+ Args.notNull(response, "HTTP response");
+ final int status = response.getStatusLine().getStatusCode();
+ return status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED;
+ }
+
+ public Map getChallenges(
+ final HttpResponse response,
+ final HttpContext context) throws MalformedChallengeException {
+ Args.notNull(response, "HTTP response");
+ final Header[] headers = response.getHeaders(AUTH.PROXY_AUTH);
+ return parseChallenges(headers);
+ }
+
+ @Override
+ protected List getAuthPreferences(
+ final HttpResponse response,
+ final HttpContext context) {
+ @SuppressWarnings("unchecked")
+ final
+ List authpref = (List) response.getParams().getParameter(
+ AuthPNames.PROXY_AUTH_PREF);
+ if (authpref != null) {
+ return authpref;
+ } else {
+ return super.getAuthPreferences(response, context);
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultRedirectHandler.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultRedirectHandler.java
new file mode 100644
index 000000000..6bd58c035
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultRedirectHandler.java
@@ -0,0 +1,180 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.ProtocolException;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.CircularRedirectException;
+import ch.boye.httpclientandroidlib.client.RedirectHandler;
+import ch.boye.httpclientandroidlib.client.methods.HttpGet;
+import ch.boye.httpclientandroidlib.client.methods.HttpHead;
+import ch.boye.httpclientandroidlib.client.params.ClientPNames;
+import ch.boye.httpclientandroidlib.client.utils.URIUtils;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.ExecutionContext;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.Asserts;
+
+/**
+ * Default implementation of {@link RedirectHandler}.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.1) use {@link DefaultRedirectStrategy}.
+ */
+@Immutable
+@Deprecated
+public class DefaultRedirectHandler implements RedirectHandler {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ private static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations";
+
+ public DefaultRedirectHandler() {
+ super();
+ }
+
+ public boolean isRedirectRequested(
+ final HttpResponse response,
+ final HttpContext context) {
+ Args.notNull(response, "HTTP response");
+
+ final int statusCode = response.getStatusLine().getStatusCode();
+ switch (statusCode) {
+ case HttpStatus.SC_MOVED_TEMPORARILY:
+ case HttpStatus.SC_MOVED_PERMANENTLY:
+ case HttpStatus.SC_TEMPORARY_REDIRECT:
+ final HttpRequest request = (HttpRequest) context.getAttribute(
+ ExecutionContext.HTTP_REQUEST);
+ final String method = request.getRequestLine().getMethod();
+ return method.equalsIgnoreCase(HttpGet.METHOD_NAME)
+ || method.equalsIgnoreCase(HttpHead.METHOD_NAME);
+ case HttpStatus.SC_SEE_OTHER:
+ return true;
+ default:
+ return false;
+ } //end of switch
+ }
+
+ public URI getLocationURI(
+ final HttpResponse response,
+ final HttpContext context) throws ProtocolException {
+ Args.notNull(response, "HTTP response");
+ //get the location header to find out where to redirect to
+ final Header locationHeader = response.getFirstHeader("location");
+ if (locationHeader == null) {
+ // got a redirect response, but no location header
+ throw new ProtocolException(
+ "Received redirect response " + response.getStatusLine()
+ + " but no location header");
+ }
+ final String location = locationHeader.getValue();
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Redirect requested to location '" + location + "'");
+ }
+
+ URI uri;
+ try {
+ uri = new URI(location);
+ } catch (final URISyntaxException ex) {
+ throw new ProtocolException("Invalid redirect URI: " + location, ex);
+ }
+
+ final HttpParams params = response.getParams();
+ // rfc2616 demands the location value be a complete URI
+ // Location = "Location" ":" absoluteURI
+ if (!uri.isAbsolute()) {
+ if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
+ throw new ProtocolException("Relative redirect location '"
+ + uri + "' not allowed");
+ }
+ // Adjust location URI
+ final HttpHost target = (HttpHost) context.getAttribute(
+ ExecutionContext.HTTP_TARGET_HOST);
+ Asserts.notNull(target, "Target host");
+
+ final HttpRequest request = (HttpRequest) context.getAttribute(
+ ExecutionContext.HTTP_REQUEST);
+
+ try {
+ final URI requestURI = new URI(request.getRequestLine().getUri());
+ final URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
+ uri = URIUtils.resolve(absoluteRequestURI, uri);
+ } catch (final URISyntaxException ex) {
+ throw new ProtocolException(ex.getMessage(), ex);
+ }
+ }
+
+ if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {
+
+ RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(
+ REDIRECT_LOCATIONS);
+
+ if (redirectLocations == null) {
+ redirectLocations = new RedirectLocations();
+ context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
+ }
+
+ final URI redirectURI;
+ if (uri.getFragment() != null) {
+ try {
+ final HttpHost target = new HttpHost(
+ uri.getHost(),
+ uri.getPort(),
+ uri.getScheme());
+ redirectURI = URIUtils.rewriteURI(uri, target, true);
+ } catch (final URISyntaxException ex) {
+ throw new ProtocolException(ex.getMessage(), ex);
+ }
+ } else {
+ redirectURI = uri;
+ }
+
+ if (redirectLocations.contains(redirectURI)) {
+ throw new CircularRedirectException("Circular redirect to '" +
+ redirectURI + "'");
+ } else {
+ redirectLocations.add(redirectURI);
+ }
+ }
+
+ return uri;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultRedirectStrategy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultRedirectStrategy.java
new file mode 100644
index 000000000..e7d9315d2
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultRedirectStrategy.java
@@ -0,0 +1,233 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Locale;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.ProtocolException;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.CircularRedirectException;
+import ch.boye.httpclientandroidlib.client.RedirectStrategy;
+import ch.boye.httpclientandroidlib.client.config.RequestConfig;
+import ch.boye.httpclientandroidlib.client.methods.HttpGet;
+import ch.boye.httpclientandroidlib.client.methods.HttpHead;
+import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest;
+import ch.boye.httpclientandroidlib.client.methods.RequestBuilder;
+import ch.boye.httpclientandroidlib.client.protocol.HttpClientContext;
+import ch.boye.httpclientandroidlib.client.utils.URIBuilder;
+import ch.boye.httpclientandroidlib.client.utils.URIUtils;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.Asserts;
+import ch.boye.httpclientandroidlib.util.TextUtils;
+
+/**
+ * Default implementation of {@link RedirectStrategy}. This strategy honors the restrictions
+ * on automatic redirection of entity enclosing methods such as POST and PUT imposed by the
+ * HTTP specification. 302 Moved Temporarily, 301 Moved Permanently and
+ * 307 Temporary Redirect status codes will result in an automatic redirect of
+ * HEAD and GET methods only. POST and PUT methods will not be automatically redirected
+ * as requiring user confirmation.
+ *
+ * The restriction on automatic redirection of POST methods can be relaxed by using
+ * {@link LaxRedirectStrategy} instead of {@link DefaultRedirectStrategy}.
+ *
+ * @see LaxRedirectStrategy
+ * @since 4.1
+ */
+@Immutable
+public class DefaultRedirectStrategy implements RedirectStrategy {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ /**
+ * @deprecated (4.3) use {@link ch.boye.httpclientandroidlib.client.protocol.HttpClientContext#REDIRECT_LOCATIONS}.
+ */
+ @Deprecated
+ public static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations";
+
+ public static final DefaultRedirectStrategy INSTANCE = new DefaultRedirectStrategy();
+
+ /**
+ * Redirectable methods.
+ */
+ private static final String[] REDIRECT_METHODS = new String[] {
+ HttpGet.METHOD_NAME,
+ HttpHead.METHOD_NAME
+ };
+
+ public DefaultRedirectStrategy() {
+ super();
+ }
+
+ public boolean isRedirected(
+ final HttpRequest request,
+ final HttpResponse response,
+ final HttpContext context) throws ProtocolException {
+ Args.notNull(request, "HTTP request");
+ Args.notNull(response, "HTTP response");
+
+ final int statusCode = response.getStatusLine().getStatusCode();
+ final String method = request.getRequestLine().getMethod();
+ final Header locationHeader = response.getFirstHeader("location");
+ switch (statusCode) {
+ case HttpStatus.SC_MOVED_TEMPORARILY:
+ return isRedirectable(method) && locationHeader != null;
+ case HttpStatus.SC_MOVED_PERMANENTLY:
+ case HttpStatus.SC_TEMPORARY_REDIRECT:
+ return isRedirectable(method);
+ case HttpStatus.SC_SEE_OTHER:
+ return true;
+ default:
+ return false;
+ } //end of switch
+ }
+
+ public URI getLocationURI(
+ final HttpRequest request,
+ final HttpResponse response,
+ final HttpContext context) throws ProtocolException {
+ Args.notNull(request, "HTTP request");
+ Args.notNull(response, "HTTP response");
+ Args.notNull(context, "HTTP context");
+
+ final HttpClientContext clientContext = HttpClientContext.adapt(context);
+
+ //get the location header to find out where to redirect to
+ final Header locationHeader = response.getFirstHeader("location");
+ if (locationHeader == null) {
+ // got a redirect response, but no location header
+ throw new ProtocolException(
+ "Received redirect response " + response.getStatusLine()
+ + " but no location header");
+ }
+ final String location = locationHeader.getValue();
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Redirect requested to location '" + location + "'");
+ }
+
+ final RequestConfig config = clientContext.getRequestConfig();
+
+ URI uri = createLocationURI(location);
+
+ // rfc2616 demands the location value be a complete URI
+ // Location = "Location" ":" absoluteURI
+ try {
+ if (!uri.isAbsolute()) {
+ if (!config.isRelativeRedirectsAllowed()) {
+ throw new ProtocolException("Relative redirect location '"
+ + uri + "' not allowed");
+ }
+ // Adjust location URI
+ final HttpHost target = clientContext.getTargetHost();
+ Asserts.notNull(target, "Target host");
+ final URI requestURI = new URI(request.getRequestLine().getUri());
+ final URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, false);
+ uri = URIUtils.resolve(absoluteRequestURI, uri);
+ }
+ } catch (final URISyntaxException ex) {
+ throw new ProtocolException(ex.getMessage(), ex);
+ }
+
+ RedirectLocations redirectLocations = (RedirectLocations) clientContext.getAttribute(
+ HttpClientContext.REDIRECT_LOCATIONS);
+ if (redirectLocations == null) {
+ redirectLocations = new RedirectLocations();
+ context.setAttribute(HttpClientContext.REDIRECT_LOCATIONS, redirectLocations);
+ }
+ if (!config.isCircularRedirectsAllowed()) {
+ if (redirectLocations.contains(uri)) {
+ throw new CircularRedirectException("Circular redirect to '" + uri + "'");
+ }
+ }
+ redirectLocations.add(uri);
+ return uri;
+ }
+
+ /**
+ * @since 4.1
+ */
+ protected URI createLocationURI(final String location) throws ProtocolException {
+ try {
+ final URIBuilder b = new URIBuilder(new URI(location).normalize());
+ final String host = b.getHost();
+ if (host != null) {
+ b.setHost(host.toLowerCase(Locale.ENGLISH));
+ }
+ final String path = b.getPath();
+ if (TextUtils.isEmpty(path)) {
+ b.setPath("/");
+ }
+ return b.build();
+ } catch (final URISyntaxException ex) {
+ throw new ProtocolException("Invalid redirect URI: " + location, ex);
+ }
+ }
+
+ /**
+ * @since 4.2
+ */
+ protected boolean isRedirectable(final String method) {
+ for (final String m: REDIRECT_METHODS) {
+ if (m.equalsIgnoreCase(method)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public HttpUriRequest getRedirect(
+ final HttpRequest request,
+ final HttpResponse response,
+ final HttpContext context) throws ProtocolException {
+ final URI uri = getLocationURI(request, response, context);
+ final String method = request.getRequestLine().getMethod();
+ if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
+ return new HttpHead(uri);
+ } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
+ return new HttpGet(uri);
+ } else {
+ final int status = response.getStatusLine().getStatusCode();
+ if (status == HttpStatus.SC_TEMPORARY_REDIRECT) {
+ return RequestBuilder.copy(request).setUri(uri).build();
+ } else {
+ return new HttpGet(uri);
+ }
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultRedirectStrategyAdaptor.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultRedirectStrategyAdaptor.java
new file mode 100644
index 000000000..b49fb7f73
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultRedirectStrategyAdaptor.java
@@ -0,0 +1,81 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.net.URI;
+
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.ProtocolException;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.RedirectHandler;
+import ch.boye.httpclientandroidlib.client.RedirectStrategy;
+import ch.boye.httpclientandroidlib.client.methods.HttpGet;
+import ch.boye.httpclientandroidlib.client.methods.HttpHead;
+import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+/**
+ * @deprecated (4.1) do not use
+ */
+@Immutable
+@Deprecated
+class DefaultRedirectStrategyAdaptor implements RedirectStrategy {
+
+ private final RedirectHandler handler;
+
+ public DefaultRedirectStrategyAdaptor(final RedirectHandler handler) {
+ super();
+ this.handler = handler;
+ }
+
+ public boolean isRedirected(
+ final HttpRequest request,
+ final HttpResponse response,
+ final HttpContext context) throws ProtocolException {
+ return this.handler.isRedirectRequested(response, context);
+ }
+
+ public HttpUriRequest getRedirect(
+ final HttpRequest request,
+ final HttpResponse response,
+ final HttpContext context) throws ProtocolException {
+ final URI uri = this.handler.getLocationURI(response, context);
+ final String method = request.getRequestLine().getMethod();
+ if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
+ return new HttpHead(uri);
+ } else {
+ return new HttpGet(uri);
+ }
+ }
+
+ public RedirectHandler getHandler() {
+ return this.handler;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultRequestDirector.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultRequestDirector.java
new file mode 100644
index 000000000..03d9e1e5f
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultRequestDirector.java
@@ -0,0 +1,1150 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.concurrent.TimeUnit;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.ConnectionReuseStrategy;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.NoHttpResponseException;
+import ch.boye.httpclientandroidlib.ProtocolException;
+import ch.boye.httpclientandroidlib.ProtocolVersion;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.auth.AuthProtocolState;
+import ch.boye.httpclientandroidlib.auth.AuthScheme;
+import ch.boye.httpclientandroidlib.auth.AuthState;
+import ch.boye.httpclientandroidlib.auth.UsernamePasswordCredentials;
+import ch.boye.httpclientandroidlib.client.AuthenticationHandler;
+import ch.boye.httpclientandroidlib.client.AuthenticationStrategy;
+import ch.boye.httpclientandroidlib.client.HttpRequestRetryHandler;
+import ch.boye.httpclientandroidlib.client.NonRepeatableRequestException;
+import ch.boye.httpclientandroidlib.client.RedirectException;
+import ch.boye.httpclientandroidlib.client.RedirectHandler;
+import ch.boye.httpclientandroidlib.client.RedirectStrategy;
+import ch.boye.httpclientandroidlib.client.RequestDirector;
+import ch.boye.httpclientandroidlib.client.UserTokenHandler;
+import ch.boye.httpclientandroidlib.client.methods.AbortableHttpRequest;
+import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest;
+import ch.boye.httpclientandroidlib.client.params.ClientPNames;
+import ch.boye.httpclientandroidlib.client.params.HttpClientParams;
+import ch.boye.httpclientandroidlib.client.protocol.ClientContext;
+import ch.boye.httpclientandroidlib.client.utils.URIUtils;
+import ch.boye.httpclientandroidlib.conn.BasicManagedEntity;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionRequest;
+import ch.boye.httpclientandroidlib.conn.ConnectionKeepAliveStrategy;
+import ch.boye.httpclientandroidlib.conn.ManagedClientConnection;
+import ch.boye.httpclientandroidlib.conn.routing.BasicRouteDirector;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRouteDirector;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoutePlanner;
+import ch.boye.httpclientandroidlib.conn.scheme.Scheme;
+import ch.boye.httpclientandroidlib.entity.BufferedHttpEntity;
+import ch.boye.httpclientandroidlib.impl.auth.BasicScheme;
+import ch.boye.httpclientandroidlib.impl.conn.ConnectionShutdownException;
+import ch.boye.httpclientandroidlib.message.BasicHttpRequest;
+import ch.boye.httpclientandroidlib.params.HttpConnectionParams;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.params.HttpProtocolParams;
+import ch.boye.httpclientandroidlib.protocol.ExecutionContext;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.protocol.HttpProcessor;
+import ch.boye.httpclientandroidlib.protocol.HttpRequestExecutor;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.EntityUtils;
+
+/**
+ * Default implementation of {@link RequestDirector}.
+ *
+ * The following parameters can be used to customize the behavior of this
+ * class:
+ *
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3)
+ */
+@Deprecated
+@NotThreadSafe // e.g. managedConn
+public class DefaultRequestDirector implements RequestDirector {
+
+ public HttpClientAndroidLog log;
+
+ /** The connection manager. */
+ protected final ClientConnectionManager connManager;
+
+ /** The route planner. */
+ protected final HttpRoutePlanner routePlanner;
+
+ /** The connection re-use strategy. */
+ protected final ConnectionReuseStrategy reuseStrategy;
+
+ /** The keep-alive duration strategy. */
+ protected final ConnectionKeepAliveStrategy keepAliveStrategy;
+
+ /** The request executor. */
+ protected final HttpRequestExecutor requestExec;
+
+ /** The HTTP protocol processor. */
+ protected final HttpProcessor httpProcessor;
+
+ /** The request retry handler. */
+ protected final HttpRequestRetryHandler retryHandler;
+
+ /** The redirect handler. */
+ @Deprecated
+ protected final RedirectHandler redirectHandler;
+
+ /** The redirect strategy. */
+ protected final RedirectStrategy redirectStrategy;
+
+ /** The target authentication handler. */
+ @Deprecated
+ protected final AuthenticationHandler targetAuthHandler;
+
+ /** The target authentication handler. */
+ protected final AuthenticationStrategy targetAuthStrategy;
+
+ /** The proxy authentication handler. */
+ @Deprecated
+ protected final AuthenticationHandler proxyAuthHandler;
+
+ /** The proxy authentication handler. */
+ protected final AuthenticationStrategy proxyAuthStrategy;
+
+ /** The user token handler. */
+ protected final UserTokenHandler userTokenHandler;
+
+ /** The HTTP parameters. */
+ protected final HttpParams params;
+
+ /** The currently allocated connection. */
+ protected ManagedClientConnection managedConn;
+
+ protected final AuthState targetAuthState;
+
+ protected final AuthState proxyAuthState;
+
+ private final HttpAuthenticator authenticator;
+
+ private int execCount;
+
+ private int redirectCount;
+
+ private final int maxRedirects;
+
+ private HttpHost virtualHost;
+
+ @Deprecated
+ public DefaultRequestDirector(
+ final HttpRequestExecutor requestExec,
+ final ClientConnectionManager conman,
+ final ConnectionReuseStrategy reustrat,
+ final ConnectionKeepAliveStrategy kastrat,
+ final HttpRoutePlanner rouplan,
+ final HttpProcessor httpProcessor,
+ final HttpRequestRetryHandler retryHandler,
+ final RedirectHandler redirectHandler,
+ final AuthenticationHandler targetAuthHandler,
+ final AuthenticationHandler proxyAuthHandler,
+ final UserTokenHandler userTokenHandler,
+ final HttpParams params) {
+ this(new HttpClientAndroidLog(DefaultRequestDirector.class),
+ requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler,
+ new DefaultRedirectStrategyAdaptor(redirectHandler),
+ new AuthenticationStrategyAdaptor(targetAuthHandler),
+ new AuthenticationStrategyAdaptor(proxyAuthHandler),
+ userTokenHandler,
+ params);
+ }
+
+
+ @Deprecated
+ public DefaultRequestDirector(
+ final HttpClientAndroidLog log,
+ final HttpRequestExecutor requestExec,
+ final ClientConnectionManager conman,
+ final ConnectionReuseStrategy reustrat,
+ final ConnectionKeepAliveStrategy kastrat,
+ final HttpRoutePlanner rouplan,
+ final HttpProcessor httpProcessor,
+ final HttpRequestRetryHandler retryHandler,
+ final RedirectStrategy redirectStrategy,
+ final AuthenticationHandler targetAuthHandler,
+ final AuthenticationHandler proxyAuthHandler,
+ final UserTokenHandler userTokenHandler,
+ final HttpParams params) {
+ this(new HttpClientAndroidLog(DefaultRequestDirector.class),
+ requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler,
+ redirectStrategy,
+ new AuthenticationStrategyAdaptor(targetAuthHandler),
+ new AuthenticationStrategyAdaptor(proxyAuthHandler),
+ userTokenHandler,
+ params);
+ }
+
+ /**
+ * @since 4.2
+ */
+ public DefaultRequestDirector(
+ final HttpClientAndroidLog log,
+ final HttpRequestExecutor requestExec,
+ final ClientConnectionManager conman,
+ final ConnectionReuseStrategy reustrat,
+ final ConnectionKeepAliveStrategy kastrat,
+ final HttpRoutePlanner rouplan,
+ final HttpProcessor httpProcessor,
+ final HttpRequestRetryHandler retryHandler,
+ final RedirectStrategy redirectStrategy,
+ final AuthenticationStrategy targetAuthStrategy,
+ final AuthenticationStrategy proxyAuthStrategy,
+ final UserTokenHandler userTokenHandler,
+ final HttpParams params) {
+
+ Args.notNull(log, "Log");
+ Args.notNull(requestExec, "Request executor");
+ Args.notNull(conman, "Client connection manager");
+ Args.notNull(reustrat, "Connection reuse strategy");
+ Args.notNull(kastrat, "Connection keep alive strategy");
+ Args.notNull(rouplan, "Route planner");
+ Args.notNull(httpProcessor, "HTTP protocol processor");
+ Args.notNull(retryHandler, "HTTP request retry handler");
+ Args.notNull(redirectStrategy, "Redirect strategy");
+ Args.notNull(targetAuthStrategy, "Target authentication strategy");
+ Args.notNull(proxyAuthStrategy, "Proxy authentication strategy");
+ Args.notNull(userTokenHandler, "User token handler");
+ Args.notNull(params, "HTTP parameters");
+ this.log = log;
+ this.authenticator = new HttpAuthenticator(log);
+ this.requestExec = requestExec;
+ this.connManager = conman;
+ this.reuseStrategy = reustrat;
+ this.keepAliveStrategy = kastrat;
+ this.routePlanner = rouplan;
+ this.httpProcessor = httpProcessor;
+ this.retryHandler = retryHandler;
+ this.redirectStrategy = redirectStrategy;
+ this.targetAuthStrategy = targetAuthStrategy;
+ this.proxyAuthStrategy = proxyAuthStrategy;
+ this.userTokenHandler = userTokenHandler;
+ this.params = params;
+
+ if (redirectStrategy instanceof DefaultRedirectStrategyAdaptor) {
+ this.redirectHandler = ((DefaultRedirectStrategyAdaptor) redirectStrategy).getHandler();
+ } else {
+ this.redirectHandler = null;
+ }
+ if (targetAuthStrategy instanceof AuthenticationStrategyAdaptor) {
+ this.targetAuthHandler = ((AuthenticationStrategyAdaptor) targetAuthStrategy).getHandler();
+ } else {
+ this.targetAuthHandler = null;
+ }
+ if (proxyAuthStrategy instanceof AuthenticationStrategyAdaptor) {
+ this.proxyAuthHandler = ((AuthenticationStrategyAdaptor) proxyAuthStrategy).getHandler();
+ } else {
+ this.proxyAuthHandler = null;
+ }
+
+ this.managedConn = null;
+
+ this.execCount = 0;
+ this.redirectCount = 0;
+ this.targetAuthState = new AuthState();
+ this.proxyAuthState = new AuthState();
+ this.maxRedirects = this.params.getIntParameter(ClientPNames.MAX_REDIRECTS, 100);
+ }
+
+
+ private RequestWrapper wrapRequest(
+ final HttpRequest request) throws ProtocolException {
+ if (request instanceof HttpEntityEnclosingRequest) {
+ return new EntityEnclosingRequestWrapper(
+ (HttpEntityEnclosingRequest) request);
+ } else {
+ return new RequestWrapper(
+ request);
+ }
+ }
+
+
+ protected void rewriteRequestURI(
+ final RequestWrapper request,
+ final HttpRoute route) throws ProtocolException {
+ try {
+
+ URI uri = request.getURI();
+ if (route.getProxyHost() != null && !route.isTunnelled()) {
+ // Make sure the request URI is absolute
+ if (!uri.isAbsolute()) {
+ final HttpHost target = route.getTargetHost();
+ uri = URIUtils.rewriteURI(uri, target, true);
+ } else {
+ uri = URIUtils.rewriteURI(uri);
+ }
+ } else {
+ // Make sure the request URI is relative
+ if (uri.isAbsolute()) {
+ uri = URIUtils.rewriteURI(uri, null, true);
+ } else {
+ uri = URIUtils.rewriteURI(uri);
+ }
+ }
+ request.setURI(uri);
+
+ } catch (final URISyntaxException ex) {
+ throw new ProtocolException("Invalid URI: " +
+ request.getRequestLine().getUri(), ex);
+ }
+ }
+
+
+ // non-javadoc, see interface ClientRequestDirector
+ public HttpResponse execute(final HttpHost targetHost, final HttpRequest request,
+ final HttpContext context)
+ throws HttpException, IOException {
+
+ context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState);
+ context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);
+
+ HttpHost target = targetHost;
+
+ final HttpRequest orig = request;
+ final RequestWrapper origWrapper = wrapRequest(orig);
+ origWrapper.setParams(params);
+ final HttpRoute origRoute = determineRoute(target, origWrapper, context);
+
+ virtualHost = (HttpHost) origWrapper.getParams().getParameter(ClientPNames.VIRTUAL_HOST);
+
+ // HTTPCLIENT-1092 - add the port if necessary
+ if (virtualHost != null && virtualHost.getPort() == -1) {
+ final HttpHost host = (target != null) ? target : origRoute.getTargetHost();
+ final int port = host.getPort();
+ if (port != -1){
+ virtualHost = new HttpHost(virtualHost.getHostName(), port, virtualHost.getSchemeName());
+ }
+ }
+
+ RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute);
+
+ boolean reuse = false;
+ boolean done = false;
+ try {
+ HttpResponse response = null;
+ while (!done) {
+ // In this loop, the RoutedRequest may be replaced by a
+ // followup request and route. The request and route passed
+ // in the method arguments will be replaced. The original
+ // request is still available in 'orig'.
+
+ final RequestWrapper wrapper = roureq.getRequest();
+ final HttpRoute route = roureq.getRoute();
+ response = null;
+
+ // See if we have a user token bound to the execution context
+ Object userToken = context.getAttribute(ClientContext.USER_TOKEN);
+
+ // Allocate connection if needed
+ if (managedConn == null) {
+ final ClientConnectionRequest connRequest = connManager.requestConnection(
+ route, userToken);
+ if (orig instanceof AbortableHttpRequest) {
+ ((AbortableHttpRequest) orig).setConnectionRequest(connRequest);
+ }
+
+ final long timeout = HttpClientParams.getConnectionManagerTimeout(params);
+ try {
+ managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
+ } catch(final InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException();
+ }
+
+ if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
+ // validate connection
+ if (managedConn.isOpen()) {
+ this.log.debug("Stale connection check");
+ if (managedConn.isStale()) {
+ this.log.debug("Stale connection detected");
+ managedConn.close();
+ }
+ }
+ }
+ }
+
+ if (orig instanceof AbortableHttpRequest) {
+ ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn);
+ }
+
+ try {
+ tryConnect(roureq, context);
+ } catch (final TunnelRefusedException ex) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug(ex.getMessage());
+ }
+ response = ex.getResponse();
+ break;
+ }
+
+ final String userinfo = wrapper.getURI().getUserInfo();
+ if (userinfo != null) {
+ targetAuthState.update(
+ new BasicScheme(), new UsernamePasswordCredentials(userinfo));
+ }
+
+ // Get target. Even if there's virtual host, we may need the target to set the port.
+ if (virtualHost != null) {
+ target = virtualHost;
+ } else {
+ final URI requestURI = wrapper.getURI();
+ if (requestURI.isAbsolute()) {
+ target = URIUtils.extractHost(requestURI);
+ }
+ }
+ if (target == null) {
+ target = route.getTargetHost();
+ }
+
+ // Reset headers on the request wrapper
+ wrapper.resetHeaders();
+ // Re-write request URI if needed
+ rewriteRequestURI(wrapper, route);
+
+ // Populate the execution context
+ context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
+ context.setAttribute(ClientContext.ROUTE, route);
+ context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);
+
+ // Run request protocol interceptors
+ requestExec.preProcess(wrapper, httpProcessor, context);
+
+ response = tryExecute(roureq, context);
+ if (response == null) {
+ // Need to start over
+ continue;
+ }
+
+ // Run response protocol interceptors
+ response.setParams(params);
+ requestExec.postProcess(response, httpProcessor, context);
+
+
+ // The connection is in or can be brought to a re-usable state.
+ reuse = reuseStrategy.keepAlive(response, context);
+ if (reuse) {
+ // Set the idle duration of this connection
+ final long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
+ if (this.log.isDebugEnabled()) {
+ final String s;
+ if (duration > 0) {
+ s = "for " + duration + " " + TimeUnit.MILLISECONDS;
+ } else {
+ s = "indefinitely";
+ }
+ this.log.debug("Connection can be kept alive " + s);
+ }
+ managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);
+ }
+
+ final RoutedRequest followup = handleResponse(roureq, response, context);
+ if (followup == null) {
+ done = true;
+ } else {
+ if (reuse) {
+ // Make sure the response body is fully consumed, if present
+ final HttpEntity entity = response.getEntity();
+ EntityUtils.consume(entity);
+ // entity consumed above is not an auto-release entity,
+ // need to mark the connection re-usable explicitly
+ managedConn.markReusable();
+ } else {
+ managedConn.close();
+ if (proxyAuthState.getState().compareTo(AuthProtocolState.CHALLENGED) > 0
+ && proxyAuthState.getAuthScheme() != null
+ && proxyAuthState.getAuthScheme().isConnectionBased()) {
+ this.log.debug("Resetting proxy auth state");
+ proxyAuthState.reset();
+ }
+ if (targetAuthState.getState().compareTo(AuthProtocolState.CHALLENGED) > 0
+ && targetAuthState.getAuthScheme() != null
+ && targetAuthState.getAuthScheme().isConnectionBased()) {
+ this.log.debug("Resetting target auth state");
+ targetAuthState.reset();
+ }
+ }
+ // check if we can use the same connection for the followup
+ if (!followup.getRoute().equals(roureq.getRoute())) {
+ releaseConnection();
+ }
+ roureq = followup;
+ }
+
+ if (managedConn != null) {
+ if (userToken == null) {
+ userToken = userTokenHandler.getUserToken(context);
+ context.setAttribute(ClientContext.USER_TOKEN, userToken);
+ }
+ if (userToken != null) {
+ managedConn.setState(userToken);
+ }
+ }
+
+ } // while not done
+
+
+ // check for entity, release connection if possible
+ if ((response == null) || (response.getEntity() == null) ||
+ !response.getEntity().isStreaming()) {
+ // connection not needed and (assumed to be) in re-usable state
+ if (reuse) {
+ managedConn.markReusable();
+ }
+ releaseConnection();
+ } else {
+ // install an auto-release entity
+ HttpEntity entity = response.getEntity();
+ entity = new BasicManagedEntity(entity, managedConn, reuse);
+ response.setEntity(entity);
+ }
+
+ return response;
+
+ } catch (final ConnectionShutdownException ex) {
+ final InterruptedIOException ioex = new InterruptedIOException(
+ "Connection has been shut down");
+ ioex.initCause(ex);
+ throw ioex;
+ } catch (final HttpException ex) {
+ abortConnection();
+ throw ex;
+ } catch (final IOException ex) {
+ abortConnection();
+ throw ex;
+ } catch (final RuntimeException ex) {
+ abortConnection();
+ throw ex;
+ }
+ } // execute
+
+ /**
+ * Establish connection either directly or through a tunnel and retry in case of
+ * a recoverable I/O failure
+ */
+ private void tryConnect(
+ final RoutedRequest req, final HttpContext context) throws HttpException, IOException {
+ final HttpRoute route = req.getRoute();
+ final HttpRequest wrapper = req.getRequest();
+
+ int connectCount = 0;
+ for (;;) {
+ context.setAttribute(ExecutionContext.HTTP_REQUEST, wrapper);
+ // Increment connect count
+ connectCount++;
+ try {
+ if (!managedConn.isOpen()) {
+ managedConn.open(route, context, params);
+ } else {
+ managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
+ }
+ establishRoute(route, context);
+ break;
+ } catch (final IOException ex) {
+ try {
+ managedConn.close();
+ } catch (final IOException ignore) {
+ }
+ if (retryHandler.retryRequest(ex, connectCount, context)) {
+ if (this.log.isInfoEnabled()) {
+ this.log.info("I/O exception ("+ ex.getClass().getName() +
+ ") caught when connecting to "
+ + route +
+ ": "
+ + ex.getMessage());
+ if (this.log.isDebugEnabled()) {
+ this.log.debug(ex.getMessage(), ex);
+ }
+ this.log.info("Retrying connect to " + route);
+ }
+ } else {
+ throw ex;
+ }
+ }
+ }
+ }
+
+ /**
+ * Execute request and retry in case of a recoverable I/O failure
+ */
+ private HttpResponse tryExecute(
+ final RoutedRequest req, final HttpContext context) throws HttpException, IOException {
+ final RequestWrapper wrapper = req.getRequest();
+ final HttpRoute route = req.getRoute();
+ HttpResponse response = null;
+
+ Exception retryReason = null;
+ for (;;) {
+ // Increment total exec count (with redirects)
+ execCount++;
+ // Increment exec count for this particular request
+ wrapper.incrementExecCount();
+ if (!wrapper.isRepeatable()) {
+ this.log.debug("Cannot retry non-repeatable request");
+ if (retryReason != null) {
+ throw new NonRepeatableRequestException("Cannot retry request " +
+ "with a non-repeatable request entity. The cause lists the " +
+ "reason the original request failed.", retryReason);
+ } else {
+ throw new NonRepeatableRequestException("Cannot retry request " +
+ "with a non-repeatable request entity.");
+ }
+ }
+
+ try {
+ if (!managedConn.isOpen()) {
+ // If we have a direct route to the target host
+ // just re-open connection and re-try the request
+ if (!route.isTunnelled()) {
+ this.log.debug("Reopening the direct connection.");
+ managedConn.open(route, context, params);
+ } else {
+ // otherwise give up
+ this.log.debug("Proxied connection. Need to start over.");
+ break;
+ }
+ }
+
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Attempt " + execCount + " to execute request");
+ }
+ response = requestExec.execute(wrapper, managedConn, context);
+ break;
+
+ } catch (final IOException ex) {
+ this.log.debug("Closing the connection.");
+ try {
+ managedConn.close();
+ } catch (final IOException ignore) {
+ }
+ if (retryHandler.retryRequest(ex, wrapper.getExecCount(), context)) {
+ if (this.log.isInfoEnabled()) {
+ this.log.info("I/O exception ("+ ex.getClass().getName() +
+ ") caught when processing request to "
+ + route +
+ ": "
+ + ex.getMessage());
+ }
+ if (this.log.isDebugEnabled()) {
+ this.log.debug(ex.getMessage(), ex);
+ }
+ if (this.log.isInfoEnabled()) {
+ this.log.info("Retrying request to " + route);
+ }
+ retryReason = ex;
+ } else {
+ if (ex instanceof NoHttpResponseException) {
+ final NoHttpResponseException updatedex = new NoHttpResponseException(
+ route.getTargetHost().toHostString() + " failed to respond");
+ updatedex.setStackTrace(ex.getStackTrace());
+ throw updatedex;
+ } else {
+ throw ex;
+ }
+ }
+ }
+ }
+ return response;
+ }
+
+ /**
+ * Returns the connection back to the connection manager
+ * and prepares for retrieving a new connection during
+ * the next request.
+ */
+ protected void releaseConnection() {
+ // Release the connection through the ManagedConnection instead of the
+ // ConnectionManager directly. This lets the connection control how
+ // it is released.
+ try {
+ managedConn.releaseConnection();
+ } catch(final IOException ignored) {
+ this.log.debug("IOException releasing connection", ignored);
+ }
+ managedConn = null;
+ }
+
+ /**
+ * Determines the route for a request.
+ * Called by {@link #execute}
+ * to determine the route for either the original or a followup request.
+ *
+ * @param targetHost the target host for the request.
+ * Implementations may accept null
+ * if they can still determine a route, for example
+ * to a default target or by inspecting the request.
+ * @param request the request to execute
+ * @param context the context to use for the execution,
+ * never null
+ *
+ * @return the route the request should take
+ *
+ * @throws HttpException in case of a problem
+ */
+ protected HttpRoute determineRoute(final HttpHost targetHost,
+ final HttpRequest request,
+ final HttpContext context)
+ throws HttpException {
+ return this.routePlanner.determineRoute(
+ targetHost != null ? targetHost : (HttpHost) request.getParams()
+ .getParameter(ClientPNames.DEFAULT_HOST),
+ request, context);
+ }
+
+
+ /**
+ * Establishes the target route.
+ *
+ * @param route the route to establish
+ * @param context the context for the request execution
+ *
+ * @throws HttpException in case of a problem
+ * @throws IOException in case of an IO problem
+ */
+ protected void establishRoute(final HttpRoute route, final HttpContext context)
+ throws HttpException, IOException {
+
+ final HttpRouteDirector rowdy = new BasicRouteDirector();
+ int step;
+ do {
+ final HttpRoute fact = managedConn.getRoute();
+ step = rowdy.nextStep(route, fact);
+
+ switch (step) {
+
+ case HttpRouteDirector.CONNECT_TARGET:
+ case HttpRouteDirector.CONNECT_PROXY:
+ managedConn.open(route, context, this.params);
+ break;
+
+ case HttpRouteDirector.TUNNEL_TARGET: {
+ final boolean secure = createTunnelToTarget(route, context);
+ this.log.debug("Tunnel to target created.");
+ managedConn.tunnelTarget(secure, this.params);
+ } break;
+
+ case HttpRouteDirector.TUNNEL_PROXY: {
+ // The most simple example for this case is a proxy chain
+ // of two proxies, where P1 must be tunnelled to P2.
+ // route: Source -> P1 -> P2 -> Target (3 hops)
+ // fact: Source -> P1 -> Target (2 hops)
+ final int hop = fact.getHopCount()-1; // the hop to establish
+ final boolean secure = createTunnelToProxy(route, hop, context);
+ this.log.debug("Tunnel to proxy created.");
+ managedConn.tunnelProxy(route.getHopTarget(hop),
+ secure, this.params);
+ } break;
+
+
+ case HttpRouteDirector.LAYER_PROTOCOL:
+ managedConn.layerProtocol(context, this.params);
+ break;
+
+ case HttpRouteDirector.UNREACHABLE:
+ throw new HttpException("Unable to establish route: " +
+ "planned = " + route + "; current = " + fact);
+ case HttpRouteDirector.COMPLETE:
+ // do nothing
+ break;
+ default:
+ throw new IllegalStateException("Unknown step indicator "
+ + step + " from RouteDirector.");
+ }
+
+ } while (step > HttpRouteDirector.COMPLETE);
+
+ } // establishConnection
+
+
+ /**
+ * Creates a tunnel to the target server.
+ * The connection must be established to the (last) proxy.
+ * A CONNECT request for tunnelling through the proxy will
+ * be created and sent, the response received and checked.
+ * This method does not update the connection with
+ * information about the tunnel, that is left to the caller.
+ *
+ * @param route the route to establish
+ * @param context the context for request execution
+ *
+ * @return true if the tunnelled route is secure,
+ * false otherwise.
+ * The implementation here always returns false,
+ * but derived classes may override.
+ *
+ * @throws HttpException in case of a problem
+ * @throws IOException in case of an IO problem
+ */
+ protected boolean createTunnelToTarget(final HttpRoute route,
+ final HttpContext context)
+ throws HttpException, IOException {
+
+ final HttpHost proxy = route.getProxyHost();
+ final HttpHost target = route.getTargetHost();
+ HttpResponse response = null;
+
+ for (;;) {
+ if (!this.managedConn.isOpen()) {
+ this.managedConn.open(route, context, this.params);
+ }
+
+ final HttpRequest connect = createConnectRequest(route, context);
+ connect.setParams(this.params);
+
+ // Populate the execution context
+ context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
+ context.setAttribute(ClientContext.ROUTE, route);
+ context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy);
+ context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);
+ context.setAttribute(ExecutionContext.HTTP_REQUEST, connect);
+
+ this.requestExec.preProcess(connect, this.httpProcessor, context);
+
+ response = this.requestExec.execute(connect, this.managedConn, context);
+
+ response.setParams(this.params);
+ this.requestExec.postProcess(response, this.httpProcessor, context);
+
+ final int status = response.getStatusLine().getStatusCode();
+ if (status < 200) {
+ throw new HttpException("Unexpected response to CONNECT request: " +
+ response.getStatusLine());
+ }
+
+ if (HttpClientParams.isAuthenticating(this.params)) {
+ if (this.authenticator.isAuthenticationRequested(proxy, response,
+ this.proxyAuthStrategy, this.proxyAuthState, context)) {
+ if (this.authenticator.authenticate(proxy, response,
+ this.proxyAuthStrategy, this.proxyAuthState, context)) {
+ // Retry request
+ if (this.reuseStrategy.keepAlive(response, context)) {
+ this.log.debug("Connection kept alive");
+ // Consume response content
+ final HttpEntity entity = response.getEntity();
+ EntityUtils.consume(entity);
+ } else {
+ this.managedConn.close();
+ }
+ } else {
+ break;
+ }
+ } else {
+ break;
+ }
+ }
+ }
+
+ final int status = response.getStatusLine().getStatusCode();
+
+ if (status > 299) {
+
+ // Buffer response content
+ final HttpEntity entity = response.getEntity();
+ if (entity != null) {
+ response.setEntity(new BufferedHttpEntity(entity));
+ }
+
+ this.managedConn.close();
+ throw new TunnelRefusedException("CONNECT refused by proxy: " +
+ response.getStatusLine(), response);
+ }
+
+ this.managedConn.markReusable();
+
+ // How to decide on security of the tunnelled connection?
+ // The socket factory knows only about the segment to the proxy.
+ // Even if that is secure, the hop to the target may be insecure.
+ // Leave it to derived classes, consider insecure by default here.
+ return false;
+
+ } // createTunnelToTarget
+
+
+
+ /**
+ * Creates a tunnel to an intermediate proxy.
+ * This method is not implemented in this class.
+ * It just throws an exception here.
+ *
+ * @param route the route to establish
+ * @param hop the hop in the route to establish now.
+ * route.getHopTarget(hop)
+ * will return the proxy to tunnel to.
+ * @param context the context for request execution
+ *
+ * @return true if the partially tunnelled connection
+ * is secure, false otherwise.
+ *
+ * @throws HttpException in case of a problem
+ * @throws IOException in case of an IO problem
+ */
+ protected boolean createTunnelToProxy(final HttpRoute route, final int hop,
+ final HttpContext context)
+ throws HttpException, IOException {
+
+ // Have a look at createTunnelToTarget and replicate the parts
+ // you need in a custom derived class. If your proxies don't require
+ // authentication, it is not too hard. But for the stock version of
+ // HttpClient, we cannot make such simplifying assumptions and would
+ // have to include proxy authentication code. The HttpComponents team
+ // is currently not in a position to support rarely used code of this
+ // complexity. Feel free to submit patches that refactor the code in
+ // createTunnelToTarget to facilitate re-use for proxy tunnelling.
+
+ throw new HttpException("Proxy chains are not supported.");
+ }
+
+
+
+ /**
+ * Creates the CONNECT request for tunnelling.
+ * Called by {@link #createTunnelToTarget createTunnelToTarget}.
+ *
+ * @param route the route to establish
+ * @param context the context for request execution
+ *
+ * @return the CONNECT request for tunnelling
+ */
+ protected HttpRequest createConnectRequest(final HttpRoute route,
+ final HttpContext context) {
+ // see RFC 2817, section 5.2 and
+ // INTERNET-DRAFT: Tunneling TCP based protocols through
+ // Web proxy servers
+
+ final HttpHost target = route.getTargetHost();
+
+ final String host = target.getHostName();
+ int port = target.getPort();
+ if (port < 0) {
+ final Scheme scheme = connManager.getSchemeRegistry().
+ getScheme(target.getSchemeName());
+ port = scheme.getDefaultPort();
+ }
+
+ final StringBuilder buffer = new StringBuilder(host.length() + 6);
+ buffer.append(host);
+ buffer.append(':');
+ buffer.append(Integer.toString(port));
+
+ final String authority = buffer.toString();
+ final ProtocolVersion ver = HttpProtocolParams.getVersion(params);
+ final HttpRequest req = new BasicHttpRequest
+ ("CONNECT", authority, ver);
+
+ return req;
+ }
+
+
+ /**
+ * Analyzes a response to check need for a followup.
+ *
+ * @param roureq the request and route.
+ * @param response the response to analayze
+ * @param context the context used for the current request execution
+ *
+ * @return the followup request and route if there is a followup, or
+ * null if the response should be returned as is
+ *
+ * @throws HttpException in case of a problem
+ * @throws IOException in case of an IO problem
+ */
+ protected RoutedRequest handleResponse(final RoutedRequest roureq,
+ final HttpResponse response,
+ final HttpContext context)
+ throws HttpException, IOException {
+
+ final HttpRoute route = roureq.getRoute();
+ final RequestWrapper request = roureq.getRequest();
+
+ final HttpParams params = request.getParams();
+
+ if (HttpClientParams.isAuthenticating(params)) {
+ HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
+ if (target == null) {
+ target = route.getTargetHost();
+ }
+ if (target.getPort() < 0) {
+ final Scheme scheme = connManager.getSchemeRegistry().getScheme(target);
+ target = new HttpHost(target.getHostName(), scheme.getDefaultPort(), target.getSchemeName());
+ }
+
+ final boolean targetAuthRequested = this.authenticator.isAuthenticationRequested(
+ target, response, this.targetAuthStrategy, targetAuthState, context);
+
+ HttpHost proxy = route.getProxyHost();
+ // if proxy is not set use target host instead
+ if (proxy == null) {
+ proxy = route.getTargetHost();
+ }
+ final boolean proxyAuthRequested = this.authenticator.isAuthenticationRequested(
+ proxy, response, this.proxyAuthStrategy, proxyAuthState, context);
+
+ if (targetAuthRequested) {
+ if (this.authenticator.authenticate(target, response,
+ this.targetAuthStrategy, this.targetAuthState, context)) {
+ // Re-try the same request via the same route
+ return roureq;
+ }
+ }
+ if (proxyAuthRequested) {
+ if (this.authenticator.authenticate(proxy, response,
+ this.proxyAuthStrategy, this.proxyAuthState, context)) {
+ // Re-try the same request via the same route
+ return roureq;
+ }
+ }
+ }
+
+ if (HttpClientParams.isRedirecting(params) &&
+ this.redirectStrategy.isRedirected(request, response, context)) {
+
+ if (redirectCount >= maxRedirects) {
+ throw new RedirectException("Maximum redirects ("
+ + maxRedirects + ") exceeded");
+ }
+ redirectCount++;
+
+ // Virtual host cannot be used any longer
+ virtualHost = null;
+
+ final HttpUriRequest redirect = redirectStrategy.getRedirect(request, response, context);
+ final HttpRequest orig = request.getOriginal();
+ redirect.setHeaders(orig.getAllHeaders());
+
+ final URI uri = redirect.getURI();
+ final HttpHost newTarget = URIUtils.extractHost(uri);
+ if (newTarget == null) {
+ throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri);
+ }
+
+ // Reset auth states if redirecting to another host
+ if (!route.getTargetHost().equals(newTarget)) {
+ this.log.debug("Resetting target auth state");
+ targetAuthState.reset();
+ final AuthScheme authScheme = proxyAuthState.getAuthScheme();
+ if (authScheme != null && authScheme.isConnectionBased()) {
+ this.log.debug("Resetting proxy auth state");
+ proxyAuthState.reset();
+ }
+ }
+
+ final RequestWrapper wrapper = wrapRequest(redirect);
+ wrapper.setParams(params);
+
+ final HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
+ final RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);
+
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
+ }
+
+ return newRequest;
+ }
+
+ return null;
+ } // handleResponse
+
+
+ /**
+ * Shuts down the connection.
+ * This method is called from a catch block in
+ * {@link #execute execute} during exception handling.
+ */
+ private void abortConnection() {
+ final ManagedClientConnection mcc = managedConn;
+ if (mcc != null) {
+ // we got here as the result of an exception
+ // no response will be returned, release the connection
+ managedConn = null;
+ try {
+ mcc.abortConnection();
+ } catch (final IOException ex) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug(ex.getMessage(), ex);
+ }
+ }
+ // ensure the connection manager properly releases this connection
+ try {
+ mcc.releaseConnection();
+ } catch(final IOException ignored) {
+ this.log.debug("Error releasing connection", ignored);
+ }
+ }
+ } // abortConnection
+
+
+} // class DefaultClientRequestDirector
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultServiceUnavailableRetryStrategy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultServiceUnavailableRetryStrategy.java
new file mode 100644
index 000000000..8e7279aab
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultServiceUnavailableRetryStrategy.java
@@ -0,0 +1,80 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.ServiceUnavailableRetryStrategy;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Default implementation of the {@link ServiceUnavailableRetryStrategy} interface.
+ * that retries 503 (Service Unavailable) responses for a fixed number of times
+ * at a fixed interval.
+ *
+ * @since 4.2
+ */
+@Immutable
+public class DefaultServiceUnavailableRetryStrategy implements ServiceUnavailableRetryStrategy {
+
+ /**
+ * Maximum number of allowed retries if the server responds with a HTTP code
+ * in our retry code list. Default value is 1.
+ */
+ private final int maxRetries;
+
+ /**
+ * Retry interval between subsequent requests, in milliseconds. Default
+ * value is 1 second.
+ */
+ private final long retryInterval;
+
+ public DefaultServiceUnavailableRetryStrategy(final int maxRetries, final int retryInterval) {
+ super();
+ Args.positive(maxRetries, "Max retries");
+ Args.positive(retryInterval, "Retry interval");
+ this.maxRetries = maxRetries;
+ this.retryInterval = retryInterval;
+ }
+
+ public DefaultServiceUnavailableRetryStrategy() {
+ this(1, 1000);
+ }
+
+ public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) {
+ return executionCount <= maxRetries &&
+ response.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE;
+ }
+
+ public long getRetryInterval() {
+ return retryInterval;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultTargetAuthenticationHandler.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultTargetAuthenticationHandler.java
new file mode 100644
index 000000000..a2a57e1d5
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultTargetAuthenticationHandler.java
@@ -0,0 +1,91 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.util.List;
+import java.util.Map;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.auth.AUTH;
+import ch.boye.httpclientandroidlib.auth.MalformedChallengeException;
+import ch.boye.httpclientandroidlib.auth.params.AuthPNames;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Default {@link ch.boye.httpclientandroidlib.client.AuthenticationHandler} implementation
+ * for target host authentication.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.2) use {@link TargetAuthenticationStrategy}
+ */
+@Deprecated
+@Immutable
+public class DefaultTargetAuthenticationHandler extends AbstractAuthenticationHandler {
+
+ public DefaultTargetAuthenticationHandler() {
+ super();
+ }
+
+ public boolean isAuthenticationRequested(
+ final HttpResponse response,
+ final HttpContext context) {
+ Args.notNull(response, "HTTP response");
+ final int status = response.getStatusLine().getStatusCode();
+ return status == HttpStatus.SC_UNAUTHORIZED;
+ }
+
+ public Map getChallenges(
+ final HttpResponse response,
+ final HttpContext context) throws MalformedChallengeException {
+ Args.notNull(response, "HTTP response");
+ final Header[] headers = response.getHeaders(AUTH.WWW_AUTH);
+ return parseChallenges(headers);
+ }
+
+ @Override
+ protected List getAuthPreferences(
+ final HttpResponse response,
+ final HttpContext context) {
+ @SuppressWarnings("unchecked")
+ final
+ List authpref = (List) response.getParams().getParameter(
+ AuthPNames.TARGET_AUTH_PREF);
+ if (authpref != null) {
+ return authpref;
+ } else {
+ return super.getAuthPreferences(response, context);
+ }
+ }
+
+}
+
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultUserTokenHandler.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultUserTokenHandler.java
new file mode 100644
index 000000000..c6d2a8daa
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/DefaultUserTokenHandler.java
@@ -0,0 +1,101 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.security.Principal;
+
+import javax.net.ssl.SSLSession;
+
+import ch.boye.httpclientandroidlib.HttpConnection;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.auth.AuthScheme;
+import ch.boye.httpclientandroidlib.auth.AuthState;
+import ch.boye.httpclientandroidlib.auth.Credentials;
+import ch.boye.httpclientandroidlib.client.UserTokenHandler;
+import ch.boye.httpclientandroidlib.client.protocol.HttpClientContext;
+import ch.boye.httpclientandroidlib.conn.ManagedHttpClientConnection;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+/**
+ * Default implementation of {@link UserTokenHandler}. This class will use
+ * an instance of {@link Principal} as a state object for HTTP connections,
+ * if it can be obtained from the given execution context. This helps ensure
+ * persistent connections created with a particular user identity within
+ * a particular security context can be reused by the same user only.
+ *
+ * DefaultUserTokenHandler will use the user principle of connection
+ * based authentication schemes such as NTLM or that of the SSL session
+ * with the client authentication turned on. If both are unavailable,
+ * null token will be returned.
+ *
+ * @since 4.0
+ */
+@Immutable
+public class DefaultUserTokenHandler implements UserTokenHandler {
+
+ public static final DefaultUserTokenHandler INSTANCE = new DefaultUserTokenHandler();
+
+ public Object getUserToken(final HttpContext context) {
+
+ final HttpClientContext clientContext = HttpClientContext.adapt(context);
+
+ Principal userPrincipal = null;
+
+ final AuthState targetAuthState = clientContext.getTargetAuthState();
+ if (targetAuthState != null) {
+ userPrincipal = getAuthPrincipal(targetAuthState);
+ if (userPrincipal == null) {
+ final AuthState proxyAuthState = clientContext.getProxyAuthState();
+ userPrincipal = getAuthPrincipal(proxyAuthState);
+ }
+ }
+
+ if (userPrincipal == null) {
+ final HttpConnection conn = clientContext.getConnection();
+ if (conn.isOpen() && conn instanceof ManagedHttpClientConnection) {
+ final SSLSession sslsession = ((ManagedHttpClientConnection) conn).getSSLSession();
+ if (sslsession != null) {
+ userPrincipal = sslsession.getLocalPrincipal();
+ }
+ }
+ }
+
+ return userPrincipal;
+ }
+
+ private static Principal getAuthPrincipal(final AuthState authState) {
+ final AuthScheme scheme = authState.getAuthScheme();
+ if (scheme != null && scheme.isComplete() && scheme.isConnectionBased()) {
+ final Credentials creds = authState.getCredentials();
+ if (creds != null) {
+ return creds.getUserPrincipal();
+ }
+ }
+ return null;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/EntityEnclosingRequestWrapper.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/EntityEnclosingRequestWrapper.java
new file mode 100644
index 000000000..45fbbe0a6
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/EntityEnclosingRequestWrapper.java
@@ -0,0 +1,113 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.ProtocolException;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.entity.HttpEntityWrapper;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+
+/**
+ * A wrapper class for {@link HttpEntityEnclosingRequest}s that can
+ * be used to change properties of the current request without
+ * modifying the original object.
+ *
+ * This class is also capable of resetting the request headers to
+ * the state of the original request.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) do not use.
+ */
+@Deprecated
+@NotThreadSafe // e.g. [gs]etEntity()
+public class EntityEnclosingRequestWrapper extends RequestWrapper
+ implements HttpEntityEnclosingRequest {
+
+ private HttpEntity entity;
+ private boolean consumed;
+
+ public EntityEnclosingRequestWrapper(final HttpEntityEnclosingRequest request)
+ throws ProtocolException {
+ super(request);
+ setEntity(request.getEntity());
+ }
+
+ public HttpEntity getEntity() {
+ return this.entity;
+ }
+
+ public void setEntity(final HttpEntity entity) {
+ this.entity = entity != null ? new EntityWrapper(entity) : null;
+ this.consumed = false;
+ }
+
+ public boolean expectContinue() {
+ final Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE);
+ return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue());
+ }
+
+ @Override
+ public boolean isRepeatable() {
+ return this.entity == null || this.entity.isRepeatable() || !this.consumed;
+ }
+
+ class EntityWrapper extends HttpEntityWrapper {
+
+ EntityWrapper(final HttpEntity entity) {
+ super(entity);
+ }
+
+ @Override
+ public void consumeContent() throws IOException {
+ consumed = true;
+ super.consumeContent();
+ }
+
+ @Override
+ public InputStream getContent() throws IOException {
+ consumed = true;
+ return super.getContent();
+ }
+
+ @Override
+ public void writeTo(final OutputStream outstream) throws IOException {
+ consumed = true;
+ super.writeTo(outstream);
+ }
+
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/FutureRequestExecutionMetrics.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/FutureRequestExecutionMetrics.java
new file mode 100644
index 000000000..888e7e3a5
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/FutureRequestExecutionMetrics.java
@@ -0,0 +1,156 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * Collection of different counters used to gather metrics for {@link FutureRequestExecutionService}.
+ */
+public final class FutureRequestExecutionMetrics {
+
+ private final AtomicLong activeConnections = new AtomicLong();
+ private final AtomicLong scheduledConnections = new AtomicLong();
+ private final DurationCounter successfulConnections = new DurationCounter();
+ private final DurationCounter failedConnections = new DurationCounter();
+ private final DurationCounter requests = new DurationCounter();
+ private final DurationCounter tasks = new DurationCounter();
+
+ FutureRequestExecutionMetrics() {
+ }
+
+ AtomicLong getActiveConnections() {
+ return activeConnections;
+ }
+
+ AtomicLong getScheduledConnections() {
+ return scheduledConnections;
+ }
+
+ DurationCounter getSuccessfulConnections() {
+ return successfulConnections;
+ }
+
+ DurationCounter getFailedConnections() {
+ return failedConnections;
+ }
+
+ DurationCounter getRequests() {
+ return requests;
+ }
+
+ DurationCounter getTasks() {
+ return tasks;
+ }
+
+ public long getActiveConnectionCount() {
+ return activeConnections.get();
+ }
+
+ public long getScheduledConnectionCount() {
+ return scheduledConnections.get();
+ }
+
+ public long getSuccessfulConnectionCount() {
+ return successfulConnections.count();
+ }
+
+ public long getSuccessfulConnectionAverageDuration() {
+ return successfulConnections.averageDuration();
+ }
+
+ public long getFailedConnectionCount() {
+ return failedConnections.count();
+ }
+
+ public long getFailedConnectionAverageDuration() {
+ return failedConnections.averageDuration();
+ }
+
+ public long getRequestCount() {
+ return requests.count();
+ }
+
+ public long getRequestAverageDuration() {
+ return requests.averageDuration();
+ }
+
+ public long getTaskCount() {
+ return tasks.count();
+ }
+
+ public long getTaskAverageDuration() {
+ return tasks.averageDuration();
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("[activeConnections=").append(activeConnections)
+ .append(", scheduledConnections=").append(scheduledConnections)
+ .append(", successfulConnections=").append(successfulConnections)
+ .append(", failedConnections=").append(failedConnections)
+ .append(", requests=").append(requests)
+ .append(", tasks=").append(tasks)
+ .append("]");
+ return builder.toString();
+ }
+
+ /**
+ * A counter that can measure duration and number of events.
+ */
+ static class DurationCounter {
+
+ private final AtomicLong count = new AtomicLong(0);
+ private final AtomicLong cumulativeDuration = new AtomicLong(0);
+
+ public void increment(final long startTime) {
+ count.incrementAndGet();
+ cumulativeDuration.addAndGet(System.currentTimeMillis() - startTime);
+ }
+
+ public long count() {
+ return count.get();
+ }
+
+ public long averageDuration() {
+ final long counter = count.get();
+ return counter > 0 ? cumulativeDuration.get() / counter : 0;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("[count=").append(count())
+ .append(", averageDuration=").append(averageDuration())
+ .append("]");
+ return builder.toString();
+ }
+
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/FutureRequestExecutionService.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/FutureRequestExecutionService.java
new file mode 100644
index 000000000..26fa9dba3
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/FutureRequestExecutionService.java
@@ -0,0 +1,142 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.client.HttpClient;
+import ch.boye.httpclientandroidlib.client.ResponseHandler;
+import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest;
+import ch.boye.httpclientandroidlib.concurrent.FutureCallback;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+/**
+ * HttpAsyncClientWithFuture wraps calls to execute with a {@link HttpRequestFutureTask}
+ * and schedules them using the provided executor service. Scheduled calls may be cancelled.
+ */
+@ThreadSafe
+public class FutureRequestExecutionService implements Closeable {
+
+ private final HttpClient httpclient;
+ private final ExecutorService executorService;
+ private final FutureRequestExecutionMetrics metrics = new FutureRequestExecutionMetrics();
+ private final AtomicBoolean closed = new AtomicBoolean(false);
+
+ /**
+ * Create a new FutureRequestExecutionService.
+ *
+ * @param httpclient
+ * you should tune your httpclient instance to match your needs. You should
+ * align the max number of connections in the pool and the number of threads
+ * in the executor; it doesn't make sense to have more threads than connections
+ * and if you have less connections than threads, the threads will just end up
+ * blocking on getting a connection from the pool.
+ * @param executorService
+ * any executorService will do here. E.g.
+ * {@link java.util.concurrent.Executors#newFixedThreadPool(int)}
+ */
+ public FutureRequestExecutionService(
+ final HttpClient httpclient,
+ final ExecutorService executorService) {
+ this.httpclient = httpclient;
+ this.executorService = executorService;
+ }
+
+ /**
+ * Schedule a request for execution.
+ *
+ * @param
+ *
+ * @param request
+ * request to execute
+ * @param responseHandler
+ * handler that will process the response.
+ * @return HttpAsyncClientFutureTask for the scheduled request.
+ * @throws InterruptedException
+ */
+ public HttpRequestFutureTask execute(
+ final HttpUriRequest request,
+ final HttpContext context,
+ final ResponseHandler responseHandler) {
+ return execute(request, context, responseHandler, null);
+ }
+
+ /**
+ * Schedule a request for execution.
+ *
+ * @param
+ *
+ * @param request
+ * request to execute
+ * @param context
+ * optional context; use null if not needed.
+ * @param responseHandler
+ * handler that will process the response.
+ * @param callback
+ * callback handler that will be called when the request is scheduled,
+ * started, completed, failed, or cancelled.
+ * @return HttpAsyncClientFutureTask for the scheduled request.
+ * @throws InterruptedException
+ */
+ public HttpRequestFutureTask execute(
+ final HttpUriRequest request,
+ final HttpContext context,
+ final ResponseHandler responseHandler,
+ final FutureCallback callback) {
+ if(closed.get()) {
+ throw new IllegalStateException("Close has been called on this httpclient instance.");
+ }
+ metrics.getScheduledConnections().incrementAndGet();
+ final HttpRequestTaskCallable callable = new HttpRequestTaskCallable(
+ httpclient, request, context, responseHandler, callback, metrics);
+ final HttpRequestFutureTask httpRequestFutureTask = new HttpRequestFutureTask(
+ request, callable);
+ executorService.execute(httpRequestFutureTask);
+
+ return httpRequestFutureTask;
+ }
+
+ /**
+ * @return metrics gathered for this instance.
+ * @see FutureRequestExecutionMetrics
+ */
+ public FutureRequestExecutionMetrics metrics() {
+ return metrics;
+ }
+
+ public void close() throws IOException {
+ closed.set(true);
+ executorService.shutdownNow();
+ if (httpclient instanceof Closeable) {
+ ((Closeable) httpclient).close();
+ }
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/HttpAuthenticator.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/HttpAuthenticator.java
new file mode 100644
index 000000000..745ae4735
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/HttpAuthenticator.java
@@ -0,0 +1,61 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.auth.AuthState;
+import ch.boye.httpclientandroidlib.client.AuthenticationStrategy;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+/**
+ * @deprecated (4.3) reserved for internal use.
+ *
+ */
+@Deprecated
+public class HttpAuthenticator extends ch.boye.httpclientandroidlib.impl.auth.HttpAuthenticator {
+
+ public HttpAuthenticator(final HttpClientAndroidLog log) {
+ super(log);
+ }
+
+ public HttpAuthenticator() {
+ super();
+ }
+
+ public boolean authenticate (
+ final HttpHost host,
+ final HttpResponse response,
+ final AuthenticationStrategy authStrategy,
+ final AuthState authState,
+ final HttpContext context) {
+ return handleAuthChallenge(host, response, authStrategy, authState, context);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/HttpClientBuilder.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/HttpClientBuilder.java
new file mode 100644
index 000000000..00313e668
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/HttpClientBuilder.java
@@ -0,0 +1,954 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.io.Closeable;
+import java.net.ProxySelector;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocketFactory;
+
+import ch.boye.httpclientandroidlib.ConnectionReuseStrategy;
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequestInterceptor;
+import ch.boye.httpclientandroidlib.HttpResponseInterceptor;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.auth.AuthSchemeProvider;
+import ch.boye.httpclientandroidlib.client.AuthenticationStrategy;
+import ch.boye.httpclientandroidlib.client.BackoffManager;
+import ch.boye.httpclientandroidlib.client.ConnectionBackoffStrategy;
+import ch.boye.httpclientandroidlib.client.CookieStore;
+import ch.boye.httpclientandroidlib.client.CredentialsProvider;
+import ch.boye.httpclientandroidlib.client.HttpRequestRetryHandler;
+import ch.boye.httpclientandroidlib.client.RedirectStrategy;
+import ch.boye.httpclientandroidlib.client.ServiceUnavailableRetryStrategy;
+import ch.boye.httpclientandroidlib.client.UserTokenHandler;
+import ch.boye.httpclientandroidlib.client.config.AuthSchemes;
+import ch.boye.httpclientandroidlib.client.config.CookieSpecs;
+import ch.boye.httpclientandroidlib.client.config.RequestConfig;
+import ch.boye.httpclientandroidlib.client.protocol.RequestAcceptEncoding;
+import ch.boye.httpclientandroidlib.client.protocol.RequestAddCookies;
+import ch.boye.httpclientandroidlib.client.protocol.RequestAuthCache;
+import ch.boye.httpclientandroidlib.client.protocol.RequestClientConnControl;
+import ch.boye.httpclientandroidlib.client.protocol.RequestDefaultHeaders;
+import ch.boye.httpclientandroidlib.client.protocol.RequestExpectContinue;
+import ch.boye.httpclientandroidlib.client.protocol.ResponseContentEncoding;
+import ch.boye.httpclientandroidlib.client.protocol.ResponseProcessCookies;
+import ch.boye.httpclientandroidlib.config.ConnectionConfig;
+import ch.boye.httpclientandroidlib.config.Lookup;
+import ch.boye.httpclientandroidlib.config.RegistryBuilder;
+import ch.boye.httpclientandroidlib.config.SocketConfig;
+import ch.boye.httpclientandroidlib.conn.ConnectionKeepAliveStrategy;
+import ch.boye.httpclientandroidlib.conn.HttpClientConnectionManager;
+import ch.boye.httpclientandroidlib.conn.SchemePortResolver;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoutePlanner;
+import ch.boye.httpclientandroidlib.conn.socket.ConnectionSocketFactory;
+import ch.boye.httpclientandroidlib.conn.socket.LayeredConnectionSocketFactory;
+import ch.boye.httpclientandroidlib.conn.socket.PlainConnectionSocketFactory;
+import ch.boye.httpclientandroidlib.conn.ssl.SSLConnectionSocketFactory;
+import ch.boye.httpclientandroidlib.conn.ssl.SSLContexts;
+import ch.boye.httpclientandroidlib.conn.ssl.X509HostnameVerifier;
+import ch.boye.httpclientandroidlib.cookie.CookieSpecProvider;
+import ch.boye.httpclientandroidlib.impl.DefaultConnectionReuseStrategy;
+import ch.boye.httpclientandroidlib.impl.NoConnectionReuseStrategy;
+import ch.boye.httpclientandroidlib.impl.auth.BasicSchemeFactory;
+import ch.boye.httpclientandroidlib.impl.auth.DigestSchemeFactory;
+/* KerberosSchemeFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.impl.auth.NTLMSchemeFactory;
+/* SPNegoSchemeFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.impl.conn.DefaultProxyRoutePlanner;
+import ch.boye.httpclientandroidlib.impl.conn.DefaultRoutePlanner;
+import ch.boye.httpclientandroidlib.impl.conn.DefaultSchemePortResolver;
+import ch.boye.httpclientandroidlib.impl.conn.PoolingHttpClientConnectionManager;
+import ch.boye.httpclientandroidlib.impl.conn.SystemDefaultRoutePlanner;
+import ch.boye.httpclientandroidlib.impl.cookie.BestMatchSpecFactory;
+import ch.boye.httpclientandroidlib.impl.cookie.BrowserCompatSpecFactory;
+import ch.boye.httpclientandroidlib.impl.cookie.IgnoreSpecFactory;
+import ch.boye.httpclientandroidlib.impl.cookie.NetscapeDraftSpecFactory;
+import ch.boye.httpclientandroidlib.impl.cookie.RFC2109SpecFactory;
+import ch.boye.httpclientandroidlib.impl.cookie.RFC2965SpecFactory;
+import ch.boye.httpclientandroidlib.impl.execchain.BackoffStrategyExec;
+import ch.boye.httpclientandroidlib.impl.execchain.ClientExecChain;
+import ch.boye.httpclientandroidlib.impl.execchain.MainClientExec;
+import ch.boye.httpclientandroidlib.impl.execchain.ProtocolExec;
+import ch.boye.httpclientandroidlib.impl.execchain.RedirectExec;
+import ch.boye.httpclientandroidlib.impl.execchain.RetryExec;
+import ch.boye.httpclientandroidlib.impl.execchain.ServiceUnavailableRetryExec;
+import ch.boye.httpclientandroidlib.protocol.HttpProcessor;
+import ch.boye.httpclientandroidlib.protocol.HttpProcessorBuilder;
+import ch.boye.httpclientandroidlib.protocol.HttpRequestExecutor;
+import ch.boye.httpclientandroidlib.protocol.RequestContent;
+import ch.boye.httpclientandroidlib.protocol.RequestTargetHost;
+import ch.boye.httpclientandroidlib.protocol.RequestUserAgent;
+import ch.boye.httpclientandroidlib.util.TextUtils;
+import ch.boye.httpclientandroidlib.util.VersionInfo;
+
+/**
+ * Builder for {@link CloseableHttpClient} instances.
+ *
+ * When a particular component is not explicitly this class will
+ * use its default implementation. System properties will be taken
+ * into account when configuring the default implementations when
+ * {@link #useSystemProperties()} method is called prior to calling
+ * {@link #build()}.
+ *
+ *
ssl.TrustManagerFactory.algorithm
+ *
javax.net.ssl.trustStoreType
+ *
javax.net.ssl.trustStore
+ *
javax.net.ssl.trustStoreProvider
+ *
javax.net.ssl.trustStorePassword
+ *
ssl.KeyManagerFactory.algorithm
+ *
javax.net.ssl.keyStoreType
+ *
javax.net.ssl.keyStore
+ *
javax.net.ssl.keyStoreProvider
+ *
javax.net.ssl.keyStorePassword
+ *
https.protocols
+ *
https.cipherSuites
+ *
http.proxyHost
+ *
http.proxyPort
+ *
http.nonProxyHosts
+ *
http.keepAlive
+ *
http.maxConnections
+ *
http.agent
+ *
+ *
+ * Please note that some settings used by this class can be mutually
+ * exclusive and may not apply when building {@link CloseableHttpClient}
+ * instances.
+ *
+ * @since 4.3
+ */
+@NotThreadSafe
+public class HttpClientBuilder {
+
+ private HttpRequestExecutor requestExec;
+ private X509HostnameVerifier hostnameVerifier;
+ private LayeredConnectionSocketFactory sslSocketFactory;
+ private SSLContext sslcontext;
+ private HttpClientConnectionManager connManager;
+ private SchemePortResolver schemePortResolver;
+ private ConnectionReuseStrategy reuseStrategy;
+ private ConnectionKeepAliveStrategy keepAliveStrategy;
+ private AuthenticationStrategy targetAuthStrategy;
+ private AuthenticationStrategy proxyAuthStrategy;
+ private UserTokenHandler userTokenHandler;
+ private HttpProcessor httpprocessor;
+
+ private LinkedList requestFirst;
+ private LinkedList requestLast;
+ private LinkedList responseFirst;
+ private LinkedList responseLast;
+
+ private HttpRequestRetryHandler retryHandler;
+ private HttpRoutePlanner routePlanner;
+ private RedirectStrategy redirectStrategy;
+ private ConnectionBackoffStrategy connectionBackoffStrategy;
+ private BackoffManager backoffManager;
+ private ServiceUnavailableRetryStrategy serviceUnavailStrategy;
+ private Lookup authSchemeRegistry;
+ private Lookup cookieSpecRegistry;
+ private CookieStore cookieStore;
+ private CredentialsProvider credentialsProvider;
+ private String userAgent;
+ private HttpHost proxy;
+ private Collection extends Header> defaultHeaders;
+ private SocketConfig defaultSocketConfig;
+ private ConnectionConfig defaultConnectionConfig;
+ private RequestConfig defaultRequestConfig;
+
+ private boolean systemProperties;
+ private boolean redirectHandlingDisabled;
+ private boolean automaticRetriesDisabled;
+ private boolean contentCompressionDisabled;
+ private boolean cookieManagementDisabled;
+ private boolean authCachingDisabled;
+ private boolean connectionStateDisabled;
+
+ private int maxConnTotal = 0;
+ private int maxConnPerRoute = 0;
+
+ private List closeables;
+
+ static final String DEFAULT_USER_AGENT;
+ static {
+ final VersionInfo vi = VersionInfo.loadVersionInfo
+ ("ch.boye.httpclientandroidlib.client", HttpClientBuilder.class.getClassLoader());
+ final String release = (vi != null) ?
+ vi.getRelease() : VersionInfo.UNAVAILABLE;
+ DEFAULT_USER_AGENT = "Apache-HttpClient/" + release + " (java 1.5)";
+ }
+
+ public static HttpClientBuilder create() {
+ return new HttpClientBuilder();
+ }
+
+ protected HttpClientBuilder() {
+ super();
+ }
+
+ /**
+ * Assigns {@link HttpRequestExecutor} instance.
+ */
+ public final HttpClientBuilder setRequestExecutor(final HttpRequestExecutor requestExec) {
+ this.requestExec = requestExec;
+ return this;
+ }
+
+ /**
+ * Assigns {@link X509HostnameVerifier} instance.
+ *
+ * Please note this value can be overridden by the {@link #setConnectionManager(
+ * ch.boye.httpclientandroidlib.conn.HttpClientConnectionManager)} and the {@link #setSSLSocketFactory(
+ * ch.boye.httpclientandroidlib.conn.socket.LayeredConnectionSocketFactory)} methods.
+ */
+ public final HttpClientBuilder setHostnameVerifier(final X509HostnameVerifier hostnameVerifier) {
+ this.hostnameVerifier = hostnameVerifier;
+ return this;
+ }
+
+ /**
+ * Assigns {@link SSLContext} instance.
+ *
+ *
+ * Please note this value can be overridden by the {@link #setConnectionManager(
+ * ch.boye.httpclientandroidlib.conn.HttpClientConnectionManager)} and the {@link #setSSLSocketFactory(
+ * ch.boye.httpclientandroidlib.conn.socket.LayeredConnectionSocketFactory)} methods.
+ */
+ public final HttpClientBuilder setSslcontext(final SSLContext sslcontext) {
+ this.sslcontext = sslcontext;
+ return this;
+ }
+
+ /**
+ * Assigns {@link LayeredConnectionSocketFactory} instance.
+ *
+ * Please note this value can be overridden by the {@link #setConnectionManager(
+ * ch.boye.httpclientandroidlib.conn.HttpClientConnectionManager)} method.
+ */
+ public final HttpClientBuilder setSSLSocketFactory(
+ final LayeredConnectionSocketFactory sslSocketFactory) {
+ this.sslSocketFactory = sslSocketFactory;
+ return this;
+ }
+
+ /**
+ * Assigns maximum total connection value.
+ *
+ * Please note this value can be overridden by the {@link #setConnectionManager(
+ * ch.boye.httpclientandroidlib.conn.HttpClientConnectionManager)} method.
+ */
+ public final HttpClientBuilder setMaxConnTotal(final int maxConnTotal) {
+ this.maxConnTotal = maxConnTotal;
+ return this;
+ }
+
+ /**
+ * Assigns maximum connection per route value.
+ *
+ * Please note this value can be overridden by the {@link #setConnectionManager(
+ * ch.boye.httpclientandroidlib.conn.HttpClientConnectionManager)} method.
+ */
+ public final HttpClientBuilder setMaxConnPerRoute(final int maxConnPerRoute) {
+ this.maxConnPerRoute = maxConnPerRoute;
+ return this;
+ }
+
+ /**
+ * Assigns default {@link SocketConfig}.
+ *
+ * Please note this value can be overridden by the {@link #setConnectionManager(
+ * ch.boye.httpclientandroidlib.conn.HttpClientConnectionManager)} method.
+ */
+ public final HttpClientBuilder setDefaultSocketConfig(final SocketConfig config) {
+ this.defaultSocketConfig = config;
+ return this;
+ }
+
+ /**
+ * Assigns default {@link ConnectionConfig}.
+ *
+ * Please note this value can be overridden by the {@link #setConnectionManager(
+ * ch.boye.httpclientandroidlib.conn.HttpClientConnectionManager)} method.
+ */
+ public final HttpClientBuilder setDefaultConnectionConfig(final ConnectionConfig config) {
+ this.defaultConnectionConfig = config;
+ return this;
+ }
+
+ /**
+ * Assigns {@link HttpClientConnectionManager} instance.
+ */
+ public final HttpClientBuilder setConnectionManager(
+ final HttpClientConnectionManager connManager) {
+ this.connManager = connManager;
+ return this;
+ }
+
+ /**
+ * Assigns {@link ConnectionReuseStrategy} instance.
+ */
+ public final HttpClientBuilder setConnectionReuseStrategy(
+ final ConnectionReuseStrategy reuseStrategy) {
+ this.reuseStrategy = reuseStrategy;
+ return this;
+ }
+
+ /**
+ * Assigns {@link ConnectionKeepAliveStrategy} instance.
+ */
+ public final HttpClientBuilder setKeepAliveStrategy(
+ final ConnectionKeepAliveStrategy keepAliveStrategy) {
+ this.keepAliveStrategy = keepAliveStrategy;
+ return this;
+ }
+
+ /**
+ * Assigns {@link AuthenticationStrategy} instance for proxy
+ * authentication.
+ */
+ public final HttpClientBuilder setTargetAuthenticationStrategy(
+ final AuthenticationStrategy targetAuthStrategy) {
+ this.targetAuthStrategy = targetAuthStrategy;
+ return this;
+ }
+
+ /**
+ * Assigns {@link AuthenticationStrategy} instance for target
+ * host authentication.
+ */
+ public final HttpClientBuilder setProxyAuthenticationStrategy(
+ final AuthenticationStrategy proxyAuthStrategy) {
+ this.proxyAuthStrategy = proxyAuthStrategy;
+ return this;
+ }
+
+ /**
+ * Assigns {@link UserTokenHandler} instance.
+ *
+ * Please note this value can be overridden by the {@link #disableConnectionState()}
+ * method.
+ */
+ public final HttpClientBuilder setUserTokenHandler(final UserTokenHandler userTokenHandler) {
+ this.userTokenHandler = userTokenHandler;
+ return this;
+ }
+
+ /**
+ * Disables connection state tracking.
+ */
+ public final HttpClientBuilder disableConnectionState() {
+ connectionStateDisabled = true;
+ return this;
+ }
+
+ /**
+ * Assigns {@link SchemePortResolver} instance.
+ */
+ public final HttpClientBuilder setSchemePortResolver(
+ final SchemePortResolver schemePortResolver) {
+ this.schemePortResolver = schemePortResolver;
+ return this;
+ }
+
+ /**
+ * Assigns User-Agent value.
+ *
+ * Please note this value can be overridden by the {@link #setHttpProcessor(
+ * ch.boye.httpclientandroidlib.protocol.HttpProcessor)} method.
+ */
+ public final HttpClientBuilder setUserAgent(final String userAgent) {
+ this.userAgent = userAgent;
+ return this;
+ }
+
+ /**
+ * Assigns default request header values.
+ *
+ * Please note this value can be overridden by the {@link #setHttpProcessor(
+ * ch.boye.httpclientandroidlib.protocol.HttpProcessor)} method.
+ */
+ public final HttpClientBuilder setDefaultHeaders(final Collection extends Header> defaultHeaders) {
+ this.defaultHeaders = defaultHeaders;
+ return this;
+ }
+
+ /**
+ * Adds this protocol interceptor to the head of the protocol processing list.
+ *
+ * Please note this value can be overridden by the {@link #setHttpProcessor(
+ * ch.boye.httpclientandroidlib.protocol.HttpProcessor)} method.
+ */
+ public final HttpClientBuilder addInterceptorFirst(final HttpResponseInterceptor itcp) {
+ if (itcp == null) {
+ return this;
+ }
+ if (responseFirst == null) {
+ responseFirst = new LinkedList();
+ }
+ responseFirst.addFirst(itcp);
+ return this;
+ }
+
+ /**
+ * Adds this protocol interceptor to the tail of the protocol processing list.
+ *
+ * Please note this value can be overridden by the {@link #setHttpProcessor(
+ * ch.boye.httpclientandroidlib.protocol.HttpProcessor)} method.
+ */
+ public final HttpClientBuilder addInterceptorLast(final HttpResponseInterceptor itcp) {
+ if (itcp == null) {
+ return this;
+ }
+ if (responseLast == null) {
+ responseLast = new LinkedList();
+ }
+ responseLast.addLast(itcp);
+ return this;
+ }
+
+ /**
+ * Adds this protocol interceptor to the head of the protocol processing list.
+ *
+ * Please note this value can be overridden by the {@link #setHttpProcessor(
+ * ch.boye.httpclientandroidlib.protocol.HttpProcessor)} method.
+ */
+ public final HttpClientBuilder addInterceptorFirst(final HttpRequestInterceptor itcp) {
+ if (itcp == null) {
+ return this;
+ }
+ if (requestFirst == null) {
+ requestFirst = new LinkedList();
+ }
+ requestFirst.addFirst(itcp);
+ return this;
+ }
+
+ /**
+ * Adds this protocol interceptor to the tail of the protocol processing list.
+ *
+ * Please note this value can be overridden by the {@link #setHttpProcessor(
+ * ch.boye.httpclientandroidlib.protocol.HttpProcessor)} method.
+ */
+ public final HttpClientBuilder addInterceptorLast(final HttpRequestInterceptor itcp) {
+ if (itcp == null) {
+ return this;
+ }
+ if (requestLast == null) {
+ requestLast = new LinkedList();
+ }
+ requestLast.addLast(itcp);
+ return this;
+ }
+
+ /**
+ * Disables state (cookie) management.
+ *
+ * Please note this value can be overridden by the {@link #setHttpProcessor(
+ * ch.boye.httpclientandroidlib.protocol.HttpProcessor)} method.
+ */
+ public final HttpClientBuilder disableCookieManagement() {
+ this.cookieManagementDisabled = true;
+ return this;
+ }
+
+ /**
+ * Disables automatic content decompression.
+ *
+ * Please note this value can be overridden by the {@link #setHttpProcessor(
+ * ch.boye.httpclientandroidlib.protocol.HttpProcessor)} method.
+ */
+ public final HttpClientBuilder disableContentCompression() {
+ contentCompressionDisabled = true;
+ return this;
+ }
+
+ /**
+ * Disables authentication scheme caching.
+ *
+ * Please note this value can be overridden by the {@link #setHttpProcessor(
+ * ch.boye.httpclientandroidlib.protocol.HttpProcessor)} method.
+ */
+ public final HttpClientBuilder disableAuthCaching() {
+ this.authCachingDisabled = true;
+ return this;
+ }
+
+ /**
+ * Assigns {@link HttpProcessor} instance.
+ */
+ public final HttpClientBuilder setHttpProcessor(final HttpProcessor httpprocessor) {
+ this.httpprocessor = httpprocessor;
+ return this;
+ }
+
+ /**
+ * Assigns {@link HttpRequestRetryHandler} instance.
+ *
+ * Please note this value can be overridden by the {@link #disableAutomaticRetries()}
+ * method.
+ */
+ public final HttpClientBuilder setRetryHandler(final HttpRequestRetryHandler retryHandler) {
+ this.retryHandler = retryHandler;
+ return this;
+ }
+
+ /**
+ * Disables automatic request recovery and re-execution.
+ */
+ public final HttpClientBuilder disableAutomaticRetries() {
+ automaticRetriesDisabled = true;
+ return this;
+ }
+
+ /**
+ * Assigns default proxy value.
+ *
+ * Please note this value can be overridden by the {@link #setRoutePlanner(
+ * ch.boye.httpclientandroidlib.conn.routing.HttpRoutePlanner)} method.
+ */
+ public final HttpClientBuilder setProxy(final HttpHost proxy) {
+ this.proxy = proxy;
+ return this;
+ }
+
+ /**
+ * Assigns {@link HttpRoutePlanner} instance.
+ */
+ public final HttpClientBuilder setRoutePlanner(final HttpRoutePlanner routePlanner) {
+ this.routePlanner = routePlanner;
+ return this;
+ }
+
+ /**
+ * Assigns {@link RedirectStrategy} instance.
+ *
+ * Please note this value can be overridden by the {@link #disableRedirectHandling()}
+ * method.
+` */
+ public final HttpClientBuilder setRedirectStrategy(final RedirectStrategy redirectStrategy) {
+ this.redirectStrategy = redirectStrategy;
+ return this;
+ }
+
+ /**
+ * Disables automatic redirect handling.
+ */
+ public final HttpClientBuilder disableRedirectHandling() {
+ redirectHandlingDisabled = true;
+ return this;
+ }
+
+ /**
+ * Assigns {@link ConnectionBackoffStrategy} instance.
+ */
+ public final HttpClientBuilder setConnectionBackoffStrategy(
+ final ConnectionBackoffStrategy connectionBackoffStrategy) {
+ this.connectionBackoffStrategy = connectionBackoffStrategy;
+ return this;
+ }
+
+ /**
+ * Assigns {@link BackoffManager} instance.
+ */
+ public final HttpClientBuilder setBackoffManager(final BackoffManager backoffManager) {
+ this.backoffManager = backoffManager;
+ return this;
+ }
+
+ /**
+ * Assigns {@link ServiceUnavailableRetryStrategy} instance.
+ */
+ public final HttpClientBuilder setServiceUnavailableRetryStrategy(
+ final ServiceUnavailableRetryStrategy serviceUnavailStrategy) {
+ this.serviceUnavailStrategy = serviceUnavailStrategy;
+ return this;
+ }
+
+ /**
+ * Assigns default {@link CookieStore} instance which will be used for
+ * request execution if not explicitly set in the client execution context.
+ */
+ public final HttpClientBuilder setDefaultCookieStore(final CookieStore cookieStore) {
+ this.cookieStore = cookieStore;
+ return this;
+ }
+
+ /**
+ * Assigns default {@link CredentialsProvider} instance which will be used
+ * for request execution if not explicitly set in the client execution
+ * context.
+ */
+ public final HttpClientBuilder setDefaultCredentialsProvider(
+ final CredentialsProvider credentialsProvider) {
+ this.credentialsProvider = credentialsProvider;
+ return this;
+ }
+
+ /**
+ * Assigns default {@link ch.boye.httpclientandroidlib.auth.AuthScheme} registry which will
+ * be used for request execution if not explicitly set in the client execution
+ * context.
+ */
+ public final HttpClientBuilder setDefaultAuthSchemeRegistry(
+ final Lookup authSchemeRegistry) {
+ this.authSchemeRegistry = authSchemeRegistry;
+ return this;
+ }
+
+ /**
+ * Assigns default {@link ch.boye.httpclientandroidlib.cookie.CookieSpec} registry which will
+ * be used for request execution if not explicitly set in the client execution
+ * context.
+ */
+ public final HttpClientBuilder setDefaultCookieSpecRegistry(
+ final Lookup cookieSpecRegistry) {
+ this.cookieSpecRegistry = cookieSpecRegistry;
+ return this;
+ }
+
+ /**
+ * Assigns default {@link RequestConfig} instance which will be used
+ * for request execution if not explicitly set in the client execution
+ * context.
+ */
+ public final HttpClientBuilder setDefaultRequestConfig(final RequestConfig config) {
+ this.defaultRequestConfig = config;
+ return this;
+ }
+
+ /**
+ * Use system properties when creating and configuring default
+ * implementations.
+ */
+ public final HttpClientBuilder useSystemProperties() {
+ systemProperties = true;
+ return this;
+ }
+
+ /**
+ * For internal use.
+ */
+ protected ClientExecChain decorateMainExec(final ClientExecChain mainExec) {
+ return mainExec;
+ }
+
+ /**
+ * For internal use.
+ */
+ protected ClientExecChain decorateProtocolExec(final ClientExecChain protocolExec) {
+ return protocolExec;
+ }
+
+ /**
+ * For internal use.
+ */
+ protected void addCloseable(final Closeable closeable) {
+ if (closeable == null) {
+ return;
+ }
+ if (closeables == null) {
+ closeables = new ArrayList();
+ }
+ closeables.add(closeable);
+ }
+
+ private static String[] split(final String s) {
+ if (TextUtils.isBlank(s)) {
+ return null;
+ }
+ return s.split(" *, *");
+ }
+
+ public CloseableHttpClient build() {
+ // Create main request executor
+ HttpRequestExecutor requestExec = this.requestExec;
+ if (requestExec == null) {
+ requestExec = new HttpRequestExecutor();
+ }
+ HttpClientConnectionManager connManager = this.connManager;
+ if (connManager == null) {
+ LayeredConnectionSocketFactory sslSocketFactory = this.sslSocketFactory;
+ if (sslSocketFactory == null) {
+ final String[] supportedProtocols = systemProperties ? split(
+ System.getProperty("https.protocols")) : null;
+ final String[] supportedCipherSuites = systemProperties ? split(
+ System.getProperty("https.cipherSuites")) : null;
+ X509HostnameVerifier hostnameVerifier = this.hostnameVerifier;
+ if (hostnameVerifier == null) {
+ hostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
+ }
+ if (sslcontext != null) {
+ sslSocketFactory = new SSLConnectionSocketFactory(
+ sslcontext, supportedProtocols, supportedCipherSuites, hostnameVerifier);
+ } else {
+ if (systemProperties) {
+ sslSocketFactory = new SSLConnectionSocketFactory(
+ (SSLSocketFactory) SSLSocketFactory.getDefault(),
+ supportedProtocols, supportedCipherSuites, hostnameVerifier);
+ } else {
+ sslSocketFactory = new SSLConnectionSocketFactory(
+ SSLContexts.createDefault(),
+ hostnameVerifier);
+ }
+ }
+ }
+ @SuppressWarnings("resource")
+ final PoolingHttpClientConnectionManager poolingmgr = new PoolingHttpClientConnectionManager(
+ RegistryBuilder.create()
+ .register("http", PlainConnectionSocketFactory.getSocketFactory())
+ .register("https", sslSocketFactory)
+ .build());
+ if (defaultSocketConfig != null) {
+ poolingmgr.setDefaultSocketConfig(defaultSocketConfig);
+ }
+ if (defaultConnectionConfig != null) {
+ poolingmgr.setDefaultConnectionConfig(defaultConnectionConfig);
+ }
+ if (systemProperties) {
+ String s = System.getProperty("http.keepAlive", "true");
+ if ("true".equalsIgnoreCase(s)) {
+ s = System.getProperty("http.maxConnections", "5");
+ final int max = Integer.parseInt(s);
+ poolingmgr.setDefaultMaxPerRoute(max);
+ poolingmgr.setMaxTotal(2 * max);
+ }
+ }
+ if (maxConnTotal > 0) {
+ poolingmgr.setMaxTotal(maxConnTotal);
+ }
+ if (maxConnPerRoute > 0) {
+ poolingmgr.setDefaultMaxPerRoute(maxConnPerRoute);
+ }
+ connManager = poolingmgr;
+ }
+ ConnectionReuseStrategy reuseStrategy = this.reuseStrategy;
+ if (reuseStrategy == null) {
+ if (systemProperties) {
+ final String s = System.getProperty("http.keepAlive", "true");
+ if ("true".equalsIgnoreCase(s)) {
+ reuseStrategy = DefaultConnectionReuseStrategy.INSTANCE;
+ } else {
+ reuseStrategy = NoConnectionReuseStrategy.INSTANCE;
+ }
+ } else {
+ reuseStrategy = DefaultConnectionReuseStrategy.INSTANCE;
+ }
+ }
+ ConnectionKeepAliveStrategy keepAliveStrategy = this.keepAliveStrategy;
+ if (keepAliveStrategy == null) {
+ keepAliveStrategy = DefaultConnectionKeepAliveStrategy.INSTANCE;
+ }
+ AuthenticationStrategy targetAuthStrategy = this.targetAuthStrategy;
+ if (targetAuthStrategy == null) {
+ targetAuthStrategy = TargetAuthenticationStrategy.INSTANCE;
+ }
+ AuthenticationStrategy proxyAuthStrategy = this.proxyAuthStrategy;
+ if (proxyAuthStrategy == null) {
+ proxyAuthStrategy = ProxyAuthenticationStrategy.INSTANCE;
+ }
+ UserTokenHandler userTokenHandler = this.userTokenHandler;
+ if (userTokenHandler == null) {
+ if (!connectionStateDisabled) {
+ userTokenHandler = DefaultUserTokenHandler.INSTANCE;
+ } else {
+ userTokenHandler = NoopUserTokenHandler.INSTANCE;
+ }
+ }
+ ClientExecChain execChain = new MainClientExec(
+ requestExec,
+ connManager,
+ reuseStrategy,
+ keepAliveStrategy,
+ targetAuthStrategy,
+ proxyAuthStrategy,
+ userTokenHandler);
+
+ execChain = decorateMainExec(execChain);
+
+ HttpProcessor httpprocessor = this.httpprocessor;
+ if (httpprocessor == null) {
+
+ String userAgent = this.userAgent;
+ if (userAgent == null) {
+ if (systemProperties) {
+ userAgent = System.getProperty("http.agent");
+ }
+ if (userAgent == null) {
+ userAgent = DEFAULT_USER_AGENT;
+ }
+ }
+
+ final HttpProcessorBuilder b = HttpProcessorBuilder.create();
+ if (requestFirst != null) {
+ for (final HttpRequestInterceptor i: requestFirst) {
+ b.addFirst(i);
+ }
+ }
+ if (responseFirst != null) {
+ for (final HttpResponseInterceptor i: responseFirst) {
+ b.addFirst(i);
+ }
+ }
+ b.addAll(
+ new RequestDefaultHeaders(defaultHeaders),
+ new RequestContent(),
+ new RequestTargetHost(),
+ new RequestClientConnControl(),
+ new RequestUserAgent(userAgent),
+ new RequestExpectContinue());
+ if (!cookieManagementDisabled) {
+ b.add(new RequestAddCookies());
+ }
+ if (!contentCompressionDisabled) {
+ b.add(new RequestAcceptEncoding());
+ }
+ if (!authCachingDisabled) {
+ b.add(new RequestAuthCache());
+ }
+ if (!cookieManagementDisabled) {
+ b.add(new ResponseProcessCookies());
+ }
+ if (!contentCompressionDisabled) {
+ b.add(new ResponseContentEncoding());
+ }
+ if (requestLast != null) {
+ for (final HttpRequestInterceptor i: requestLast) {
+ b.addLast(i);
+ }
+ }
+ if (responseLast != null) {
+ for (final HttpResponseInterceptor i: responseLast) {
+ b.addLast(i);
+ }
+ }
+ httpprocessor = b.build();
+ }
+ execChain = new ProtocolExec(execChain, httpprocessor);
+
+ execChain = decorateProtocolExec(execChain);
+
+ // Add request retry executor, if not disabled
+ if (!automaticRetriesDisabled) {
+ HttpRequestRetryHandler retryHandler = this.retryHandler;
+ if (retryHandler == null) {
+ retryHandler = DefaultHttpRequestRetryHandler.INSTANCE;
+ }
+ execChain = new RetryExec(execChain, retryHandler);
+ }
+
+ HttpRoutePlanner routePlanner = this.routePlanner;
+ if (routePlanner == null) {
+ SchemePortResolver schemePortResolver = this.schemePortResolver;
+ if (schemePortResolver == null) {
+ schemePortResolver = DefaultSchemePortResolver.INSTANCE;
+ }
+ if (proxy != null) {
+ routePlanner = new DefaultProxyRoutePlanner(proxy, schemePortResolver);
+ } else if (systemProperties) {
+ routePlanner = new SystemDefaultRoutePlanner(
+ schemePortResolver, ProxySelector.getDefault());
+ } else {
+ routePlanner = new DefaultRoutePlanner(schemePortResolver);
+ }
+ }
+ // Add redirect executor, if not disabled
+ if (!redirectHandlingDisabled) {
+ RedirectStrategy redirectStrategy = this.redirectStrategy;
+ if (redirectStrategy == null) {
+ redirectStrategy = DefaultRedirectStrategy.INSTANCE;
+ }
+ execChain = new RedirectExec(execChain, routePlanner, redirectStrategy);
+ }
+
+ // Optionally, add service unavailable retry executor
+ final ServiceUnavailableRetryStrategy serviceUnavailStrategy = this.serviceUnavailStrategy;
+ if (serviceUnavailStrategy != null) {
+ execChain = new ServiceUnavailableRetryExec(execChain, serviceUnavailStrategy);
+ }
+ // Optionally, add connection back-off executor
+ final BackoffManager backoffManager = this.backoffManager;
+ final ConnectionBackoffStrategy connectionBackoffStrategy = this.connectionBackoffStrategy;
+ if (backoffManager != null && connectionBackoffStrategy != null) {
+ execChain = new BackoffStrategyExec(execChain, connectionBackoffStrategy, backoffManager);
+ }
+
+ Lookup authSchemeRegistry = this.authSchemeRegistry;
+ if (authSchemeRegistry == null) {
+ authSchemeRegistry = RegistryBuilder.create()
+ .register(AuthSchemes.BASIC, new BasicSchemeFactory())
+ .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
+ .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
+ /* SPNegoSchemeFactory removed by HttpClient for Android script. */
+ /* KerberosSchemeFactory removed by HttpClient for Android script. */
+ .build();
+ }
+ Lookup cookieSpecRegistry = this.cookieSpecRegistry;
+ if (cookieSpecRegistry == null) {
+ cookieSpecRegistry = RegistryBuilder.create()
+ .register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
+ .register(CookieSpecs.STANDARD, new RFC2965SpecFactory())
+ .register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory())
+ .register(CookieSpecs.NETSCAPE, new NetscapeDraftSpecFactory())
+ .register(CookieSpecs.IGNORE_COOKIES, new IgnoreSpecFactory())
+ .register("rfc2109", new RFC2109SpecFactory())
+ .register("rfc2965", new RFC2965SpecFactory())
+ .build();
+ }
+
+ CookieStore defaultCookieStore = this.cookieStore;
+ if (defaultCookieStore == null) {
+ defaultCookieStore = new BasicCookieStore();
+ }
+
+ CredentialsProvider defaultCredentialsProvider = this.credentialsProvider;
+ if (defaultCredentialsProvider == null) {
+ if (systemProperties) {
+ defaultCredentialsProvider = new SystemDefaultCredentialsProvider();
+ } else {
+ defaultCredentialsProvider = new BasicCredentialsProvider();
+ }
+ }
+
+ return new InternalHttpClient(
+ execChain,
+ connManager,
+ routePlanner,
+ cookieSpecRegistry,
+ authSchemeRegistry,
+ defaultCookieStore,
+ defaultCredentialsProvider,
+ defaultRequestConfig != null ? defaultRequestConfig : RequestConfig.DEFAULT,
+ closeables != null ? new ArrayList(closeables) : null);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/HttpClients.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/HttpClients.java
new file mode 100644
index 000000000..294ac636b
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/HttpClients.java
@@ -0,0 +1,85 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.conn.HttpClientConnectionManager;
+import ch.boye.httpclientandroidlib.impl.conn.PoolingHttpClientConnectionManager;
+
+/**
+ * Factory methods for {@link CloseableHttpClient} instances.
+ * @since 4.3
+ */
+@Immutable
+public class HttpClients {
+
+ private HttpClients() {
+ super();
+ }
+
+ /**
+ * Creates builder object for construction of custom
+ * {@link CloseableHttpClient} instances.
+ */
+ public static HttpClientBuilder custom() {
+ return HttpClientBuilder.create();
+ }
+
+ /**
+ * Creates {@link CloseableHttpClient} instance with default
+ * configuration.
+ */
+ public static CloseableHttpClient createDefault() {
+ return HttpClientBuilder.create().build();
+ }
+
+ /**
+ * Creates {@link CloseableHttpClient} instance with default
+ * configuration based on ssytem properties.
+ */
+ public static CloseableHttpClient createSystem() {
+ return HttpClientBuilder.create().useSystemProperties().build();
+ }
+
+ /**
+ * Creates {@link CloseableHttpClient} instance that implements
+ * the most basic HTTP protocol support.
+ */
+ public static CloseableHttpClient createMinimal() {
+ return new MinimalHttpClient(new PoolingHttpClientConnectionManager());
+ }
+
+ /**
+ * Creates {@link CloseableHttpClient} instance that implements
+ * the most basic HTTP protocol support.
+ */
+ public static CloseableHttpClient createMinimal(final HttpClientConnectionManager connManager) {
+ return new MinimalHttpClient(connManager);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/HttpRequestFutureTask.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/HttpRequestFutureTask.java
new file mode 100644
index 000000000..b5f932403
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/HttpRequestFutureTask.java
@@ -0,0 +1,118 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.util.concurrent.FutureTask;
+
+import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest;
+
+/**
+ * FutureTask implementation that wraps a HttpAsyncClientCallable and exposes various task
+ * specific metrics.
+ *
+ * @param
+ */
+public class HttpRequestFutureTask extends FutureTask {
+
+ private final HttpUriRequest request;
+ private final HttpRequestTaskCallable callable;
+
+ public HttpRequestFutureTask(
+ final HttpUriRequest request,
+ final HttpRequestTaskCallable httpCallable) {
+ super(httpCallable);
+ this.request = request;
+ this.callable = httpCallable;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.concurrent.FutureTask#cancel(boolean)
+ */
+ @Override
+ public boolean cancel(final boolean mayInterruptIfRunning) {
+ callable.cancel();
+ if (mayInterruptIfRunning) {
+ request.abort();
+ }
+ return super.cancel(mayInterruptIfRunning);
+ }
+
+ /**
+ * @return the time in millis the task was scheduled.
+ */
+ public long scheduledTime() {
+ return callable.getScheduled();
+ }
+
+ /**
+ * @return the time in millis the task was started.
+ */
+ public long startedTime() {
+ return callable.getStarted();
+ }
+
+ /**
+ * @return the time in millis the task was finished/cancelled.
+ */
+ public long endedTime() {
+ if (isDone()) {
+ return callable.getEnded();
+ } else {
+ throw new IllegalStateException("Task is not done yet");
+ }
+ }
+
+ /**
+ * @return the time in millis it took to make the request (excluding the time it was
+ * scheduled to be executed).
+ */
+ public long requestDuration() {
+ if (isDone()) {
+ return endedTime() - startedTime();
+ } else {
+ throw new IllegalStateException("Task is not done yet");
+ }
+ }
+
+ /**
+ * @return the time in millis it took to execute the task from the moment it was scheduled.
+ */
+ public long taskDuration() {
+ if (isDone()) {
+ return endedTime() - scheduledTime();
+ } else {
+ throw new IllegalStateException("Task is not done yet");
+ }
+ }
+
+ @Override
+ public String toString() {
+ return request.getRequestLine().getUri();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/HttpRequestTaskCallable.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/HttpRequestTaskCallable.java
new file mode 100644
index 000000000..42e95f0aa
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/HttpRequestTaskCallable.java
@@ -0,0 +1,119 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import ch.boye.httpclientandroidlib.client.HttpClient;
+import ch.boye.httpclientandroidlib.client.ResponseHandler;
+import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest;
+import ch.boye.httpclientandroidlib.concurrent.FutureCallback;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+class HttpRequestTaskCallable implements Callable {
+
+ private final HttpUriRequest request;
+ private final HttpClient httpclient;
+ private final AtomicBoolean cancelled = new AtomicBoolean(false);
+
+ private final long scheduled = System.currentTimeMillis();
+ private long started = -1;
+ private long ended = -1;
+
+ private final HttpContext context;
+ private final ResponseHandler responseHandler;
+ private final FutureCallback callback;
+
+ private final FutureRequestExecutionMetrics metrics;
+
+ HttpRequestTaskCallable(
+ final HttpClient httpClient,
+ final HttpUriRequest request,
+ final HttpContext context,
+ final ResponseHandler responseHandler,
+ final FutureCallback callback,
+ final FutureRequestExecutionMetrics metrics) {
+ this.httpclient = httpClient;
+ this.responseHandler = responseHandler;
+ this.request = request;
+ this.context = context;
+ this.callback = callback;
+ this.metrics = metrics;
+ }
+
+ public long getScheduled() {
+ return scheduled;
+ }
+
+ public long getStarted() {
+ return started;
+ }
+
+ public long getEnded() {
+ return ended;
+ }
+
+ public V call() throws Exception {
+ if (!cancelled.get()) {
+ try {
+ metrics.getActiveConnections().incrementAndGet();
+ started = System.currentTimeMillis();
+ try {
+ metrics.getScheduledConnections().decrementAndGet();
+ final V result = httpclient.execute(request, responseHandler, context);
+ ended = System.currentTimeMillis();
+ metrics.getSuccessfulConnections().increment(started);
+ if (callback != null) {
+ callback.completed(result);
+ }
+ return result;
+ } catch (final Exception e) {
+ metrics.getFailedConnections().increment(started);
+ ended = System.currentTimeMillis();
+ if (callback != null) {
+ callback.failed(e);
+ }
+ throw e;
+ }
+ } finally {
+ metrics.getRequests().increment(started);
+ metrics.getTasks().increment(started);
+ metrics.getActiveConnections().decrementAndGet();
+ }
+ } else {
+ throw new IllegalStateException("call has been cancelled for request " + request.getURI());
+ }
+ }
+
+ public void cancel() {
+ cancelled.set(true);
+ if (callback != null) {
+ callback.cancelled();
+ }
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/InternalHttpClient.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/InternalHttpClient.java
new file mode 100644
index 000000000..c445fe181
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/InternalHttpClient.java
@@ -0,0 +1,242 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.auth.AuthSchemeProvider;
+import ch.boye.httpclientandroidlib.auth.AuthState;
+import ch.boye.httpclientandroidlib.client.ClientProtocolException;
+import ch.boye.httpclientandroidlib.client.CookieStore;
+import ch.boye.httpclientandroidlib.client.CredentialsProvider;
+import ch.boye.httpclientandroidlib.client.config.RequestConfig;
+import ch.boye.httpclientandroidlib.client.methods.CloseableHttpResponse;
+import ch.boye.httpclientandroidlib.client.methods.Configurable;
+import ch.boye.httpclientandroidlib.client.methods.HttpExecutionAware;
+import ch.boye.httpclientandroidlib.client.methods.HttpRequestWrapper;
+import ch.boye.httpclientandroidlib.client.params.ClientPNames;
+import ch.boye.httpclientandroidlib.client.params.HttpClientParamConfig;
+import ch.boye.httpclientandroidlib.client.protocol.HttpClientContext;
+import ch.boye.httpclientandroidlib.config.Lookup;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionRequest;
+import ch.boye.httpclientandroidlib.conn.HttpClientConnectionManager;
+import ch.boye.httpclientandroidlib.conn.ManagedClientConnection;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoutePlanner;
+import ch.boye.httpclientandroidlib.conn.scheme.SchemeRegistry;
+import ch.boye.httpclientandroidlib.cookie.CookieSpecProvider;
+import ch.boye.httpclientandroidlib.impl.execchain.ClientExecChain;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.params.HttpParamsNames;
+import ch.boye.httpclientandroidlib.protocol.BasicHttpContext;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Internal class.
+ *
+ * @since 4.3
+ */
+@ThreadSafe
+@SuppressWarnings("deprecation")
+class InternalHttpClient extends CloseableHttpClient {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ private final ClientExecChain execChain;
+ private final HttpClientConnectionManager connManager;
+ private final HttpRoutePlanner routePlanner;
+ private final Lookup cookieSpecRegistry;
+ private final Lookup authSchemeRegistry;
+ private final CookieStore cookieStore;
+ private final CredentialsProvider credentialsProvider;
+ private final RequestConfig defaultConfig;
+ private final List closeables;
+
+ public InternalHttpClient(
+ final ClientExecChain execChain,
+ final HttpClientConnectionManager connManager,
+ final HttpRoutePlanner routePlanner,
+ final Lookup cookieSpecRegistry,
+ final Lookup authSchemeRegistry,
+ final CookieStore cookieStore,
+ final CredentialsProvider credentialsProvider,
+ final RequestConfig defaultConfig,
+ final List closeables) {
+ super();
+ Args.notNull(execChain, "HTTP client exec chain");
+ Args.notNull(connManager, "HTTP connection manager");
+ Args.notNull(routePlanner, "HTTP route planner");
+ this.execChain = execChain;
+ this.connManager = connManager;
+ this.routePlanner = routePlanner;
+ this.cookieSpecRegistry = cookieSpecRegistry;
+ this.authSchemeRegistry = authSchemeRegistry;
+ this.cookieStore = cookieStore;
+ this.credentialsProvider = credentialsProvider;
+ this.defaultConfig = defaultConfig;
+ this.closeables = closeables;
+ }
+
+ private HttpRoute determineRoute(
+ final HttpHost target,
+ final HttpRequest request,
+ final HttpContext context) throws HttpException {
+ HttpHost host = target;
+ if (host == null) {
+ host = (HttpHost) request.getParams().getParameter(ClientPNames.DEFAULT_HOST);
+ }
+ return this.routePlanner.determineRoute(host, request, context);
+ }
+
+ private void setupContext(final HttpClientContext context) {
+ if (context.getAttribute(HttpClientContext.TARGET_AUTH_STATE) == null) {
+ context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, new AuthState());
+ }
+ if (context.getAttribute(HttpClientContext.PROXY_AUTH_STATE) == null) {
+ context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, new AuthState());
+ }
+ if (context.getAttribute(HttpClientContext.AUTHSCHEME_REGISTRY) == null) {
+ context.setAttribute(HttpClientContext.AUTHSCHEME_REGISTRY, this.authSchemeRegistry);
+ }
+ if (context.getAttribute(HttpClientContext.COOKIESPEC_REGISTRY) == null) {
+ context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry);
+ }
+ if (context.getAttribute(HttpClientContext.COOKIE_STORE) == null) {
+ context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);
+ }
+ if (context.getAttribute(HttpClientContext.CREDS_PROVIDER) == null) {
+ context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credentialsProvider);
+ }
+ if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
+ context.setAttribute(HttpClientContext.REQUEST_CONFIG, this.defaultConfig);
+ }
+ }
+
+ @Override
+ protected CloseableHttpResponse doExecute(
+ final HttpHost target,
+ final HttpRequest request,
+ final HttpContext context) throws IOException, ClientProtocolException {
+ Args.notNull(request, "HTTP request");
+ HttpExecutionAware execAware = null;
+ if (request instanceof HttpExecutionAware) {
+ execAware = (HttpExecutionAware) request;
+ }
+ try {
+ final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(request);
+ final HttpClientContext localcontext = HttpClientContext.adapt(
+ context != null ? context : new BasicHttpContext());
+ RequestConfig config = null;
+ if (request instanceof Configurable) {
+ config = ((Configurable) request).getConfig();
+ }
+ if (config == null) {
+ final HttpParams params = request.getParams();
+ if (params instanceof HttpParamsNames) {
+ if (!((HttpParamsNames) params).getNames().isEmpty()) {
+ config = HttpClientParamConfig.getRequestConfig(params);
+ }
+ } else {
+ config = HttpClientParamConfig.getRequestConfig(params);
+ }
+ }
+ if (config != null) {
+ localcontext.setRequestConfig(config);
+ }
+ setupContext(localcontext);
+ final HttpRoute route = determineRoute(target, wrapper, localcontext);
+ return this.execChain.execute(route, wrapper, localcontext, execAware);
+ } catch (final HttpException httpException) {
+ throw new ClientProtocolException(httpException);
+ }
+ }
+
+ public void close() {
+ this.connManager.shutdown();
+ if (this.closeables != null) {
+ for (final Closeable closeable: this.closeables) {
+ try {
+ closeable.close();
+ } catch (final IOException ex) {
+ this.log.error(ex.getMessage(), ex);
+ }
+ }
+ }
+ }
+
+ public HttpParams getParams() {
+ throw new UnsupportedOperationException();
+ }
+
+ public ClientConnectionManager getConnectionManager() {
+
+ return new ClientConnectionManager() {
+
+ public void shutdown() {
+ connManager.shutdown();
+ }
+
+ public ClientConnectionRequest requestConnection(
+ final HttpRoute route, final Object state) {
+ throw new UnsupportedOperationException();
+ }
+
+ public void releaseConnection(
+ final ManagedClientConnection conn,
+ final long validDuration, final TimeUnit timeUnit) {
+ throw new UnsupportedOperationException();
+ }
+
+ public SchemeRegistry getSchemeRegistry() {
+ throw new UnsupportedOperationException();
+ }
+
+ public void closeIdleConnections(final long idletime, final TimeUnit tunit) {
+ connManager.closeIdleConnections(idletime, tunit);
+ }
+
+ public void closeExpiredConnections() {
+ connManager.closeExpiredConnections();
+ }
+
+ };
+
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/LaxRedirectStrategy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/LaxRedirectStrategy.java
new file mode 100644
index 000000000..47688e642
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/LaxRedirectStrategy.java
@@ -0,0 +1,65 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.methods.HttpGet;
+import ch.boye.httpclientandroidlib.client.methods.HttpHead;
+import ch.boye.httpclientandroidlib.client.methods.HttpPost;
+
+/**
+ * Lax {@link ch.boye.httpclientandroidlib.client.RedirectStrategy} implementation
+ * that automatically redirects all HEAD, GET and POST requests.
+ * This strategy relaxes restrictions on automatic redirection of
+ * POST methods imposed by the HTTP specification.
+ *
+ * @since 4.2
+ */
+@Immutable
+public class LaxRedirectStrategy extends DefaultRedirectStrategy {
+
+ /**
+ * Redirectable methods.
+ */
+ private static final String[] REDIRECT_METHODS = new String[] {
+ HttpGet.METHOD_NAME,
+ HttpPost.METHOD_NAME,
+ HttpHead.METHOD_NAME
+ };
+
+ @Override
+ protected boolean isRedirectable(final String method) {
+ for (final String m: REDIRECT_METHODS) {
+ if (m.equalsIgnoreCase(method)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/MinimalHttpClient.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/MinimalHttpClient.java
new file mode 100644
index 000000000..8b0c21127
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/MinimalHttpClient.java
@@ -0,0 +1,156 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.io.IOException;
+import java.util.concurrent.TimeUnit;
+
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.client.ClientProtocolException;
+import ch.boye.httpclientandroidlib.client.config.RequestConfig;
+import ch.boye.httpclientandroidlib.client.methods.CloseableHttpResponse;
+import ch.boye.httpclientandroidlib.client.methods.Configurable;
+import ch.boye.httpclientandroidlib.client.methods.HttpExecutionAware;
+import ch.boye.httpclientandroidlib.client.methods.HttpRequestWrapper;
+import ch.boye.httpclientandroidlib.client.protocol.HttpClientContext;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionRequest;
+import ch.boye.httpclientandroidlib.conn.HttpClientConnectionManager;
+import ch.boye.httpclientandroidlib.conn.ManagedClientConnection;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.conn.scheme.SchemeRegistry;
+import ch.boye.httpclientandroidlib.impl.DefaultConnectionReuseStrategy;
+import ch.boye.httpclientandroidlib.impl.execchain.MinimalClientExec;
+import ch.boye.httpclientandroidlib.params.BasicHttpParams;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.BasicHttpContext;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.protocol.HttpRequestExecutor;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Internal class.
+ *
+ * @since 4.3
+ */
+@ThreadSafe
+@SuppressWarnings("deprecation")
+class MinimalHttpClient extends CloseableHttpClient {
+
+ private final HttpClientConnectionManager connManager;
+ private final MinimalClientExec requestExecutor;
+ private final HttpParams params;
+
+ public MinimalHttpClient(
+ final HttpClientConnectionManager connManager) {
+ super();
+ this.connManager = Args.notNull(connManager, "HTTP connection manager");
+ this.requestExecutor = new MinimalClientExec(
+ new HttpRequestExecutor(),
+ connManager,
+ DefaultConnectionReuseStrategy.INSTANCE,
+ DefaultConnectionKeepAliveStrategy.INSTANCE);
+ this.params = new BasicHttpParams();
+ }
+
+ @Override
+ protected CloseableHttpResponse doExecute(
+ final HttpHost target,
+ final HttpRequest request,
+ final HttpContext context) throws IOException, ClientProtocolException {
+ Args.notNull(target, "Target host");
+ Args.notNull(request, "HTTP request");
+ HttpExecutionAware execAware = null;
+ if (request instanceof HttpExecutionAware) {
+ execAware = (HttpExecutionAware) request;
+ }
+ try {
+ final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(request);
+ final HttpClientContext localcontext = HttpClientContext.adapt(
+ context != null ? context : new BasicHttpContext());
+ final HttpRoute route = new HttpRoute(target);
+ RequestConfig config = null;
+ if (request instanceof Configurable) {
+ config = ((Configurable) request).getConfig();
+ }
+ if (config != null) {
+ localcontext.setRequestConfig(config);
+ }
+ return this.requestExecutor.execute(route, wrapper, localcontext, execAware);
+ } catch (final HttpException httpException) {
+ throw new ClientProtocolException(httpException);
+ }
+ }
+
+ public HttpParams getParams() {
+ return this.params;
+ }
+
+ public void close() {
+ this.connManager.shutdown();
+ }
+
+ public ClientConnectionManager getConnectionManager() {
+
+ return new ClientConnectionManager() {
+
+ public void shutdown() {
+ connManager.shutdown();
+ }
+
+ public ClientConnectionRequest requestConnection(
+ final HttpRoute route, final Object state) {
+ throw new UnsupportedOperationException();
+ }
+
+ public void releaseConnection(
+ final ManagedClientConnection conn,
+ final long validDuration, final TimeUnit timeUnit) {
+ throw new UnsupportedOperationException();
+ }
+
+ public SchemeRegistry getSchemeRegistry() {
+ throw new UnsupportedOperationException();
+ }
+
+ public void closeIdleConnections(final long idletime, final TimeUnit tunit) {
+ connManager.closeIdleConnections(idletime, tunit);
+ }
+
+ public void closeExpiredConnections() {
+ connManager.closeExpiredConnections();
+ }
+
+ };
+
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/NoopUserTokenHandler.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/NoopUserTokenHandler.java
new file mode 100644
index 000000000..1e8eb3bde
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/NoopUserTokenHandler.java
@@ -0,0 +1,47 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.UserTokenHandler;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+/**
+ * Noop implementation of {@link UserTokenHandler} that always returns null.
+ *
+ * @since 4.3
+ */
+@Immutable
+public class NoopUserTokenHandler implements UserTokenHandler {
+
+ public static final NoopUserTokenHandler INSTANCE = new NoopUserTokenHandler();
+
+ public Object getUserToken(final HttpContext context) {
+ return null;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/NullBackoffStrategy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/NullBackoffStrategy.java
new file mode 100644
index 000000000..8cad78d75
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/NullBackoffStrategy.java
@@ -0,0 +1,47 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.client.ConnectionBackoffStrategy;
+
+/**
+ * This is a {@link ConnectionBackoffStrategy} that never backs off,
+ * for compatibility with existing behavior.
+ *
+ * @since 4.2
+ */
+public class NullBackoffStrategy implements ConnectionBackoffStrategy {
+
+ public boolean shouldBackoff(final Throwable t) {
+ return false;
+ }
+
+ public boolean shouldBackoff(final HttpResponse resp) {
+ return false;
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/ProxyAuthenticationStrategy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/ProxyAuthenticationStrategy.java
new file mode 100644
index 000000000..636143630
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/ProxyAuthenticationStrategy.java
@@ -0,0 +1,57 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.util.Collection;
+
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.auth.AUTH;
+import ch.boye.httpclientandroidlib.client.config.RequestConfig;
+
+/**
+ * Default {@link ch.boye.httpclientandroidlib.client.AuthenticationStrategy} implementation
+ * for proxy host authentication.
+ *
+ * @since 4.2
+ */
+@Immutable
+public class ProxyAuthenticationStrategy extends AuthenticationStrategyImpl {
+
+ public static final ProxyAuthenticationStrategy INSTANCE = new ProxyAuthenticationStrategy();
+
+ public ProxyAuthenticationStrategy() {
+ super(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED, AUTH.PROXY_AUTH);
+ }
+
+ @Override
+ Collection getPreferredAuthSchemes(final RequestConfig config) {
+ return config.getProxyPreferredAuthSchemes();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/ProxyClient.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/ProxyClient.java
new file mode 100644
index 000000000..e1211bc4b
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/ProxyClient.java
@@ -0,0 +1,254 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.io.IOException;
+import java.net.Socket;
+
+import ch.boye.httpclientandroidlib.ConnectionReuseStrategy;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpVersion;
+import ch.boye.httpclientandroidlib.auth.AUTH;
+import ch.boye.httpclientandroidlib.auth.AuthSchemeRegistry;
+import ch.boye.httpclientandroidlib.auth.AuthScope;
+import ch.boye.httpclientandroidlib.auth.AuthState;
+import ch.boye.httpclientandroidlib.auth.Credentials;
+import ch.boye.httpclientandroidlib.client.config.AuthSchemes;
+import ch.boye.httpclientandroidlib.client.config.RequestConfig;
+import ch.boye.httpclientandroidlib.client.params.HttpClientParamConfig;
+import ch.boye.httpclientandroidlib.client.protocol.HttpClientContext;
+import ch.boye.httpclientandroidlib.client.protocol.RequestClientConnControl;
+import ch.boye.httpclientandroidlib.config.ConnectionConfig;
+import ch.boye.httpclientandroidlib.conn.HttpConnectionFactory;
+import ch.boye.httpclientandroidlib.conn.ManagedHttpClientConnection;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.conn.routing.RouteInfo.LayerType;
+import ch.boye.httpclientandroidlib.conn.routing.RouteInfo.TunnelType;
+import ch.boye.httpclientandroidlib.entity.BufferedHttpEntity;
+import ch.boye.httpclientandroidlib.impl.DefaultConnectionReuseStrategy;
+import ch.boye.httpclientandroidlib.impl.auth.BasicSchemeFactory;
+import ch.boye.httpclientandroidlib.impl.auth.DigestSchemeFactory;
+import ch.boye.httpclientandroidlib.impl.auth.HttpAuthenticator;
+/* KerberosSchemeFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.impl.auth.NTLMSchemeFactory;
+/* SPNegoSchemeFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.impl.conn.ManagedHttpClientConnectionFactory;
+import ch.boye.httpclientandroidlib.impl.execchain.TunnelRefusedException;
+import ch.boye.httpclientandroidlib.message.BasicHttpRequest;
+import ch.boye.httpclientandroidlib.params.BasicHttpParams;
+import ch.boye.httpclientandroidlib.params.HttpParamConfig;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.BasicHttpContext;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.protocol.HttpCoreContext;
+import ch.boye.httpclientandroidlib.protocol.HttpProcessor;
+import ch.boye.httpclientandroidlib.protocol.HttpRequestExecutor;
+import ch.boye.httpclientandroidlib.protocol.ImmutableHttpProcessor;
+import ch.boye.httpclientandroidlib.protocol.RequestTargetHost;
+import ch.boye.httpclientandroidlib.protocol.RequestUserAgent;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.EntityUtils;
+
+/**
+ * ProxyClient can be used to establish a tunnel via an HTTP proxy.
+ */
+@SuppressWarnings("deprecation")
+public class ProxyClient {
+
+ private final HttpConnectionFactory connFactory;
+ private final ConnectionConfig connectionConfig;
+ private final RequestConfig requestConfig;
+ private final HttpProcessor httpProcessor;
+ private final HttpRequestExecutor requestExec;
+ private final ProxyAuthenticationStrategy proxyAuthStrategy;
+ private final HttpAuthenticator authenticator;
+ private final AuthState proxyAuthState;
+ private final AuthSchemeRegistry authSchemeRegistry;
+ private final ConnectionReuseStrategy reuseStrategy;
+
+ /**
+ * @since 4.3
+ */
+ public ProxyClient(
+ final HttpConnectionFactory connFactory,
+ final ConnectionConfig connectionConfig,
+ final RequestConfig requestConfig) {
+ super();
+ this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE;
+ this.connectionConfig = connectionConfig != null ? connectionConfig : ConnectionConfig.DEFAULT;
+ this.requestConfig = requestConfig != null ? requestConfig : RequestConfig.DEFAULT;
+ this.httpProcessor = new ImmutableHttpProcessor(
+ new RequestTargetHost(), new RequestClientConnControl(), new RequestUserAgent());
+ this.requestExec = new HttpRequestExecutor();
+ this.proxyAuthStrategy = new ProxyAuthenticationStrategy();
+ this.authenticator = new HttpAuthenticator();
+ this.proxyAuthState = new AuthState();
+ this.authSchemeRegistry = new AuthSchemeRegistry();
+ this.authSchemeRegistry.register(AuthSchemes.BASIC, new BasicSchemeFactory());
+ this.authSchemeRegistry.register(AuthSchemes.DIGEST, new DigestSchemeFactory());
+ this.authSchemeRegistry.register(AuthSchemes.NTLM, new NTLMSchemeFactory());
+ /* SPNegoSchemeFactory removed by HttpClient for Android script. */
+ /* KerberosSchemeFactory removed by HttpClient for Android script. */
+ this.reuseStrategy = new DefaultConnectionReuseStrategy();
+ }
+
+ /**
+ * @deprecated (4.3) use {@link ProxyClient#ProxyClient(HttpConnectionFactory, ConnectionConfig, RequestConfig)}
+ */
+ @Deprecated
+ public ProxyClient(final HttpParams params) {
+ this(null,
+ HttpParamConfig.getConnectionConfig(params),
+ HttpClientParamConfig.getRequestConfig(params));
+ }
+
+ /**
+ * @since 4.3
+ */
+ public ProxyClient(final RequestConfig requestConfig) {
+ this(null, null, requestConfig);
+ }
+
+ public ProxyClient() {
+ this(null, null, null);
+ }
+
+ /**
+ * @deprecated (4.3) do not use.
+ */
+ @Deprecated
+ public HttpParams getParams() {
+ return new BasicHttpParams();
+ }
+
+ /**
+ * @deprecated (4.3) do not use.
+ */
+ @Deprecated
+ public AuthSchemeRegistry getAuthSchemeRegistry() {
+ return this.authSchemeRegistry;
+ }
+
+ public Socket tunnel(
+ final HttpHost proxy,
+ final HttpHost target,
+ final Credentials credentials) throws IOException, HttpException {
+ Args.notNull(proxy, "Proxy host");
+ Args.notNull(target, "Target host");
+ Args.notNull(credentials, "Credentials");
+ HttpHost host = target;
+ if (host.getPort() <= 0) {
+ host = new HttpHost(host.getHostName(), 80, host.getSchemeName());
+ }
+ final HttpRoute route = new HttpRoute(
+ host,
+ this.requestConfig.getLocalAddress(),
+ proxy, false, TunnelType.TUNNELLED, LayerType.PLAIN);
+
+ final ManagedHttpClientConnection conn = this.connFactory.create(
+ route, this.connectionConfig);
+ final HttpContext context = new BasicHttpContext();
+ HttpResponse response;
+
+ final HttpRequest connect = new BasicHttpRequest(
+ "CONNECT", host.toHostString(), HttpVersion.HTTP_1_1);
+
+ final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
+ credsProvider.setCredentials(new AuthScope(proxy), credentials);
+
+ // Populate the execution context
+ context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
+ context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn);
+ context.setAttribute(HttpCoreContext.HTTP_REQUEST, connect);
+ context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
+ context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, this.proxyAuthState);
+ context.setAttribute(HttpClientContext.CREDS_PROVIDER, credsProvider);
+ context.setAttribute(HttpClientContext.AUTHSCHEME_REGISTRY, this.authSchemeRegistry);
+ context.setAttribute(HttpClientContext.REQUEST_CONFIG, this.requestConfig);
+
+ this.requestExec.preProcess(connect, this.httpProcessor, context);
+
+ for (;;) {
+ if (!conn.isOpen()) {
+ final Socket socket = new Socket(proxy.getHostName(), proxy.getPort());
+ conn.bind(socket);
+ }
+
+ this.authenticator.generateAuthResponse(connect, this.proxyAuthState, context);
+
+ response = this.requestExec.execute(connect, conn, context);
+
+ final int status = response.getStatusLine().getStatusCode();
+ if (status < 200) {
+ throw new HttpException("Unexpected response to CONNECT request: " +
+ response.getStatusLine());
+ }
+ if (this.authenticator.isAuthenticationRequested(proxy, response,
+ this.proxyAuthStrategy, this.proxyAuthState, context)) {
+ if (this.authenticator.handleAuthChallenge(proxy, response,
+ this.proxyAuthStrategy, this.proxyAuthState, context)) {
+ // Retry request
+ if (this.reuseStrategy.keepAlive(response, context)) {
+ // Consume response content
+ final HttpEntity entity = response.getEntity();
+ EntityUtils.consume(entity);
+ } else {
+ conn.close();
+ }
+ // discard previous auth header
+ connect.removeHeaders(AUTH.PROXY_AUTH_RESP);
+ } else {
+ break;
+ }
+ } else {
+ break;
+ }
+ }
+
+ final int status = response.getStatusLine().getStatusCode();
+
+ if (status > 299) {
+
+ // Buffer response content
+ final HttpEntity entity = response.getEntity();
+ if (entity != null) {
+ response.setEntity(new BufferedHttpEntity(entity));
+ }
+
+ conn.close();
+ throw new TunnelRefusedException("CONNECT refused by proxy: " +
+ response.getStatusLine(), response);
+ }
+ return conn.getSocket();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/RedirectLocations.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/RedirectLocations.java
new file mode 100644
index 000000000..872dc167f
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/RedirectLocations.java
@@ -0,0 +1,227 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.net.URI;
+import java.util.AbstractList;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+
+/**
+ * This class represents a collection of {@link java.net.URI}s used
+ * as redirect locations.
+ *
+ * @since 4.0
+ */
+@NotThreadSafe // HashSet/ArrayList are not synch.
+public class RedirectLocations extends AbstractList {
+
+ private final Set unique;
+ private final List all;
+
+ public RedirectLocations() {
+ super();
+ this.unique = new HashSet();
+ this.all = new ArrayList();
+ }
+
+ /**
+ * Test if the URI is present in the collection.
+ */
+ public boolean contains(final URI uri) {
+ return this.unique.contains(uri);
+ }
+
+ /**
+ * Adds a new URI to the collection.
+ */
+ public void add(final URI uri) {
+ this.unique.add(uri);
+ this.all.add(uri);
+ }
+
+ /**
+ * Removes a URI from the collection.
+ */
+ public boolean remove(final URI uri) {
+ final boolean removed = this.unique.remove(uri);
+ if (removed) {
+ final Iterator it = this.all.iterator();
+ while (it.hasNext()) {
+ final URI current = it.next();
+ if (current.equals(uri)) {
+ it.remove();
+ }
+ }
+ }
+ return removed;
+ }
+
+ /**
+ * Returns all redirect {@link URI}s in the order they were added to the collection.
+ *
+ * @return list of all URIs
+ *
+ * @since 4.1
+ */
+ public List getAll() {
+ return new ArrayList(this.all);
+ }
+
+ /**
+ * Returns the URI at the specified position in this list.
+ *
+ * @param index
+ * index of the location to return
+ * @return the URI at the specified position in this list
+ * @throws IndexOutOfBoundsException
+ * if the index is out of range (
+ * index < 0 || index >= size())
+ * @since 4.3
+ */
+ @Override
+ public URI get(final int index) {
+ return this.all.get(index);
+ }
+
+ /**
+ * Returns the number of elements in this list. If this list contains more
+ * than Integer.MAX_VALUE elements, returns
+ * Integer.MAX_VALUE.
+ *
+ * @return the number of elements in this list
+ * @since 4.3
+ */
+ @Override
+ public int size() {
+ return this.all.size();
+ }
+
+ /**
+ * Replaces the URI at the specified position in this list with the
+ * specified element (must be a URI).
+ *
+ * @param index
+ * index of the element to replace
+ * @param element
+ * URI to be stored at the specified position
+ * @return the URI previously at the specified position
+ * @throws UnsupportedOperationException
+ * if the set operation is not supported by this list
+ * @throws ClassCastException
+ * if the element is not a {@link URI}
+ * @throws NullPointerException
+ * if the specified element is null and this list does not
+ * permit null elements
+ * @throws IndexOutOfBoundsException
+ * if the index is out of range (
+ * index < 0 || index >= size())
+ * @since 4.3
+ */
+ @Override
+ public Object set(final int index, final Object element) {
+ final URI removed = this.all.set(index, (URI) element);
+ this.unique.remove(removed);
+ this.unique.add((URI) element);
+ if (this.all.size() != this.unique.size()) {
+ this.unique.addAll(this.all);
+ }
+ return removed;
+ }
+
+ /**
+ * Inserts the specified element at the specified position in this list
+ * (must be a URI). Shifts the URI currently at that position (if any) and
+ * any subsequent URIs to the right (adds one to their indices).
+ *
+ * @param index
+ * index at which the specified element is to be inserted
+ * @param element
+ * URI to be inserted
+ * @throws UnsupportedOperationException
+ * if the add operation is not supported by this list
+ * @throws ClassCastException
+ * if the element is not a {@link URI}
+ * @throws NullPointerException
+ * if the specified element is null and this list does not
+ * permit null elements
+ * @throws IndexOutOfBoundsException
+ * if the index is out of range (
+ * index < 0 || index > size())
+ * @since 4.3
+ */
+ @Override
+ public void add(final int index, final Object element) {
+ this.all.add(index, (URI) element);
+ this.unique.add((URI) element);
+ }
+
+ /**
+ * Removes the URI at the specified position in this list. Shifts any
+ * subsequent URIs to the left (subtracts one from their indices). Returns
+ * the URI that was removed from the list.
+ *
+ * @param index
+ * the index of the URI to be removed
+ * @return the URI previously at the specified position
+ * @throws IndexOutOfBoundsException
+ * if the index is out of range (
+ * index < 0 || index >= size())
+ * @since 4.3
+ */
+ @Override
+ public URI remove(final int index) {
+ final URI removed = this.all.remove(index);
+ this.unique.remove(removed);
+ if (this.all.size() != this.unique.size()) {
+ this.unique.addAll(this.all);
+ }
+ return removed;
+ }
+
+ /**
+ * Returns true if this collection contains the specified element.
+ * More formally, returns true if and only if this collection
+ * contains at least one element e such that
+ * (o==null ? e==null : o.equals(e)).
+ *
+ * @param o element whose presence in this collection is to be tested
+ * @return true if this collection contains the specified
+ * element
+ */
+ @Override
+ public boolean contains(final Object o) {
+ return this.unique.contains(o);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/RequestWrapper.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/RequestWrapper.java
new file mode 100644
index 000000000..3577b61a6
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/RequestWrapper.java
@@ -0,0 +1,164 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.ProtocolException;
+import ch.boye.httpclientandroidlib.ProtocolVersion;
+import ch.boye.httpclientandroidlib.RequestLine;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest;
+import ch.boye.httpclientandroidlib.message.AbstractHttpMessage;
+import ch.boye.httpclientandroidlib.message.BasicRequestLine;
+import ch.boye.httpclientandroidlib.params.HttpProtocolParams;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * A wrapper class for {@link HttpRequest}s that can be used to change
+ * properties of the current request without modifying the original
+ * object.
+ *
+ * This class is also capable of resetting the request headers to
+ * the state of the original request.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) do not use.
+ */
+@NotThreadSafe
+@Deprecated
+public class RequestWrapper extends AbstractHttpMessage implements HttpUriRequest {
+
+ private final HttpRequest original;
+
+ private URI uri;
+ private String method;
+ private ProtocolVersion version;
+ private int execCount;
+
+ public RequestWrapper(final HttpRequest request) throws ProtocolException {
+ super();
+ Args.notNull(request, "HTTP request");
+ this.original = request;
+ setParams(request.getParams());
+ setHeaders(request.getAllHeaders());
+ // Make a copy of the original URI
+ if (request instanceof HttpUriRequest) {
+ this.uri = ((HttpUriRequest) request).getURI();
+ this.method = ((HttpUriRequest) request).getMethod();
+ this.version = null;
+ } else {
+ final RequestLine requestLine = request.getRequestLine();
+ try {
+ this.uri = new URI(requestLine.getUri());
+ } catch (final URISyntaxException ex) {
+ throw new ProtocolException("Invalid request URI: "
+ + requestLine.getUri(), ex);
+ }
+ this.method = requestLine.getMethod();
+ this.version = request.getProtocolVersion();
+ }
+ this.execCount = 0;
+ }
+
+ public void resetHeaders() {
+ // Make a copy of original headers
+ this.headergroup.clear();
+ setHeaders(this.original.getAllHeaders());
+ }
+
+ public String getMethod() {
+ return this.method;
+ }
+
+ public void setMethod(final String method) {
+ Args.notNull(method, "Method name");
+ this.method = method;
+ }
+
+ public ProtocolVersion getProtocolVersion() {
+ if (this.version == null) {
+ this.version = HttpProtocolParams.getVersion(getParams());
+ }
+ return this.version;
+ }
+
+ public void setProtocolVersion(final ProtocolVersion version) {
+ this.version = version;
+ }
+
+
+ public URI getURI() {
+ return this.uri;
+ }
+
+ public void setURI(final URI uri) {
+ this.uri = uri;
+ }
+
+ public RequestLine getRequestLine() {
+ final String method = getMethod();
+ final ProtocolVersion ver = getProtocolVersion();
+ String uritext = null;
+ if (uri != null) {
+ uritext = uri.toASCIIString();
+ }
+ if (uritext == null || uritext.length() == 0) {
+ uritext = "/";
+ }
+ return new BasicRequestLine(method, uritext, ver);
+ }
+
+ public void abort() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean isAborted() {
+ return false;
+ }
+
+ public HttpRequest getOriginal() {
+ return this.original;
+ }
+
+ public boolean isRepeatable() {
+ return true;
+ }
+
+ public int getExecCount() {
+ return this.execCount;
+ }
+
+ public void incrementExecCount() {
+ this.execCount++;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/RoutedRequest.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/RoutedRequest.java
new file mode 100644
index 000000000..2e5ff76e9
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/RoutedRequest.java
@@ -0,0 +1,67 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+
+/**
+ * A request with the route along which it should be sent.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) do not use.
+ */
+@Deprecated
+@NotThreadSafe // RequestWrapper is @NotThreadSafe
+public class RoutedRequest {
+
+ protected final RequestWrapper request; // @NotThreadSafe
+ protected final HttpRoute route; // @Immutable
+
+ /**
+ * Creates a new routed request.
+ *
+ * @param req the request
+ * @param route the route
+ */
+ public RoutedRequest(final RequestWrapper req, final HttpRoute route) {
+ super();
+ this.request = req;
+ this.route = route;
+ }
+
+ public final RequestWrapper getRequest() {
+ return request;
+ }
+
+ public final HttpRoute getRoute() {
+ return route;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/StandardHttpRequestRetryHandler.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/StandardHttpRequestRetryHandler.java
new file mode 100644
index 000000000..ec0ce7e00
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/StandardHttpRequestRetryHandler.java
@@ -0,0 +1,80 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+
+/**
+ * {@link ch.boye.httpclientandroidlib.client.HttpRequestRetryHandler} which assumes
+ * that all requested HTTP methods which should be idempotent according
+ * to RFC-2616 are in fact idempotent and can be retried.
+ *
+ * According to RFC-2616 section 9.1.2 the idempotent HTTP methods are:
+ * GET, HEAD, PUT, DELETE, OPTIONS, and TRACE
+ *
+ * @since 4.2
+ */
+@Immutable
+public class StandardHttpRequestRetryHandler extends DefaultHttpRequestRetryHandler {
+
+ private final Map idempotentMethods;
+
+ /**
+ * Default constructor
+ */
+ public StandardHttpRequestRetryHandler(final int retryCount, final boolean requestSentRetryEnabled) {
+ super(retryCount, requestSentRetryEnabled);
+ this.idempotentMethods = new ConcurrentHashMap();
+ this.idempotentMethods.put("GET", Boolean.TRUE);
+ this.idempotentMethods.put("HEAD", Boolean.TRUE);
+ this.idempotentMethods.put("PUT", Boolean.TRUE);
+ this.idempotentMethods.put("DELETE", Boolean.TRUE);
+ this.idempotentMethods.put("OPTIONS", Boolean.TRUE);
+ this.idempotentMethods.put("TRACE", Boolean.TRUE);
+ }
+
+ /**
+ * Default constructor
+ */
+ public StandardHttpRequestRetryHandler() {
+ this(3, false);
+ }
+
+ @Override
+ protected boolean handleAsIdempotent(final HttpRequest request) {
+ final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
+ final Boolean b = this.idempotentMethods.get(method);
+ return b != null && b.booleanValue();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/SystemClock.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/SystemClock.java
new file mode 100644
index 000000000..b037af841
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/SystemClock.java
@@ -0,0 +1,40 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+/**
+ * The actual system clock.
+ *
+ * @since 4.2
+ */
+class SystemClock implements Clock {
+
+ public long getCurrentTime() {
+ return System.currentTimeMillis();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/SystemDefaultCredentialsProvider.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/SystemDefaultCredentialsProvider.java
new file mode 100644
index 000000000..1327b71dc
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/SystemDefaultCredentialsProvider.java
@@ -0,0 +1,145 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.net.Authenticator;
+import java.net.PasswordAuthentication;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.auth.AuthScope;
+import ch.boye.httpclientandroidlib.auth.Credentials;
+import ch.boye.httpclientandroidlib.auth.NTCredentials;
+import ch.boye.httpclientandroidlib.auth.UsernamePasswordCredentials;
+import ch.boye.httpclientandroidlib.client.CredentialsProvider;
+import ch.boye.httpclientandroidlib.client.config.AuthSchemes;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Implementation of {@link CredentialsProvider} backed by standard
+ * JRE {@link Authenticator}.
+ *
+ * @since 4.3
+ */
+@ThreadSafe
+public class SystemDefaultCredentialsProvider implements CredentialsProvider {
+
+ private static final Map SCHEME_MAP;
+
+ static {
+ SCHEME_MAP = new ConcurrentHashMap();
+ SCHEME_MAP.put(AuthSchemes.BASIC.toUpperCase(Locale.ENGLISH), "Basic");
+ SCHEME_MAP.put(AuthSchemes.DIGEST.toUpperCase(Locale.ENGLISH), "Digest");
+ SCHEME_MAP.put(AuthSchemes.NTLM.toUpperCase(Locale.ENGLISH), "NTLM");
+ SCHEME_MAP.put(AuthSchemes.SPNEGO.toUpperCase(Locale.ENGLISH), "SPNEGO");
+ SCHEME_MAP.put(AuthSchemes.KERBEROS.toUpperCase(Locale.ENGLISH), "Kerberos");
+ }
+
+ private static String translateScheme(final String key) {
+ if (key == null) {
+ return null;
+ }
+ final String s = SCHEME_MAP.get(key);
+ return s != null ? s : key;
+ }
+
+ private final BasicCredentialsProvider internal;
+
+ /**
+ * Default constructor.
+ */
+ public SystemDefaultCredentialsProvider() {
+ super();
+ this.internal = new BasicCredentialsProvider();
+ }
+
+ public void setCredentials(final AuthScope authscope, final Credentials credentials) {
+ internal.setCredentials(authscope, credentials);
+ }
+
+ private static PasswordAuthentication getSystemCreds(
+ final AuthScope authscope,
+ final Authenticator.RequestorType requestorType) {
+ final String hostname = authscope.getHost();
+ final int port = authscope.getPort();
+ final String protocol = port == 443 ? "https" : "http";
+ return Authenticator.requestPasswordAuthentication(
+ hostname,
+ null,
+ port,
+ protocol,
+ null,
+ translateScheme(authscope.getScheme()),
+ null,
+ requestorType);
+ }
+
+ public Credentials getCredentials(final AuthScope authscope) {
+ Args.notNull(authscope, "Auth scope");
+ final Credentials localcreds = internal.getCredentials(authscope);
+ if (localcreds != null) {
+ return localcreds;
+ }
+ if (authscope.getHost() != null) {
+ PasswordAuthentication systemcreds = getSystemCreds(
+ authscope, Authenticator.RequestorType.SERVER);
+ if (systemcreds == null) {
+ systemcreds = getSystemCreds(
+ authscope, Authenticator.RequestorType.PROXY);
+ }
+ if (systemcreds != null) {
+ final String domain = System.getProperty("http.auth.ntlm.domain");
+ if (domain != null) {
+ return new NTCredentials(
+ systemcreds.getUserName(),
+ new String(systemcreds.getPassword()),
+ null, domain);
+ } else {
+ if (AuthSchemes.NTLM.equalsIgnoreCase(authscope.getScheme())) {
+ // Domian may be specified in a fully qualified user name
+ return new NTCredentials(
+ systemcreds.getUserName(),
+ new String(systemcreds.getPassword()),
+ null, null);
+ } else {
+ return new UsernamePasswordCredentials(
+ systemcreds.getUserName(),
+ new String(systemcreds.getPassword()));
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ public void clear() {
+ internal.clear();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/SystemDefaultHttpClient.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/SystemDefaultHttpClient.java
new file mode 100644
index 000000000..0806537ed
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/SystemDefaultHttpClient.java
@@ -0,0 +1,149 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.net.ProxySelector;
+
+import ch.boye.httpclientandroidlib.ConnectionReuseStrategy;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoutePlanner;
+import ch.boye.httpclientandroidlib.impl.DefaultConnectionReuseStrategy;
+import ch.boye.httpclientandroidlib.impl.NoConnectionReuseStrategy;
+import ch.boye.httpclientandroidlib.impl.conn.PoolingClientConnectionManager;
+import ch.boye.httpclientandroidlib.impl.conn.ProxySelectorRoutePlanner;
+import ch.boye.httpclientandroidlib.impl.conn.SchemeRegistryFactory;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+
+/**
+ * An extension of {@link DefaultHttpClient} pre-configured using system properties.
+ *
+ * The following system properties are taken into account by this class:
+ *
+ *
ssl.TrustManagerFactory.algorithm
+ *
javax.net.ssl.trustStoreType
+ *
javax.net.ssl.trustStore
+ *
javax.net.ssl.trustStoreProvider
+ *
javax.net.ssl.trustStorePassword
+ *
java.home
+ *
ssl.KeyManagerFactory.algorithm
+ *
javax.net.ssl.keyStoreType
+ *
javax.net.ssl.keyStore
+ *
javax.net.ssl.keyStoreProvider
+ *
javax.net.ssl.keyStorePassword
+ *
http.proxyHost
+ *
http.proxyPort
+ *
http.nonProxyHosts
+ *
http.keepAlive
+ *
http.maxConnections
+ *
+ *
+ *
+ * The following parameters can be used to customize the behavior of this
+ * class:
+ *
+ *
+ * @since 4.2
+ *
+ * @deprecated (4.3) use {@link HttpClientBuilder}
+ */
+@ThreadSafe
+@Deprecated
+public class SystemDefaultHttpClient extends DefaultHttpClient {
+
+ public SystemDefaultHttpClient(final HttpParams params) {
+ super(null, params);
+ }
+
+ public SystemDefaultHttpClient() {
+ super(null, null);
+ }
+
+ @Override
+ protected ClientConnectionManager createClientConnectionManager() {
+ final PoolingClientConnectionManager connmgr = new PoolingClientConnectionManager(
+ SchemeRegistryFactory.createSystemDefault());
+ String s = System.getProperty("http.keepAlive", "true");
+ if ("true".equalsIgnoreCase(s)) {
+ s = System.getProperty("http.maxConnections", "5");
+ final int max = Integer.parseInt(s);
+ connmgr.setDefaultMaxPerRoute(max);
+ connmgr.setMaxTotal(2 * max);
+ }
+ return connmgr;
+ }
+
+ @Override
+ protected HttpRoutePlanner createHttpRoutePlanner() {
+ return new ProxySelectorRoutePlanner(getConnectionManager().getSchemeRegistry(),
+ ProxySelector.getDefault());
+ }
+
+ @Override
+ protected ConnectionReuseStrategy createConnectionReuseStrategy() {
+ final String s = System.getProperty("http.keepAlive", "true");
+ if ("true".equalsIgnoreCase(s)) {
+ return new DefaultConnectionReuseStrategy();
+ } else {
+ return new NoConnectionReuseStrategy();
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/TargetAuthenticationStrategy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/TargetAuthenticationStrategy.java
new file mode 100644
index 000000000..486167dc1
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/TargetAuthenticationStrategy.java
@@ -0,0 +1,57 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import java.util.Collection;
+
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.auth.AUTH;
+import ch.boye.httpclientandroidlib.client.config.RequestConfig;
+
+/**
+ * Default {@link ch.boye.httpclientandroidlib.client.AuthenticationStrategy} implementation
+ * for proxy host authentication.
+ *
+ * @since 4.2
+ */
+@Immutable
+public class TargetAuthenticationStrategy extends AuthenticationStrategyImpl {
+
+ public static final TargetAuthenticationStrategy INSTANCE = new TargetAuthenticationStrategy();
+
+ public TargetAuthenticationStrategy() {
+ super(HttpStatus.SC_UNAUTHORIZED, AUTH.WWW_AUTH);
+ }
+
+ @Override
+ Collection getPreferredAuthSchemes(final RequestConfig config) {
+ return config.getTargetPreferredAuthSchemes();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/TunnelRefusedException.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/TunnelRefusedException.java
new file mode 100644
index 000000000..97edac1f0
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/TunnelRefusedException.java
@@ -0,0 +1,58 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client;
+
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+
+/**
+ * Signals that the tunnel request was rejected by the proxy host.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) reserved for internal use.
+ */
+@Deprecated
+@Immutable
+public class TunnelRefusedException extends HttpException {
+
+ private static final long serialVersionUID = -8646722842745617323L;
+
+ private final HttpResponse response;
+
+ public TunnelRefusedException(final String message, final HttpResponse response) {
+ super(message);
+ this.response = response;
+ }
+
+ public HttpResponse getResponse() {
+ return this.response;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/AsynchronousValidationRequest.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/AsynchronousValidationRequest.java
new file mode 100644
index 000000000..60ad6ca1f
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/AsynchronousValidationRequest.java
@@ -0,0 +1,178 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.client.cache.HeaderConstants;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.client.methods.HttpExecutionAware;
+import ch.boye.httpclientandroidlib.client.methods.HttpRequestWrapper;
+import ch.boye.httpclientandroidlib.client.methods.CloseableHttpResponse;
+import ch.boye.httpclientandroidlib.client.protocol.HttpClientContext;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+
+/**
+ * Class used to represent an asynchronous revalidation event, such as with
+ * "stale-while-revalidate"
+ */
+class AsynchronousValidationRequest implements Runnable {
+ private final AsynchronousValidator parent;
+ private final CachingExec cachingExec;
+ private final HttpRoute route;
+ private final HttpRequestWrapper request;
+ private final HttpClientContext context;
+ private final HttpExecutionAware execAware;
+ private final HttpCacheEntry cacheEntry;
+ private final String identifier;
+ private final int consecutiveFailedAttempts;
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ /**
+ * Used internally by {@link AsynchronousValidator} to schedule a
+ * revalidation.
+ * @param request
+ * @param context
+ * @param cacheEntry
+ * @param identifier
+ * @param consecutiveFailedAttempts
+ */
+ AsynchronousValidationRequest(
+ final AsynchronousValidator parent,
+ final CachingExec cachingExec,
+ final HttpRoute route,
+ final HttpRequestWrapper request,
+ final HttpClientContext context,
+ final HttpExecutionAware execAware,
+ final HttpCacheEntry cacheEntry,
+ final String identifier,
+ final int consecutiveFailedAttempts) {
+ this.parent = parent;
+ this.cachingExec = cachingExec;
+ this.route = route;
+ this.request = request;
+ this.context = context;
+ this.execAware = execAware;
+ this.cacheEntry = cacheEntry;
+ this.identifier = identifier;
+ this.consecutiveFailedAttempts = consecutiveFailedAttempts;
+ }
+
+ public void run() {
+ try {
+ if (revalidateCacheEntry()) {
+ parent.jobSuccessful(identifier);
+ } else {
+ parent.jobFailed(identifier);
+ }
+ } finally {
+ parent.markComplete(identifier);
+ }
+ }
+
+ /**
+ * Revalidate the cache entry and return if the operation was successful.
+ * Success means a connection to the server was established and replay did
+ * not indicate a server error.
+ * @return true if the cache entry was successfully validated;
+ * otherwise false
+ */
+ protected boolean revalidateCacheEntry() {
+ try {
+ final CloseableHttpResponse httpResponse = cachingExec.revalidateCacheEntry(route, request, context, execAware, cacheEntry);
+ try {
+ final int statusCode = httpResponse.getStatusLine().getStatusCode();
+ return isNotServerError(statusCode) && isNotStale(httpResponse);
+ } finally {
+ httpResponse.close();
+ }
+ } catch (final IOException ioe) {
+ log.debug("Asynchronous revalidation failed due to I/O error", ioe);
+ return false;
+ } catch (final HttpException pe) {
+ log.error("HTTP protocol exception during asynchronous revalidation", pe);
+ return false;
+ } catch (final RuntimeException re) {
+ log.error("RuntimeException thrown during asynchronous revalidation: " + re);
+ return false;
+ }
+ }
+
+ /**
+ * Return whether the status code indicates a server error or not.
+ * @param statusCode the status code to be checked
+ * @return if the status code indicates a server error or not
+ */
+ private boolean isNotServerError(final int statusCode) {
+ return statusCode < 500;
+ }
+
+ /**
+ * Try to detect if the returned response is generated from a stale cache entry.
+ * @param httpResponse the response to be checked
+ * @return whether the response is stale or not
+ */
+ private boolean isNotStale(final HttpResponse httpResponse) {
+ final Header[] warnings = httpResponse.getHeaders(HeaderConstants.WARNING);
+ if (warnings != null)
+ {
+ for (final Header warning : warnings)
+ {
+ /**
+ * warn-codes
+ * 110 = Response is stale
+ * 111 = Revalidation failed
+ */
+ final String warningValue = warning.getValue();
+ if (warningValue.startsWith("110") || warningValue.startsWith("111"))
+ {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ String getIdentifier() {
+ return identifier;
+ }
+
+ /**
+ * The number of consecutively failed revalidation attempts.
+ * @return the number of consecutively failed revalidation attempts.
+ */
+ public int getConsecutiveFailedAttempts() {
+ return consecutiveFailedAttempts;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/AsynchronousValidator.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/AsynchronousValidator.java
new file mode 100644
index 000000000..05765a236
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/AsynchronousValidator.java
@@ -0,0 +1,150 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.RejectedExecutionException;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.client.methods.HttpExecutionAware;
+import ch.boye.httpclientandroidlib.client.methods.HttpRequestWrapper;
+import ch.boye.httpclientandroidlib.client.protocol.HttpClientContext;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+
+/**
+ * Class used for asynchronous revalidations to be used when the "stale-
+ * while-revalidate" directive is present
+ */
+class AsynchronousValidator implements Closeable {
+ private final SchedulingStrategy schedulingStrategy;
+ private final Set queued;
+ private final CacheKeyGenerator cacheKeyGenerator;
+ private final FailureCache failureCache;
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ /**
+ * Create AsynchronousValidator which will make revalidation requests
+ * using an {@link ImmediateSchedulingStrategy}. Its thread
+ * pool will be configured according to the given {@link CacheConfig}.
+ * @param config specifies thread pool settings. See
+ * {@link CacheConfig#getAsynchronousWorkersMax()},
+ * {@link CacheConfig#getAsynchronousWorkersCore()},
+ * {@link CacheConfig#getAsynchronousWorkerIdleLifetimeSecs()},
+ * and {@link CacheConfig#getRevalidationQueueSize()}.
+ */
+ public AsynchronousValidator(final CacheConfig config) {
+ this(new ImmediateSchedulingStrategy(config));
+ }
+
+ /**
+ * Create AsynchronousValidator which will make revalidation requests
+ * using the supplied {@link SchedulingStrategy}. Closing the validator
+ * will also close the given schedulingStrategy.
+ * @param schedulingStrategy used to maintain a pool of worker threads and
+ * schedules when requests are executed
+ */
+ AsynchronousValidator(final SchedulingStrategy schedulingStrategy) {
+ this.schedulingStrategy = schedulingStrategy;
+ this.queued = new HashSet();
+ this.cacheKeyGenerator = new CacheKeyGenerator();
+ this.failureCache = new DefaultFailureCache();
+ }
+
+ public void close() throws IOException {
+ schedulingStrategy.close();
+ }
+
+ /**
+ * Schedules an asynchronous revalidation
+ */
+ public synchronized void revalidateCacheEntry(
+ final CachingExec cachingExec,
+ final HttpRoute route,
+ final HttpRequestWrapper request,
+ final HttpClientContext context,
+ final HttpExecutionAware execAware,
+ final HttpCacheEntry entry) {
+ // getVariantURI will fall back on getURI if no variants exist
+ final String uri = cacheKeyGenerator.getVariantURI(context.getTargetHost(), request, entry);
+
+ if (!queued.contains(uri)) {
+ final int consecutiveFailedAttempts = failureCache.getErrorCount(uri);
+ final AsynchronousValidationRequest revalidationRequest =
+ new AsynchronousValidationRequest(
+ this, cachingExec, route, request, context, execAware, entry, uri, consecutiveFailedAttempts);
+
+ try {
+ schedulingStrategy.schedule(revalidationRequest);
+ queued.add(uri);
+ } catch (final RejectedExecutionException ree) {
+ log.debug("Revalidation for [" + uri + "] not scheduled: " + ree);
+ }
+ }
+ }
+
+ /**
+ * Removes an identifier from the internal list of revalidation jobs in
+ * progress. This is meant to be called by
+ * {@link AsynchronousValidationRequest#run()} once the revalidation is
+ * complete, using the identifier passed in during constructions.
+ * @param identifier
+ */
+ synchronized void markComplete(final String identifier) {
+ queued.remove(identifier);
+ }
+
+ /**
+ * The revalidation job was successful thus the number of consecutive
+ * failed attempts will be reset to zero. Should be called by
+ * {@link AsynchronousValidationRequest#run()}.
+ * @param identifier the revalidation job's unique identifier
+ */
+ void jobSuccessful(final String identifier) {
+ failureCache.resetErrorCount(identifier);
+ }
+
+ /**
+ * The revalidation job did fail and thus the number of consecutive failed
+ * attempts will be increased. Should be called by
+ * {@link AsynchronousValidationRequest#run()}.
+ * @param identifier the revalidation job's unique identifier
+ */
+ void jobFailed(final String identifier) {
+ failureCache.increaseErrorCount(identifier);
+ }
+
+ Set getScheduledIdentifiers() {
+ return Collections.unmodifiableSet(queued);
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/BasicHttpCache.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/BasicHttpCache.java
new file mode 100644
index 000000000..4347e173d
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/BasicHttpCache.java
@@ -0,0 +1,376 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.HttpVersion;
+import ch.boye.httpclientandroidlib.client.cache.HeaderConstants;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheInvalidator;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheStorage;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheUpdateCallback;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheUpdateException;
+import ch.boye.httpclientandroidlib.client.cache.Resource;
+import ch.boye.httpclientandroidlib.client.cache.ResourceFactory;
+import ch.boye.httpclientandroidlib.client.methods.CloseableHttpResponse;
+import ch.boye.httpclientandroidlib.entity.ByteArrayEntity;
+import ch.boye.httpclientandroidlib.message.BasicHttpResponse;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+
+class BasicHttpCache implements HttpCache {
+ private static final Set safeRequestMethods = new HashSet(
+ Arrays.asList(HeaderConstants.HEAD_METHOD,
+ HeaderConstants.GET_METHOD, HeaderConstants.OPTIONS_METHOD,
+ HeaderConstants.TRACE_METHOD));
+
+ private final CacheKeyGenerator uriExtractor;
+ private final ResourceFactory resourceFactory;
+ private final long maxObjectSizeBytes;
+ private final CacheEntryUpdater cacheEntryUpdater;
+ private final CachedHttpResponseGenerator responseGenerator;
+ private final HttpCacheInvalidator cacheInvalidator;
+ private final HttpCacheStorage storage;
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ public BasicHttpCache(
+ final ResourceFactory resourceFactory,
+ final HttpCacheStorage storage,
+ final CacheConfig config,
+ final CacheKeyGenerator uriExtractor,
+ final HttpCacheInvalidator cacheInvalidator) {
+ this.resourceFactory = resourceFactory;
+ this.uriExtractor = uriExtractor;
+ this.cacheEntryUpdater = new CacheEntryUpdater(resourceFactory);
+ this.maxObjectSizeBytes = config.getMaxObjectSize();
+ this.responseGenerator = new CachedHttpResponseGenerator();
+ this.storage = storage;
+ this.cacheInvalidator = cacheInvalidator;
+ }
+
+ public BasicHttpCache(
+ final ResourceFactory resourceFactory,
+ final HttpCacheStorage storage,
+ final CacheConfig config,
+ final CacheKeyGenerator uriExtractor) {
+ this( resourceFactory, storage, config, uriExtractor,
+ new CacheInvalidator(uriExtractor, storage));
+ }
+
+ public BasicHttpCache(
+ final ResourceFactory resourceFactory,
+ final HttpCacheStorage storage,
+ final CacheConfig config) {
+ this( resourceFactory, storage, config, new CacheKeyGenerator());
+ }
+
+ public BasicHttpCache(final CacheConfig config) {
+ this(new HeapResourceFactory(), new BasicHttpCacheStorage(config), config);
+ }
+
+ public BasicHttpCache() {
+ this(CacheConfig.DEFAULT);
+ }
+
+ public void flushCacheEntriesFor(final HttpHost host, final HttpRequest request)
+ throws IOException {
+ if (!safeRequestMethods.contains(request.getRequestLine().getMethod())) {
+ final String uri = uriExtractor.getURI(host, request);
+ storage.removeEntry(uri);
+ }
+ }
+
+ public void flushInvalidatedCacheEntriesFor(final HttpHost host, final HttpRequest request, final HttpResponse response) {
+ if (!safeRequestMethods.contains(request.getRequestLine().getMethod())) {
+ cacheInvalidator.flushInvalidatedCacheEntries(host, request, response);
+ }
+ }
+
+ void storeInCache(
+ final HttpHost target, final HttpRequest request, final HttpCacheEntry entry) throws IOException {
+ if (entry.hasVariants()) {
+ storeVariantEntry(target, request, entry);
+ } else {
+ storeNonVariantEntry(target, request, entry);
+ }
+ }
+
+ void storeNonVariantEntry(
+ final HttpHost target, final HttpRequest req, final HttpCacheEntry entry) throws IOException {
+ final String uri = uriExtractor.getURI(target, req);
+ storage.putEntry(uri, entry);
+ }
+
+ void storeVariantEntry(
+ final HttpHost target,
+ final HttpRequest req,
+ final HttpCacheEntry entry) throws IOException {
+ final String parentURI = uriExtractor.getURI(target, req);
+ final String variantURI = uriExtractor.getVariantURI(target, req, entry);
+ storage.putEntry(variantURI, entry);
+
+ final HttpCacheUpdateCallback callback = new HttpCacheUpdateCallback() {
+
+ public HttpCacheEntry update(final HttpCacheEntry existing) throws IOException {
+ return doGetUpdatedParentEntry(
+ req.getRequestLine().getUri(), existing, entry,
+ uriExtractor.getVariantKey(req, entry),
+ variantURI);
+ }
+
+ };
+
+ try {
+ storage.updateEntry(parentURI, callback);
+ } catch (final HttpCacheUpdateException e) {
+ log.warn("Could not update key [" + parentURI + "]", e);
+ }
+ }
+
+ public void reuseVariantEntryFor(final HttpHost target, final HttpRequest req,
+ final Variant variant) throws IOException {
+ final String parentCacheKey = uriExtractor.getURI(target, req);
+ final HttpCacheEntry entry = variant.getEntry();
+ final String variantKey = uriExtractor.getVariantKey(req, entry);
+ final String variantCacheKey = variant.getCacheKey();
+
+ final HttpCacheUpdateCallback callback = new HttpCacheUpdateCallback() {
+ public HttpCacheEntry update(final HttpCacheEntry existing)
+ throws IOException {
+ return doGetUpdatedParentEntry(req.getRequestLine().getUri(),
+ existing, entry, variantKey, variantCacheKey);
+ }
+ };
+
+ try {
+ storage.updateEntry(parentCacheKey, callback);
+ } catch (final HttpCacheUpdateException e) {
+ log.warn("Could not update key [" + parentCacheKey + "]", e);
+ }
+ }
+
+ boolean isIncompleteResponse(final HttpResponse resp, final Resource resource) {
+ final int status = resp.getStatusLine().getStatusCode();
+ if (status != HttpStatus.SC_OK
+ && status != HttpStatus.SC_PARTIAL_CONTENT) {
+ return false;
+ }
+ final Header hdr = resp.getFirstHeader(HTTP.CONTENT_LEN);
+ if (hdr == null) {
+ return false;
+ }
+ final int contentLength;
+ try {
+ contentLength = Integer.parseInt(hdr.getValue());
+ } catch (final NumberFormatException nfe) {
+ return false;
+ }
+ return (resource.length() < contentLength);
+ }
+
+ CloseableHttpResponse generateIncompleteResponseError(
+ final HttpResponse response, final Resource resource) {
+ final int contentLength = Integer.parseInt(response.getFirstHeader(HTTP.CONTENT_LEN).getValue());
+ final HttpResponse error =
+ new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_GATEWAY, "Bad Gateway");
+ error.setHeader("Content-Type","text/plain;charset=UTF-8");
+ final String msg = String.format("Received incomplete response " +
+ "with Content-Length %d but actual body length %d",
+ contentLength, resource.length());
+ final byte[] msgBytes = msg.getBytes();
+ error.setHeader("Content-Length", Integer.toString(msgBytes.length));
+ error.setEntity(new ByteArrayEntity(msgBytes));
+ return Proxies.enhanceResponse(error);
+ }
+
+ HttpCacheEntry doGetUpdatedParentEntry(
+ final String requestId,
+ final HttpCacheEntry existing,
+ final HttpCacheEntry entry,
+ final String variantKey,
+ final String variantCacheKey) throws IOException {
+ HttpCacheEntry src = existing;
+ if (src == null) {
+ src = entry;
+ }
+
+ Resource resource = null;
+ if (src.getResource() != null) {
+ resource = resourceFactory.copy(requestId, src.getResource());
+ }
+ final Map variantMap = new HashMap(src.getVariantMap());
+ variantMap.put(variantKey, variantCacheKey);
+ return new HttpCacheEntry(
+ src.getRequestDate(),
+ src.getResponseDate(),
+ src.getStatusLine(),
+ src.getAllHeaders(),
+ resource,
+ variantMap);
+ }
+
+ public HttpCacheEntry updateCacheEntry(final HttpHost target, final HttpRequest request,
+ final HttpCacheEntry stale, final HttpResponse originResponse,
+ final Date requestSent, final Date responseReceived) throws IOException {
+ final HttpCacheEntry updatedEntry = cacheEntryUpdater.updateCacheEntry(
+ request.getRequestLine().getUri(),
+ stale,
+ requestSent,
+ responseReceived,
+ originResponse);
+ storeInCache(target, request, updatedEntry);
+ return updatedEntry;
+ }
+
+ public HttpCacheEntry updateVariantCacheEntry(final HttpHost target, final HttpRequest request,
+ final HttpCacheEntry stale, final HttpResponse originResponse,
+ final Date requestSent, final Date responseReceived, final String cacheKey) throws IOException {
+ final HttpCacheEntry updatedEntry = cacheEntryUpdater.updateCacheEntry(
+ request.getRequestLine().getUri(),
+ stale,
+ requestSent,
+ responseReceived,
+ originResponse);
+ storage.putEntry(cacheKey, updatedEntry);
+ return updatedEntry;
+ }
+
+ public HttpResponse cacheAndReturnResponse(final HttpHost host, final HttpRequest request,
+ final HttpResponse originResponse, final Date requestSent, final Date responseReceived)
+ throws IOException {
+ return cacheAndReturnResponse(host, request,
+ Proxies.enhanceResponse(originResponse), requestSent,
+ responseReceived);
+ }
+
+ public CloseableHttpResponse cacheAndReturnResponse(
+ final HttpHost host,
+ final HttpRequest request,
+ final CloseableHttpResponse originResponse,
+ final Date requestSent,
+ final Date responseReceived) throws IOException {
+
+ boolean closeOriginResponse = true;
+ final SizeLimitedResponseReader responseReader = getResponseReader(request, originResponse);
+ try {
+ responseReader.readResponse();
+
+ if (responseReader.isLimitReached()) {
+ closeOriginResponse = false;
+ return responseReader.getReconstructedResponse();
+ }
+
+ final Resource resource = responseReader.getResource();
+ if (isIncompleteResponse(originResponse, resource)) {
+ return generateIncompleteResponseError(originResponse, resource);
+ }
+
+ final HttpCacheEntry entry = new HttpCacheEntry(
+ requestSent,
+ responseReceived,
+ originResponse.getStatusLine(),
+ originResponse.getAllHeaders(),
+ resource);
+ storeInCache(host, request, entry);
+ return responseGenerator.generateResponse(entry);
+ } finally {
+ if (closeOriginResponse) {
+ originResponse.close();
+ }
+ }
+ }
+
+ SizeLimitedResponseReader getResponseReader(final HttpRequest request,
+ final CloseableHttpResponse backEndResponse) {
+ return new SizeLimitedResponseReader(
+ resourceFactory, maxObjectSizeBytes, request, backEndResponse);
+ }
+
+ public HttpCacheEntry getCacheEntry(final HttpHost host, final HttpRequest request) throws IOException {
+ final HttpCacheEntry root = storage.getEntry(uriExtractor.getURI(host, request));
+ if (root == null) {
+ return null;
+ }
+ if (!root.hasVariants()) {
+ return root;
+ }
+ final String variantCacheKey = root.getVariantMap().get(uriExtractor.getVariantKey(request, root));
+ if (variantCacheKey == null) {
+ return null;
+ }
+ return storage.getEntry(variantCacheKey);
+ }
+
+ public void flushInvalidatedCacheEntriesFor(final HttpHost host,
+ final HttpRequest request) throws IOException {
+ cacheInvalidator.flushInvalidatedCacheEntries(host, request);
+ }
+
+ public Map getVariantCacheEntriesWithEtags(final HttpHost host, final HttpRequest request)
+ throws IOException {
+ final Map variants = new HashMap();
+ final HttpCacheEntry root = storage.getEntry(uriExtractor.getURI(host, request));
+ if (root == null || !root.hasVariants()) {
+ return variants;
+ }
+ for(final Map.Entry variant : root.getVariantMap().entrySet()) {
+ final String variantKey = variant.getKey();
+ final String variantCacheKey = variant.getValue();
+ addVariantWithEtag(variantKey, variantCacheKey, variants);
+ }
+ return variants;
+ }
+
+ private void addVariantWithEtag(final String variantKey,
+ final String variantCacheKey, final Map variants)
+ throws IOException {
+ final HttpCacheEntry entry = storage.getEntry(variantCacheKey);
+ if (entry == null) {
+ return;
+ }
+ final Header etagHeader = entry.getFirstHeader(HeaderConstants.ETAG);
+ if (etagHeader == null) {
+ return;
+ }
+ variants.put(etagHeader.getValue(), new Variant(variantKey, variantCacheKey, entry));
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/BasicHttpCacheStorage.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/BasicHttpCacheStorage.java
new file mode 100644
index 000000000..225730858
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/BasicHttpCacheStorage.java
@@ -0,0 +1,96 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheStorage;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheUpdateCallback;
+
+/**
+ * Basic {@link HttpCacheStorage} implementation backed by an instance of
+ * {@link java.util.LinkedHashMap}. In other words, cache entries and
+ * the cached response bodies are held in-memory. This cache does NOT
+ * deallocate resources associated with the cache entries; it is intended
+ * for use with {@link HeapResource} and similar. This is the default cache
+ * storage backend used by {@link CachingHttpClients}.
+ *
+ * @since 4.1
+ */
+@ThreadSafe
+public class BasicHttpCacheStorage implements HttpCacheStorage {
+
+ private final CacheMap entries;
+
+ public BasicHttpCacheStorage(final CacheConfig config) {
+ super();
+ this.entries = new CacheMap(config.getMaxCacheEntries());
+ }
+
+ /**
+ * Places a HttpCacheEntry in the cache
+ *
+ * @param url
+ * Url to use as the cache key
+ * @param entry
+ * HttpCacheEntry to place in the cache
+ */
+ public synchronized void putEntry(final String url, final HttpCacheEntry entry) throws IOException {
+ entries.put(url, entry);
+ }
+
+ /**
+ * Gets an entry from the cache, if it exists
+ *
+ * @param url
+ * Url that is the cache key
+ * @return HttpCacheEntry if one exists, or null for cache miss
+ */
+ public synchronized HttpCacheEntry getEntry(final String url) throws IOException {
+ return entries.get(url);
+ }
+
+ /**
+ * Removes a HttpCacheEntry from the cache
+ *
+ * @param url
+ * Url that is the cache key
+ */
+ public synchronized void removeEntry(final String url) throws IOException {
+ entries.remove(url);
+ }
+
+ public synchronized void updateEntry(
+ final String url,
+ final HttpCacheUpdateCallback callback) throws IOException {
+ final HttpCacheEntry existingEntry = entries.get(url);
+ entries.put(url, callback.update(existingEntry));
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/BasicIdGenerator.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/BasicIdGenerator.java
new file mode 100644
index 000000000..defdc3999
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/BasicIdGenerator.java
@@ -0,0 +1,86 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.util.Formatter;
+import java.util.Locale;
+
+import ch.boye.httpclientandroidlib.annotation.GuardedBy;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+
+/**
+ * Should produce reasonably unique tokens.
+ */
+@ThreadSafe
+class BasicIdGenerator {
+
+ private final String hostname;
+ private final SecureRandom rnd;
+
+ @GuardedBy("this")
+ private long count;
+
+ public BasicIdGenerator() {
+ super();
+ String hostname;
+ try {
+ hostname = InetAddress.getLocalHost().getHostName();
+ } catch (final UnknownHostException ex) {
+ hostname = "localhost";
+ }
+ this.hostname = hostname;
+ try {
+ this.rnd = SecureRandom.getInstance("SHA1PRNG");
+ } catch (final NoSuchAlgorithmException ex) {
+ throw new Error(ex);
+ }
+ this.rnd.setSeed(System.currentTimeMillis());
+ }
+
+ public synchronized void generate(final StringBuilder buffer) {
+ this.count++;
+ final int rndnum = this.rnd.nextInt();
+ buffer.append(System.currentTimeMillis());
+ buffer.append('.');
+ final Formatter formatter = new Formatter(buffer, Locale.US);
+ formatter.format("%1$016x-%2$08x", this.count, rndnum);
+ formatter.close();
+ buffer.append('.');
+ buffer.append(this.hostname);
+ }
+
+ public String generate() {
+ final StringBuilder buffer = new StringBuilder();
+ generate(buffer);
+ return buffer.toString();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheConfig.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheConfig.java
new file mode 100644
index 000000000..964ea2719
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheConfig.java
@@ -0,0 +1,764 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ *
Java Beans-style configuration for a {@link CachingHttpClient}. Any class
+ * in the caching module that has configuration options should take a
+ * {@link CacheConfig} argument in one of its constructors. A
+ * {@code CacheConfig} instance has sane and conservative defaults, so the
+ * easiest way to specify options is to get an instance and then set just
+ * the options you want to modify from their defaults.
+ *
+ *
N.B. This class is only for caching-specific configuration; to
+ * configure the behavior of the rest of the client, configure the
+ * {@link ch.boye.httpclientandroidlib.client.HttpClient} used as the "backend"
+ * for the {@code CachingHttpClient}.
+ *
+ *
Cache configuration can be grouped into the following categories:
+ *
+ *
Cache size. If the backend storage supports these limits, you
+ * can specify the {@link CacheConfig#getMaxCacheEntries maximum number of
+ * cache entries} as well as the {@link CacheConfig#getMaxObjectSizeBytes
+ * maximum cacheable response body size}.
+ *
+ *
Public/private caching. By default, the caching module considers
+ * itself to be a shared (public) cache, and will not, for example, cache
+ * responses to requests with {@code Authorization} headers or responses
+ * marked with {@code Cache-Control: private}. If, however, the cache
+ * is only going to be used by one logical "user" (behaving similarly to a
+ * browser cache), then you will want to {@link
+ * CacheConfig#setSharedCache(boolean) turn off the shared cache setting}.
+ *
+ *
303 caching. RFC2616 explicitly disallows caching 303 responses;
+ * however, the HTTPbis working group says they can be cached
+ * if explicitly indicated in the response headers and permitted by the request method.
+ * (They also indicate that disallowing 303 caching is actually an unintended
+ * spec error in RFC2616).
+ * This behavior is off by default, to err on the side of a conservative
+ * adherence to the existing standard, but you may want to
+ * {@link Builder#setAllow303Caching(boolean) enable it}.
+ *
+ *
Weak ETags on PUT/DELETE If-Match requests. RFC2616 explicitly
+ * prohibits the use of weak validators in non-GET requests, however, the
+ * HTTPbis working group says while the limitation for weak validators on ranged
+ * requests makes sense, weak ETag validation is useful on full non-GET
+ * requests; e.g., PUT with If-Match. This behavior is off by default, to err on
+ * the side of a conservative adherence to the existing standard, but you may
+ * want to {@link Builder#setWeakETagOnPutDeleteAllowed(boolean) enable it}.
+ *
+ *
Heuristic caching. Per RFC2616, a cache may cache certain cache
+ * entries even if no explicit cache control headers are set by the origin.
+ * This behavior is off by default, but you may want to turn this on if you
+ * are working with an origin that doesn't set proper headers but where you
+ * still want to cache the responses. You will want to {@link
+ * CacheConfig#setHeuristicCachingEnabled(boolean) enable heuristic caching},
+ * then specify either a {@link CacheConfig#getHeuristicDefaultLifetime()
+ * default freshness lifetime} and/or a {@link
+ * CacheConfig#setHeuristicCoefficient(float) fraction of the time since
+ * the resource was last modified}. See Sections
+ *
+ * 13.2.2 and
+ * 13.2.4 of the HTTP/1.1 RFC for more details on heuristic caching.
+ *
+ *
Background validation. The cache module supports the
+ * {@code stale-while-revalidate} directive of
+ * RFC5861, which allows
+ * certain cache entry revalidations to happen in the background. You may
+ * want to tweak the settings for the {@link
+ * CacheConfig#getAsynchronousWorkersCore() minimum} and {@link
+ * CacheConfig#getAsynchronousWorkersMax() maximum} number of background
+ * worker threads, as well as the {@link
+ * CacheConfig#getAsynchronousWorkerIdleLifetimeSecs() maximum time they
+ * can be idle before being reclaimed}. You can also control the {@link
+ * CacheConfig#getRevalidationQueueSize() size of the queue} used for
+ * revalidations when there aren't enough workers to keep up with demand.
+ */
+public class CacheConfig implements Cloneable {
+
+ /** Default setting for the maximum object size that will be
+ * cached, in bytes.
+ */
+ public final static int DEFAULT_MAX_OBJECT_SIZE_BYTES = 8192;
+
+ /** Default setting for the maximum number of cache entries
+ * that will be retained.
+ */
+ public final static int DEFAULT_MAX_CACHE_ENTRIES = 1000;
+
+ /** Default setting for the number of retries on a failed
+ * cache update
+ */
+ public final static int DEFAULT_MAX_UPDATE_RETRIES = 1;
+
+ /** Default setting for 303 caching
+ */
+ public final static boolean DEFAULT_303_CACHING_ENABLED = false;
+
+ /** Default setting to allow weak tags on PUT/DELETE methods
+ */
+ public final static boolean DEFAULT_WEAK_ETAG_ON_PUTDELETE_ALLOWED = false;
+
+ /** Default setting for heuristic caching
+ */
+ public final static boolean DEFAULT_HEURISTIC_CACHING_ENABLED = false;
+
+ /** Default coefficient used to heuristically determine freshness
+ * lifetime from the Last-Modified time of a cache entry.
+ */
+ public final static float DEFAULT_HEURISTIC_COEFFICIENT = 0.1f;
+
+ /** Default lifetime in seconds to be assumed when we cannot calculate
+ * freshness heuristically.
+ */
+ public final static long DEFAULT_HEURISTIC_LIFETIME = 0;
+
+ /** Default number of worker threads to allow for background revalidations
+ * resulting from the stale-while-revalidate directive.
+ */
+ public static final int DEFAULT_ASYNCHRONOUS_WORKERS_MAX = 1;
+
+ /** Default minimum number of worker threads to allow for background
+ * revalidations resulting from the stale-while-revalidate directive.
+ */
+ public static final int DEFAULT_ASYNCHRONOUS_WORKERS_CORE = 1;
+
+ /** Default maximum idle lifetime for a background revalidation thread
+ * before it gets reclaimed.
+ */
+ public static final int DEFAULT_ASYNCHRONOUS_WORKER_IDLE_LIFETIME_SECS = 60;
+
+ /** Default maximum queue length for background revalidation requests.
+ */
+ public static final int DEFAULT_REVALIDATION_QUEUE_SIZE = 100;
+
+ public static final CacheConfig DEFAULT = new Builder().build();
+
+ // TODO: make final
+ private long maxObjectSize;
+ private int maxCacheEntries;
+ private int maxUpdateRetries;
+ private boolean allow303Caching;
+ private boolean weakETagOnPutDeleteAllowed;
+ private boolean heuristicCachingEnabled;
+ private float heuristicCoefficient;
+ private long heuristicDefaultLifetime;
+ private boolean isSharedCache;
+ private int asynchronousWorkersMax;
+ private int asynchronousWorkersCore;
+ private int asynchronousWorkerIdleLifetimeSecs;
+ private int revalidationQueueSize;
+ private boolean neverCacheHTTP10ResponsesWithQuery;
+
+ /**
+ * @deprecated (4.3) use {@link Builder}.
+ */
+ @Deprecated
+ public CacheConfig() {
+ super();
+ this.maxObjectSize = DEFAULT_MAX_OBJECT_SIZE_BYTES;
+ this.maxCacheEntries = DEFAULT_MAX_CACHE_ENTRIES;
+ this.maxUpdateRetries = DEFAULT_MAX_UPDATE_RETRIES;
+ this.allow303Caching = DEFAULT_303_CACHING_ENABLED;
+ this.weakETagOnPutDeleteAllowed = DEFAULT_WEAK_ETAG_ON_PUTDELETE_ALLOWED;
+ this.heuristicCachingEnabled = DEFAULT_HEURISTIC_CACHING_ENABLED;
+ this.heuristicCoefficient = DEFAULT_HEURISTIC_COEFFICIENT;
+ this.heuristicDefaultLifetime = DEFAULT_HEURISTIC_LIFETIME;
+ this.isSharedCache = true;
+ this.asynchronousWorkersMax = DEFAULT_ASYNCHRONOUS_WORKERS_MAX;
+ this.asynchronousWorkersCore = DEFAULT_ASYNCHRONOUS_WORKERS_CORE;
+ this.asynchronousWorkerIdleLifetimeSecs = DEFAULT_ASYNCHRONOUS_WORKER_IDLE_LIFETIME_SECS;
+ this.revalidationQueueSize = DEFAULT_REVALIDATION_QUEUE_SIZE;
+ }
+
+ CacheConfig(
+ final long maxObjectSize,
+ final int maxCacheEntries,
+ final int maxUpdateRetries,
+ final boolean allow303Caching,
+ final boolean weakETagOnPutDeleteAllowed,
+ final boolean heuristicCachingEnabled,
+ final float heuristicCoefficient,
+ final long heuristicDefaultLifetime,
+ final boolean isSharedCache,
+ final int asynchronousWorkersMax,
+ final int asynchronousWorkersCore,
+ final int asynchronousWorkerIdleLifetimeSecs,
+ final int revalidationQueueSize,
+ final boolean neverCacheHTTP10ResponsesWithQuery) {
+ super();
+ this.maxObjectSize = maxObjectSize;
+ this.maxCacheEntries = maxCacheEntries;
+ this.maxUpdateRetries = maxUpdateRetries;
+ this.allow303Caching = allow303Caching;
+ this.weakETagOnPutDeleteAllowed = weakETagOnPutDeleteAllowed;
+ this.heuristicCachingEnabled = heuristicCachingEnabled;
+ this.heuristicCoefficient = heuristicCoefficient;
+ this.heuristicDefaultLifetime = heuristicDefaultLifetime;
+ this.isSharedCache = isSharedCache;
+ this.asynchronousWorkersMax = asynchronousWorkersMax;
+ this.asynchronousWorkersCore = asynchronousWorkersCore;
+ this.asynchronousWorkerIdleLifetimeSecs = asynchronousWorkerIdleLifetimeSecs;
+ this.revalidationQueueSize = revalidationQueueSize;
+ }
+
+ /**
+ * Returns the current maximum response body size that will be cached.
+ * @return size in bytes
+ *
+ * @deprecated (4.2) use {@link #getMaxObjectSize()}
+ */
+ @Deprecated
+ public int getMaxObjectSizeBytes() {
+ return maxObjectSize > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) maxObjectSize;
+ }
+
+ /**
+ * Specifies the maximum response body size that will be eligible for caching.
+ * @param maxObjectSizeBytes size in bytes
+ *
+ * @deprecated (4.2) use {@link Builder}.
+ */
+ @Deprecated
+ public void setMaxObjectSizeBytes(final int maxObjectSizeBytes) {
+ if (maxObjectSizeBytes > Integer.MAX_VALUE) {
+ this.maxObjectSize = Integer.MAX_VALUE;
+ } else {
+ this.maxObjectSize = maxObjectSizeBytes;
+ }
+ }
+
+ /**
+ * Returns the current maximum response body size that will be cached.
+ * @return size in bytes
+ *
+ * @since 4.2
+ */
+ public long getMaxObjectSize() {
+ return maxObjectSize;
+ }
+
+ /**
+ * Specifies the maximum response body size that will be eligible for caching.
+ * @param maxObjectSize size in bytes
+ *
+ * @since 4.2
+ *
+ * @deprecated (4.3) use {@link Builder}.
+ */
+ @Deprecated
+ public void setMaxObjectSize(final long maxObjectSize) {
+ this.maxObjectSize = maxObjectSize;
+ }
+
+ /**
+ * Returns whether the cache will never cache HTTP 1.0 responses with a query string or not.
+ * @return {@code true} to not cache query string responses, {@code false} to cache if explicit cache headers are
+ * found
+ */
+ public boolean isNeverCacheHTTP10ResponsesWithQuery() {
+ return neverCacheHTTP10ResponsesWithQuery;
+ }
+
+ /**
+ * Returns the maximum number of cache entries the cache will retain.
+ */
+ public int getMaxCacheEntries() {
+ return maxCacheEntries;
+ }
+
+ /**
+ * Sets the maximum number of cache entries the cache will retain.
+ *
+ * @deprecated (4.3) use {@link Builder}.
+ */
+ @Deprecated
+ public void setMaxCacheEntries(final int maxCacheEntries) {
+ this.maxCacheEntries = maxCacheEntries;
+ }
+
+ /**
+ * Returns the number of times to retry a cache update on failure
+ */
+ public int getMaxUpdateRetries(){
+ return maxUpdateRetries;
+ }
+
+ /**
+ * Sets the number of times to retry a cache update on failure
+ *
+ * @deprecated (4.3) use {@link Builder}.
+ */
+ @Deprecated
+ public void setMaxUpdateRetries(final int maxUpdateRetries){
+ this.maxUpdateRetries = maxUpdateRetries;
+ }
+
+ /**
+ * Returns whether 303 caching is enabled.
+ * @return {@code true} if it is enabled.
+ */
+ public boolean is303CachingEnabled() {
+ return allow303Caching;
+ }
+
+ /**
+ * Returns whether weak etags is allowed with PUT/DELETE methods.
+ * @return {@code true} if it is allowed.
+ */
+ public boolean isWeakETagOnPutDeleteAllowed() {
+ return weakETagOnPutDeleteAllowed;
+ }
+
+ /**
+ * Returns whether heuristic caching is enabled.
+ * @return {@code true} if it is enabled.
+ */
+ public boolean isHeuristicCachingEnabled() {
+ return heuristicCachingEnabled;
+ }
+
+ /**
+ * Enables or disables heuristic caching.
+ * @param heuristicCachingEnabled should be {@code true} to
+ * permit heuristic caching, {@code false} to disable it.
+ *
+ * @deprecated (4.3) use {@link Builder}.
+ */
+ @Deprecated
+ public void setHeuristicCachingEnabled(final boolean heuristicCachingEnabled) {
+ this.heuristicCachingEnabled = heuristicCachingEnabled;
+ }
+
+ /**
+ * Returns lifetime coefficient used in heuristic freshness caching.
+ */
+ public float getHeuristicCoefficient() {
+ return heuristicCoefficient;
+ }
+
+ /**
+ * Sets coefficient to be used in heuristic freshness caching. This is
+ * interpreted as the fraction of the time between the {@code Last-Modified}
+ * and {@code Date} headers of a cached response during which the cached
+ * response will be considered heuristically fresh.
+ * @param heuristicCoefficient should be between {@code 0.0} and
+ * {@code 1.0}.
+ *
+ * @deprecated (4.3) use {@link Builder}.
+ */
+ @Deprecated
+ public void setHeuristicCoefficient(final float heuristicCoefficient) {
+ this.heuristicCoefficient = heuristicCoefficient;
+ }
+
+ /**
+ * Get the default lifetime to be used if heuristic freshness calculation is
+ * not possible.
+ */
+ public long getHeuristicDefaultLifetime() {
+ return heuristicDefaultLifetime;
+ }
+
+ /**
+ * Sets default lifetime in seconds to be used if heuristic freshness
+ * calculation is not possible. Explicit cache control directives on
+ * either the request or origin response will override this, as will
+ * the heuristic {@code Last-Modified} freshness calculation if it is
+ * available.
+ * @param heuristicDefaultLifetimeSecs is the number of seconds to
+ * consider a cache-eligible response fresh in the absence of other
+ * information. Set this to {@code 0} to disable this style of
+ * heuristic caching.
+ *
+ * @deprecated (4.3) use {@link Builder}.
+ */
+ @Deprecated
+ public void setHeuristicDefaultLifetime(final long heuristicDefaultLifetimeSecs) {
+ this.heuristicDefaultLifetime = heuristicDefaultLifetimeSecs;
+ }
+
+ /**
+ * Returns whether the cache will behave as a shared cache or not.
+ * @return {@code true} for a shared cache, {@code false} for a non-
+ * shared (private) cache
+ */
+ public boolean isSharedCache() {
+ return isSharedCache;
+ }
+
+ /**
+ * Sets whether the cache should behave as a shared cache or not.
+ * @param isSharedCache true to behave as a shared cache, false to
+ * behave as a non-shared (private) cache. To have the cache
+ * behave like a browser cache, you want to set this to {@code false}.
+ *
+ * @deprecated (4.3) use {@link Builder}.
+ */
+ @Deprecated
+ public void setSharedCache(final boolean isSharedCache) {
+ this.isSharedCache = isSharedCache;
+ }
+
+ /**
+ * Returns the maximum number of threads to allow for background
+ * revalidations due to the {@code stale-while-revalidate} directive. A
+ * value of 0 means background revalidations are disabled.
+ */
+ public int getAsynchronousWorkersMax() {
+ return asynchronousWorkersMax;
+ }
+
+ /**
+ * Sets the maximum number of threads to allow for background
+ * revalidations due to the {@code stale-while-revalidate} directive.
+ * @param max number of threads; a value of 0 disables background
+ * revalidations.
+ *
+ * @deprecated (4.3) use {@link Builder}.
+ */
+ @Deprecated
+ public void setAsynchronousWorkersMax(final int max) {
+ this.asynchronousWorkersMax = max;
+ }
+
+ /**
+ * Returns the minimum number of threads to keep alive for background
+ * revalidations due to the {@code stale-while-revalidate} directive.
+ */
+ public int getAsynchronousWorkersCore() {
+ return asynchronousWorkersCore;
+ }
+
+ /**
+ * Sets the minimum number of threads to keep alive for background
+ * revalidations due to the {@code stale-while-revalidate} directive.
+ * @param min should be greater than zero and less than or equal
+ * to getAsynchronousWorkersMax()
+ *
+ * @deprecated (4.3) use {@link Builder}.
+ */
+ @Deprecated
+ public void setAsynchronousWorkersCore(final int min) {
+ this.asynchronousWorkersCore = min;
+ }
+
+ /**
+ * Returns the current maximum idle lifetime in seconds for a
+ * background revalidation worker thread. If a worker thread is idle
+ * for this long, and there are more than the core number of worker
+ * threads alive, the worker will be reclaimed.
+ */
+ public int getAsynchronousWorkerIdleLifetimeSecs() {
+ return asynchronousWorkerIdleLifetimeSecs;
+ }
+
+ /**
+ * Sets the current maximum idle lifetime in seconds for a
+ * background revalidation worker thread. If a worker thread is idle
+ * for this long, and there are more than the core number of worker
+ * threads alive, the worker will be reclaimed.
+ * @param secs idle lifetime in seconds
+ *
+ * @deprecated (4.3) use {@link Builder}.
+ */
+ @Deprecated
+ public void setAsynchronousWorkerIdleLifetimeSecs(final int secs) {
+ this.asynchronousWorkerIdleLifetimeSecs = secs;
+ }
+
+ /**
+ * Returns the current maximum queue size for background revalidations.
+ */
+ public int getRevalidationQueueSize() {
+ return revalidationQueueSize;
+ }
+
+ /**
+ * Sets the current maximum queue size for background revalidations.
+ *
+ * @deprecated (4.3) use {@link Builder}.
+ */
+ @Deprecated
+ public void setRevalidationQueueSize(final int size) {
+ this.revalidationQueueSize = size;
+ }
+
+ @Override
+ protected CacheConfig clone() throws CloneNotSupportedException {
+ return (CacheConfig) super.clone();
+ }
+
+ public static Builder custom() {
+ return new Builder();
+ }
+
+ public static Builder copy(final CacheConfig config) {
+ Args.notNull(config, "Cache config");
+ return new Builder()
+ .setMaxObjectSize(config.getMaxObjectSize())
+ .setMaxCacheEntries(config.getMaxCacheEntries())
+ .setMaxUpdateRetries(config.getMaxUpdateRetries())
+ .setHeuristicCachingEnabled(config.isHeuristicCachingEnabled())
+ .setHeuristicCoefficient(config.getHeuristicCoefficient())
+ .setHeuristicDefaultLifetime(config.getHeuristicDefaultLifetime())
+ .setSharedCache(config.isSharedCache())
+ .setAsynchronousWorkersMax(config.getAsynchronousWorkersMax())
+ .setAsynchronousWorkersCore(config.getAsynchronousWorkersCore())
+ .setAsynchronousWorkerIdleLifetimeSecs(config.getAsynchronousWorkerIdleLifetimeSecs())
+ .setRevalidationQueueSize(config.getRevalidationQueueSize())
+ .setNeverCacheHTTP10ResponsesWithQueryString(config.isNeverCacheHTTP10ResponsesWithQuery());
+ }
+
+
+ public static class Builder {
+
+ private long maxObjectSize;
+ private int maxCacheEntries;
+ private int maxUpdateRetries;
+ private boolean allow303Caching;
+ private boolean weakETagOnPutDeleteAllowed;
+ private boolean heuristicCachingEnabled;
+ private float heuristicCoefficient;
+ private long heuristicDefaultLifetime;
+ private boolean isSharedCache;
+ private int asynchronousWorkersMax;
+ private int asynchronousWorkersCore;
+ private int asynchronousWorkerIdleLifetimeSecs;
+ private int revalidationQueueSize;
+ private boolean neverCacheHTTP10ResponsesWithQuery;
+
+ Builder() {
+ this.maxObjectSize = DEFAULT_MAX_OBJECT_SIZE_BYTES;
+ this.maxCacheEntries = DEFAULT_MAX_CACHE_ENTRIES;
+ this.maxUpdateRetries = DEFAULT_MAX_UPDATE_RETRIES;
+ this.allow303Caching = DEFAULT_303_CACHING_ENABLED;
+ this.weakETagOnPutDeleteAllowed = DEFAULT_WEAK_ETAG_ON_PUTDELETE_ALLOWED;
+ this.heuristicCachingEnabled = false;
+ this.heuristicCoefficient = DEFAULT_HEURISTIC_COEFFICIENT;
+ this.heuristicDefaultLifetime = DEFAULT_HEURISTIC_LIFETIME;
+ this.isSharedCache = true;
+ this.asynchronousWorkersMax = DEFAULT_ASYNCHRONOUS_WORKERS_MAX;
+ this.asynchronousWorkersCore = DEFAULT_ASYNCHRONOUS_WORKERS_CORE;
+ this.asynchronousWorkerIdleLifetimeSecs = DEFAULT_ASYNCHRONOUS_WORKER_IDLE_LIFETIME_SECS;
+ this.revalidationQueueSize = DEFAULT_REVALIDATION_QUEUE_SIZE;
+ }
+
+ /**
+ * Specifies the maximum response body size that will be eligible for caching.
+ * @param maxObjectSize size in bytes
+ */
+ public Builder setMaxObjectSize(final long maxObjectSize) {
+ this.maxObjectSize = maxObjectSize;
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of cache entries the cache will retain.
+ */
+ public Builder setMaxCacheEntries(final int maxCacheEntries) {
+ this.maxCacheEntries = maxCacheEntries;
+ return this;
+ }
+
+ /**
+ * Sets the number of times to retry a cache update on failure
+ */
+ public Builder setMaxUpdateRetries(final int maxUpdateRetries) {
+ this.maxUpdateRetries = maxUpdateRetries;
+ return this;
+ }
+
+ /**
+ * Enables or disables 303 caching.
+ * @param allow303Caching should be {@code true} to
+ * permit 303 caching, {@code false} to disable it.
+ */
+ public Builder setAllow303Caching(final boolean allow303Caching) {
+ this.allow303Caching = allow303Caching;
+ return this;
+ }
+
+ /**
+ * Allows or disallows weak etags to be used with PUT/DELETE If-Match requests.
+ * @param weakETagOnPutDeleteAllowed should be {@code true} to
+ * permit weak etags, {@code false} to reject them.
+ */
+ public Builder setWeakETagOnPutDeleteAllowed(final boolean weakETagOnPutDeleteAllowed) {
+ this.weakETagOnPutDeleteAllowed = weakETagOnPutDeleteAllowed;
+ return this;
+ }
+
+ /**
+ * Enables or disables heuristic caching.
+ * @param heuristicCachingEnabled should be {@code true} to
+ * permit heuristic caching, {@code false} to enable it.
+ */
+ public Builder setHeuristicCachingEnabled(final boolean heuristicCachingEnabled) {
+ this.heuristicCachingEnabled = heuristicCachingEnabled;
+ return this;
+ }
+
+ /**
+ * Sets coefficient to be used in heuristic freshness caching. This is
+ * interpreted as the fraction of the time between the {@code Last-Modified}
+ * and {@code Date} headers of a cached response during which the cached
+ * response will be considered heuristically fresh.
+ * @param heuristicCoefficient should be between {@code 0.0} and
+ * {@code 1.0}.
+ */
+ public Builder setHeuristicCoefficient(final float heuristicCoefficient) {
+ this.heuristicCoefficient = heuristicCoefficient;
+ return this;
+ }
+
+ /**
+ * Sets default lifetime in seconds to be used if heuristic freshness
+ * calculation is not possible. Explicit cache control directives on
+ * either the request or origin response will override this, as will
+ * the heuristic {@code Last-Modified} freshness calculation if it is
+ * available.
+ * @param heuristicDefaultLifetime is the number of seconds to
+ * consider a cache-eligible response fresh in the absence of other
+ * information. Set this to {@code 0} to disable this style of
+ * heuristic caching.
+ */
+ public Builder setHeuristicDefaultLifetime(final long heuristicDefaultLifetime) {
+ this.heuristicDefaultLifetime = heuristicDefaultLifetime;
+ return this;
+ }
+
+ /**
+ * Sets whether the cache should behave as a shared cache or not.
+ * @param isSharedCache true to behave as a shared cache, false to
+ * behave as a non-shared (private) cache. To have the cache
+ * behave like a browser cache, you want to set this to {@code false}.
+ */
+ public Builder setSharedCache(final boolean isSharedCache) {
+ this.isSharedCache = isSharedCache;
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of threads to allow for background
+ * revalidations due to the {@code stale-while-revalidate} directive.
+ * @param asynchronousWorkersMax number of threads; a value of 0 disables background
+ * revalidations.
+ */
+ public Builder setAsynchronousWorkersMax(final int asynchronousWorkersMax) {
+ this.asynchronousWorkersMax = asynchronousWorkersMax;
+ return this;
+ }
+
+ /**
+ * Sets the minimum number of threads to keep alive for background
+ * revalidations due to the {@code stale-while-revalidate} directive.
+ * @param asynchronousWorkersCore should be greater than zero and less than or equal
+ * to getAsynchronousWorkersMax()
+ */
+ public Builder setAsynchronousWorkersCore(final int asynchronousWorkersCore) {
+ this.asynchronousWorkersCore = asynchronousWorkersCore;
+ return this;
+ }
+
+ /**
+ * Sets the current maximum idle lifetime in seconds for a
+ * background revalidation worker thread. If a worker thread is idle
+ * for this long, and there are more than the core number of worker
+ * threads alive, the worker will be reclaimed.
+ * @param asynchronousWorkerIdleLifetimeSecs idle lifetime in seconds
+ */
+ public Builder setAsynchronousWorkerIdleLifetimeSecs(final int asynchronousWorkerIdleLifetimeSecs) {
+ this.asynchronousWorkerIdleLifetimeSecs = asynchronousWorkerIdleLifetimeSecs;
+ return this;
+ }
+
+ /**
+ * Sets the current maximum queue size for background revalidations.
+ */
+ public Builder setRevalidationQueueSize(final int revalidationQueueSize) {
+ this.revalidationQueueSize = revalidationQueueSize;
+ return this;
+ }
+
+ /**
+ * Sets whether the cache should never cache HTTP 1.0 responses with a query string or not.
+ * @param neverCacheHTTP10ResponsesWithQuery true to never cache responses with a query
+ * string, false to cache if explicit cache headers are found. Set this to {@code true}
+ * to better emulate IE, which also never caches responses, regardless of what caching
+ * headers may be present.
+ */
+ public Builder setNeverCacheHTTP10ResponsesWithQueryString(
+ final boolean neverCacheHTTP10ResponsesWithQuery) {
+ this.neverCacheHTTP10ResponsesWithQuery = neverCacheHTTP10ResponsesWithQuery;
+ return this;
+ }
+
+ public CacheConfig build() {
+ return new CacheConfig(
+ maxObjectSize,
+ maxCacheEntries,
+ maxUpdateRetries,
+ allow303Caching,
+ weakETagOnPutDeleteAllowed,
+ heuristicCachingEnabled,
+ heuristicCoefficient,
+ heuristicDefaultLifetime,
+ isSharedCache,
+ asynchronousWorkersMax,
+ asynchronousWorkersCore,
+ asynchronousWorkerIdleLifetimeSecs,
+ revalidationQueueSize,
+ neverCacheHTTP10ResponsesWithQuery);
+ }
+
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("[maxObjectSize=").append(this.maxObjectSize)
+ .append(", maxCacheEntries=").append(this.maxCacheEntries)
+ .append(", maxUpdateRetries=").append(this.maxUpdateRetries)
+ .append(", 303CachingEnabled=").append(this.allow303Caching)
+ .append(", weakETagOnPutDeleteAllowed=").append(this.weakETagOnPutDeleteAllowed)
+ .append(", heuristicCachingEnabled=").append(this.heuristicCachingEnabled)
+ .append(", heuristicCoefficient=").append(this.heuristicCoefficient)
+ .append(", heuristicDefaultLifetime=").append(this.heuristicDefaultLifetime)
+ .append(", isSharedCache=").append(this.isSharedCache)
+ .append(", asynchronousWorkersMax=").append(this.asynchronousWorkersMax)
+ .append(", asynchronousWorkersCore=").append(this.asynchronousWorkersCore)
+ .append(", asynchronousWorkerIdleLifetimeSecs=").append(this.asynchronousWorkerIdleLifetimeSecs)
+ .append(", revalidationQueueSize=").append(this.revalidationQueueSize)
+ .append(", neverCacheHTTP10ResponsesWithQuery=").append(this.neverCacheHTTP10ResponsesWithQuery)
+ .append("]");
+ return builder.toString();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheEntity.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheEntity.java
new file mode 100644
index 000000000..1906166d1
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheEntity.java
@@ -0,0 +1,99 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Serializable;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+import ch.boye.httpclientandroidlib.util.Args;
+
+@Immutable
+class CacheEntity implements HttpEntity, Serializable {
+
+ private static final long serialVersionUID = -3467082284120936233L;
+
+ private final HttpCacheEntry cacheEntry;
+
+ public CacheEntity(final HttpCacheEntry cacheEntry) {
+ super();
+ this.cacheEntry = cacheEntry;
+ }
+
+ public Header getContentType() {
+ return this.cacheEntry.getFirstHeader(HTTP.CONTENT_TYPE);
+ }
+
+ public Header getContentEncoding() {
+ return this.cacheEntry.getFirstHeader(HTTP.CONTENT_ENCODING);
+ }
+
+ public boolean isChunked() {
+ return false;
+ }
+
+ public boolean isRepeatable() {
+ return true;
+ }
+
+ public long getContentLength() {
+ return this.cacheEntry.getResource().length();
+ }
+
+ public InputStream getContent() throws IOException {
+ return this.cacheEntry.getResource().getInputStream();
+ }
+
+ public void writeTo(final OutputStream outstream) throws IOException {
+ Args.notNull(outstream, "Output stream");
+ final InputStream instream = this.cacheEntry.getResource().getInputStream();
+ try {
+ IOUtils.copy(instream, outstream);
+ } finally {
+ instream.close();
+ }
+ }
+
+ public boolean isStreaming() {
+ return false;
+ }
+
+ public void consumeContent() throws IOException {
+ }
+
+ @Override
+ public Object clone() throws CloneNotSupportedException {
+ return super.clone();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheEntryUpdater.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheEntryUpdater.java
new file mode 100644
index 000000000..381a7508d
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheEntryUpdater.java
@@ -0,0 +1,173 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+import java.util.ListIterator;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.cache.HeaderConstants;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.client.cache.Resource;
+import ch.boye.httpclientandroidlib.client.cache.ResourceFactory;
+import ch.boye.httpclientandroidlib.client.utils.DateUtils;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Update a {@link HttpCacheEntry} with new or updated information based on the latest
+ * 304 status response from the Server. Use the {@link HttpResponse} to perform
+ * the update.
+ *
+ * @since 4.1
+ */
+@Immutable
+class CacheEntryUpdater {
+
+ private final ResourceFactory resourceFactory;
+
+ CacheEntryUpdater() {
+ this(new HeapResourceFactory());
+ }
+
+ CacheEntryUpdater(final ResourceFactory resourceFactory) {
+ super();
+ this.resourceFactory = resourceFactory;
+ }
+
+ /**
+ * Update the entry with the new information from the response. Should only be used for
+ * 304 responses.
+ *
+ * @param requestId
+ * @param entry The cache Entry to be updated
+ * @param requestDate When the request was performed
+ * @param responseDate When the response was gotten
+ * @param response The HttpResponse from the backend server call
+ * @return HttpCacheEntry an updated version of the cache entry
+ * @throws java.io.IOException if something bad happens while trying to read the body from the original entry
+ */
+ public HttpCacheEntry updateCacheEntry(
+ final String requestId,
+ final HttpCacheEntry entry,
+ final Date requestDate,
+ final Date responseDate,
+ final HttpResponse response) throws IOException {
+ Args.check(response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED,
+ "Response must have 304 status code");
+ final Header[] mergedHeaders = mergeHeaders(entry, response);
+ Resource resource = null;
+ if (entry.getResource() != null) {
+ resource = resourceFactory.copy(requestId, entry.getResource());
+ }
+ return new HttpCacheEntry(
+ requestDate,
+ responseDate,
+ entry.getStatusLine(),
+ mergedHeaders,
+ resource);
+ }
+
+ protected Header[] mergeHeaders(final HttpCacheEntry entry, final HttpResponse response) {
+
+ if (entryAndResponseHaveDateHeader(entry, response)
+ && entryDateHeaderNewerThenResponse(entry, response)) {
+ // Don't merge headers, keep the entry's headers as they are newer.
+ return entry.getAllHeaders();
+ }
+
+ final List cacheEntryHeaderList = new ArrayList(Arrays.asList(entry
+ .getAllHeaders()));
+ removeCacheHeadersThatMatchResponse(cacheEntryHeaderList, response);
+ removeCacheEntry1xxWarnings(cacheEntryHeaderList, entry);
+ cacheEntryHeaderList.addAll(Arrays.asList(response.getAllHeaders()));
+
+ return cacheEntryHeaderList.toArray(new Header[cacheEntryHeaderList.size()]);
+ }
+
+ private void removeCacheHeadersThatMatchResponse(final List cacheEntryHeaderList,
+ final HttpResponse response) {
+ for (final Header responseHeader : response.getAllHeaders()) {
+ final ListIterator cacheEntryHeaderListIter = cacheEntryHeaderList.listIterator();
+
+ while (cacheEntryHeaderListIter.hasNext()) {
+ final String cacheEntryHeaderName = cacheEntryHeaderListIter.next().getName();
+
+ if (cacheEntryHeaderName.equals(responseHeader.getName())) {
+ cacheEntryHeaderListIter.remove();
+ }
+ }
+ }
+ }
+
+ private void removeCacheEntry1xxWarnings(final List cacheEntryHeaderList, final HttpCacheEntry entry) {
+ final ListIterator cacheEntryHeaderListIter = cacheEntryHeaderList.listIterator();
+
+ while (cacheEntryHeaderListIter.hasNext()) {
+ final String cacheEntryHeaderName = cacheEntryHeaderListIter.next().getName();
+
+ if (HeaderConstants.WARNING.equals(cacheEntryHeaderName)) {
+ for (final Header cacheEntryWarning : entry.getHeaders(HeaderConstants.WARNING)) {
+ if (cacheEntryWarning.getValue().startsWith("1")) {
+ cacheEntryHeaderListIter.remove();
+ }
+ }
+ }
+ }
+ }
+
+ private boolean entryDateHeaderNewerThenResponse(final HttpCacheEntry entry, final HttpResponse response) {
+ final Date entryDate = DateUtils.parseDate(entry.getFirstHeader(HTTP.DATE_HEADER)
+ .getValue());
+ final Date responseDate = DateUtils.parseDate(response.getFirstHeader(HTTP.DATE_HEADER)
+ .getValue());
+ if (entryDate == null || responseDate == null) {
+ return false;
+ }
+ if (!entryDate.after(responseDate)) {
+ return false;
+ }
+ return true;
+ }
+
+ private boolean entryAndResponseHaveDateHeader(final HttpCacheEntry entry, final HttpResponse response) {
+ if (entry.getFirstHeader(HTTP.DATE_HEADER) != null
+ && response.getFirstHeader(HTTP.DATE_HEADER) != null) {
+ return true;
+ }
+
+ return false;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheInvalidator.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheInvalidator.java
new file mode 100644
index 000000000..19e62869e
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheInvalidator.java
@@ -0,0 +1,288 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Date;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.cache.HeaderConstants;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheInvalidator;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheStorage;
+import ch.boye.httpclientandroidlib.client.utils.DateUtils;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+
+/**
+ * Given a particular HttpRequest, flush any cache entries that this request
+ * would invalidate.
+ *
+ * @since 4.1
+ */
+@Immutable
+class CacheInvalidator implements HttpCacheInvalidator {
+
+ private final HttpCacheStorage storage;
+ private final CacheKeyGenerator cacheKeyGenerator;
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ /**
+ * Create a new {@link CacheInvalidator} for a given {@link HttpCache} and
+ * {@link CacheKeyGenerator}.
+ *
+ * @param uriExtractor Provides identifiers for the keys to store cache entries
+ * @param storage the cache to store items away in
+ */
+ public CacheInvalidator(
+ final CacheKeyGenerator uriExtractor,
+ final HttpCacheStorage storage) {
+ this.cacheKeyGenerator = uriExtractor;
+ this.storage = storage;
+ }
+
+ /**
+ * Remove cache entries from the cache that are no longer fresh or
+ * have been invalidated in some way.
+ *
+ * @param host The backend host we are talking to
+ * @param req The HttpRequest to that host
+ */
+ public void flushInvalidatedCacheEntries(final HttpHost host, final HttpRequest req) {
+ if (requestShouldNotBeCached(req)) {
+ log.debug("Request should not be cached");
+
+ final String theUri = cacheKeyGenerator.getURI(host, req);
+
+ final HttpCacheEntry parent = getEntry(theUri);
+
+ log.debug("parent entry: " + parent);
+
+ if (parent != null) {
+ for (final String variantURI : parent.getVariantMap().values()) {
+ flushEntry(variantURI);
+ }
+ flushEntry(theUri);
+ }
+ final URL reqURL = getAbsoluteURL(theUri);
+ if (reqURL == null) {
+ log.error("Couldn't transform request into valid URL");
+ return;
+ }
+ final Header clHdr = req.getFirstHeader("Content-Location");
+ if (clHdr != null) {
+ final String contentLocation = clHdr.getValue();
+ if (!flushAbsoluteUriFromSameHost(reqURL, contentLocation)) {
+ flushRelativeUriFromSameHost(reqURL, contentLocation);
+ }
+ }
+ final Header lHdr = req.getFirstHeader("Location");
+ if (lHdr != null) {
+ flushAbsoluteUriFromSameHost(reqURL, lHdr.getValue());
+ }
+ }
+ }
+
+ private void flushEntry(final String uri) {
+ try {
+ storage.removeEntry(uri);
+ } catch (final IOException ioe) {
+ log.warn("unable to flush cache entry", ioe);
+ }
+ }
+
+ private HttpCacheEntry getEntry(final String theUri) {
+ try {
+ return storage.getEntry(theUri);
+ } catch (final IOException ioe) {
+ log.warn("could not retrieve entry from storage", ioe);
+ }
+ return null;
+ }
+
+ protected void flushUriIfSameHost(final URL requestURL, final URL targetURL) {
+ final URL canonicalTarget = getAbsoluteURL(cacheKeyGenerator.canonicalizeUri(targetURL.toString()));
+ if (canonicalTarget == null) {
+ return;
+ }
+ if (canonicalTarget.getAuthority().equalsIgnoreCase(requestURL.getAuthority())) {
+ flushEntry(canonicalTarget.toString());
+ }
+ }
+
+ protected void flushRelativeUriFromSameHost(final URL reqURL, final String relUri) {
+ final URL relURL = getRelativeURL(reqURL, relUri);
+ if (relURL == null) {
+ return;
+ }
+ flushUriIfSameHost(reqURL, relURL);
+ }
+
+
+ protected boolean flushAbsoluteUriFromSameHost(final URL reqURL, final String uri) {
+ final URL absURL = getAbsoluteURL(uri);
+ if (absURL == null) {
+ return false;
+ }
+ flushUriIfSameHost(reqURL,absURL);
+ return true;
+ }
+
+ private URL getAbsoluteURL(final String uri) {
+ URL absURL = null;
+ try {
+ absURL = new URL(uri);
+ } catch (final MalformedURLException mue) {
+ // nop
+ }
+ return absURL;
+ }
+
+ private URL getRelativeURL(final URL reqURL, final String relUri) {
+ URL relURL = null;
+ try {
+ relURL = new URL(reqURL,relUri);
+ } catch (final MalformedURLException e) {
+ // nop
+ }
+ return relURL;
+ }
+
+ protected boolean requestShouldNotBeCached(final HttpRequest req) {
+ final String method = req.getRequestLine().getMethod();
+ return notGetOrHeadRequest(method);
+ }
+
+ private boolean notGetOrHeadRequest(final String method) {
+ return !(HeaderConstants.GET_METHOD.equals(method) || HeaderConstants.HEAD_METHOD
+ .equals(method));
+ }
+
+ /** Flushes entries that were invalidated by the given response
+ * received for the given host/request pair.
+ */
+ public void flushInvalidatedCacheEntries(final HttpHost host,
+ final HttpRequest request, final HttpResponse response) {
+ final int status = response.getStatusLine().getStatusCode();
+ if (status < 200 || status > 299) {
+ return;
+ }
+ final URL reqURL = getAbsoluteURL(cacheKeyGenerator.getURI(host, request));
+ if (reqURL == null) {
+ return;
+ }
+ final URL contentLocation = getContentLocationURL(reqURL, response);
+ if (contentLocation != null) {
+ flushLocationCacheEntry(reqURL, response, contentLocation);
+ }
+ final URL location = getLocationURL(reqURL, response);
+ if (location != null) {
+ flushLocationCacheEntry(reqURL, response, location);
+ }
+ }
+
+ private void flushLocationCacheEntry(final URL reqURL,
+ final HttpResponse response, final URL location) {
+ final String cacheKey = cacheKeyGenerator.canonicalizeUri(location.toString());
+ final HttpCacheEntry entry = getEntry(cacheKey);
+ if (entry == null) {
+ return;
+ }
+
+ // do not invalidate if response is strictly older than entry
+ // or if the etags match
+
+ if (responseDateOlderThanEntryDate(response, entry)) {
+ return;
+ }
+ if (!responseAndEntryEtagsDiffer(response, entry)) {
+ return;
+ }
+
+ flushUriIfSameHost(reqURL, location);
+ }
+
+ private URL getContentLocationURL(final URL reqURL, final HttpResponse response) {
+ final Header clHeader = response.getFirstHeader("Content-Location");
+ if (clHeader == null) {
+ return null;
+ }
+ final String contentLocation = clHeader.getValue();
+ final URL canonURL = getAbsoluteURL(contentLocation);
+ if (canonURL != null) {
+ return canonURL;
+ }
+ return getRelativeURL(reqURL, contentLocation);
+ }
+
+ private URL getLocationURL(final URL reqURL, final HttpResponse response) {
+ final Header clHeader = response.getFirstHeader("Location");
+ if (clHeader == null) {
+ return null;
+ }
+ final String location = clHeader.getValue();
+ final URL canonURL = getAbsoluteURL(location);
+ if (canonURL != null) {
+ return canonURL;
+ }
+ return getRelativeURL(reqURL, location);
+ }
+
+ private boolean responseAndEntryEtagsDiffer(final HttpResponse response,
+ final HttpCacheEntry entry) {
+ final Header entryEtag = entry.getFirstHeader(HeaderConstants.ETAG);
+ final Header responseEtag = response.getFirstHeader(HeaderConstants.ETAG);
+ if (entryEtag == null || responseEtag == null) {
+ return false;
+ }
+ return (!entryEtag.getValue().equals(responseEtag.getValue()));
+ }
+
+ private boolean responseDateOlderThanEntryDate(final HttpResponse response,
+ final HttpCacheEntry entry) {
+ final Header entryDateHeader = entry.getFirstHeader(HTTP.DATE_HEADER);
+ final Header responseDateHeader = response.getFirstHeader(HTTP.DATE_HEADER);
+ if (entryDateHeader == null || responseDateHeader == null) {
+ /* be conservative; should probably flush */
+ return false;
+ }
+ final Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
+ final Date responseDate = DateUtils.parseDate(responseDateHeader.getValue());
+ if (entryDate == null || responseDate == null) {
+ return false;
+ }
+ return responseDate.before(entryDate);
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheKeyGenerator.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheKeyGenerator.java
new file mode 100644
index 000000000..b0628041f
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheKeyGenerator.java
@@ -0,0 +1,178 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import ch.boye.httpclientandroidlib.Consts;
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HeaderElement;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.cache.HeaderConstants;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.client.utils.URIUtils;
+
+/**
+ * @since 4.1
+ */
+@Immutable
+class CacheKeyGenerator {
+
+ private static final URI BASE_URI = URI.create("http://example.com/");
+
+ /**
+ * For a given {@link HttpHost} and {@link HttpRequest} get a URI from the
+ * pair that I can use as an identifier KEY into my HttpCache
+ *
+ * @param host The host for this request
+ * @param req the {@link HttpRequest}
+ * @return String the extracted URI
+ */
+ public String getURI(final HttpHost host, final HttpRequest req) {
+ if (isRelativeRequest(req)) {
+ return canonicalizeUri(String.format("%s%s", host.toString(), req.getRequestLine().getUri()));
+ }
+ return canonicalizeUri(req.getRequestLine().getUri());
+ }
+
+ public String canonicalizeUri(final String uri) {
+ try {
+ final URI normalized = URIUtils.resolve(BASE_URI, uri);
+ final URL u = new URL(normalized.toASCIIString());
+ final String protocol = u.getProtocol();
+ final String hostname = u.getHost();
+ final int port = canonicalizePort(u.getPort(), protocol);
+ final String path = u.getPath();
+ final String query = u.getQuery();
+ final String file = (query != null) ? (path + "?" + query) : path;
+ final URL out = new URL(protocol, hostname, port, file);
+ return out.toString();
+ } catch (final IllegalArgumentException e) {
+ return uri;
+ } catch (final MalformedURLException e) {
+ return uri;
+ }
+ }
+
+ private int canonicalizePort(final int port, final String protocol) {
+ if (port == -1 && "http".equalsIgnoreCase(protocol)) {
+ return 80;
+ } else if (port == -1 && "https".equalsIgnoreCase(protocol)) {
+ return 443;
+ }
+ return port;
+ }
+
+ private boolean isRelativeRequest(final HttpRequest req) {
+ final String requestUri = req.getRequestLine().getUri();
+ return ("*".equals(requestUri) || requestUri.startsWith("/"));
+ }
+
+ protected String getFullHeaderValue(final Header[] headers) {
+ if (headers == null) {
+ return "";
+ }
+
+ final StringBuilder buf = new StringBuilder("");
+ boolean first = true;
+ for (final Header hdr : headers) {
+ if (!first) {
+ buf.append(", ");
+ }
+ buf.append(hdr.getValue().trim());
+ first = false;
+
+ }
+ return buf.toString();
+ }
+
+ /**
+ * For a given {@link HttpHost} and {@link HttpRequest} if the request has a
+ * VARY header - I need to get an additional URI from the pair of host and
+ * request so that I can also store the variant into my HttpCache.
+ *
+ * @param host The host for this request
+ * @param req the {@link HttpRequest}
+ * @param entry the parent entry used to track the variants
+ * @return String the extracted variant URI
+ */
+ public String getVariantURI(final HttpHost host, final HttpRequest req, final HttpCacheEntry entry) {
+ if (!entry.hasVariants()) {
+ return getURI(host, req);
+ }
+ return getVariantKey(req, entry) + getURI(host, req);
+ }
+
+ /**
+ * Compute a "variant key" from the headers of a given request that are
+ * covered by the Vary header of a given cache entry. Any request whose
+ * varying headers match those of this request should have the same
+ * variant key.
+ * @param req originating request
+ * @param entry cache entry in question that has variants
+ * @return a String variant key
+ */
+ public String getVariantKey(final HttpRequest req, final HttpCacheEntry entry) {
+ final List variantHeaderNames = new ArrayList();
+ for (final Header varyHdr : entry.getHeaders(HeaderConstants.VARY)) {
+ for (final HeaderElement elt : varyHdr.getElements()) {
+ variantHeaderNames.add(elt.getName());
+ }
+ }
+ Collections.sort(variantHeaderNames);
+
+ StringBuilder buf;
+ try {
+ buf = new StringBuilder("{");
+ boolean first = true;
+ for (final String headerName : variantHeaderNames) {
+ if (!first) {
+ buf.append("&");
+ }
+ buf.append(URLEncoder.encode(headerName, Consts.UTF_8.name()));
+ buf.append("=");
+ buf.append(URLEncoder.encode(getFullHeaderValue(req.getHeaders(headerName)),
+ Consts.UTF_8.name()));
+ first = false;
+ }
+ buf.append("}");
+ } catch (final UnsupportedEncodingException uee) {
+ throw new RuntimeException("couldn't encode to UTF-8", uee);
+ }
+ return buf.toString();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheMap.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheMap.java
new file mode 100644
index 000000000..0ed80920c
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheMap.java
@@ -0,0 +1,50 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+
+final class CacheMap extends LinkedHashMap {
+
+ private static final long serialVersionUID = -7750025207539768511L;
+
+ private final int maxEntries;
+
+ CacheMap(final int maxEntries) {
+ super(20, 0.75f, true);
+ this.maxEntries = maxEntries;
+ }
+
+ @Override
+ protected boolean removeEldestEntry(final Map.Entry eldest) {
+ return size() > this.maxEntries;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheValidityPolicy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheValidityPolicy.java
new file mode 100644
index 000000000..333dfbbfb
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheValidityPolicy.java
@@ -0,0 +1,320 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.util.Date;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HeaderElement;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.cache.HeaderConstants;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.client.utils.DateUtils;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+
+/**
+ * @since 4.1
+ */
+@Immutable
+class CacheValidityPolicy {
+
+ public static final long MAX_AGE = 2147483648L;
+
+ CacheValidityPolicy() {
+ super();
+ }
+
+ public long getCurrentAgeSecs(final HttpCacheEntry entry, final Date now) {
+ return getCorrectedInitialAgeSecs(entry) + getResidentTimeSecs(entry, now);
+ }
+
+ public long getFreshnessLifetimeSecs(final HttpCacheEntry entry) {
+ final long maxage = getMaxAge(entry);
+ if (maxage > -1) {
+ return maxage;
+ }
+
+ final Date dateValue = entry.getDate();
+ if (dateValue == null) {
+ return 0L;
+ }
+
+ final Date expiry = getExpirationDate(entry);
+ if (expiry == null) {
+ return 0;
+ }
+ final long diff = expiry.getTime() - dateValue.getTime();
+ return (diff / 1000);
+ }
+
+ public boolean isResponseFresh(final HttpCacheEntry entry, final Date now) {
+ return (getCurrentAgeSecs(entry, now) < getFreshnessLifetimeSecs(entry));
+ }
+
+ /**
+ * Decides if this response is fresh enough based Last-Modified and Date, if available.
+ * This entry is meant to be used when isResponseFresh returns false. The algorithm is as follows:
+ *
+ * if last-modified and date are defined, freshness lifetime is coefficient*(date-lastModified),
+ * else freshness lifetime is defaultLifetime
+ *
+ * @param entry the cache entry
+ * @param now what time is it currently (When is right NOW)
+ * @param coefficient Part of the heuristic for cache entry freshness
+ * @param defaultLifetime How long can I assume a cache entry is default TTL
+ * @return {@code true} if the response is fresh
+ */
+ public boolean isResponseHeuristicallyFresh(final HttpCacheEntry entry,
+ final Date now, final float coefficient, final long defaultLifetime) {
+ return (getCurrentAgeSecs(entry, now) < getHeuristicFreshnessLifetimeSecs(entry, coefficient, defaultLifetime));
+ }
+
+ public long getHeuristicFreshnessLifetimeSecs(final HttpCacheEntry entry,
+ final float coefficient, final long defaultLifetime) {
+ final Date dateValue = entry.getDate();
+ final Date lastModifiedValue = getLastModifiedValue(entry);
+
+ if (dateValue != null && lastModifiedValue != null) {
+ final long diff = dateValue.getTime() - lastModifiedValue.getTime();
+ if (diff < 0) {
+ return 0;
+ }
+ return (long)(coefficient * (diff / 1000));
+ }
+
+ return defaultLifetime;
+ }
+
+ public boolean isRevalidatable(final HttpCacheEntry entry) {
+ return entry.getFirstHeader(HeaderConstants.ETAG) != null
+ || entry.getFirstHeader(HeaderConstants.LAST_MODIFIED) != null;
+ }
+
+ public boolean mustRevalidate(final HttpCacheEntry entry) {
+ return hasCacheControlDirective(entry, HeaderConstants.CACHE_CONTROL_MUST_REVALIDATE);
+ }
+
+ public boolean proxyRevalidate(final HttpCacheEntry entry) {
+ return hasCacheControlDirective(entry, HeaderConstants.CACHE_CONTROL_PROXY_REVALIDATE);
+ }
+
+ public boolean mayReturnStaleWhileRevalidating(final HttpCacheEntry entry, final Date now) {
+ for (final Header h : entry.getHeaders(HeaderConstants.CACHE_CONTROL)) {
+ for(final HeaderElement elt : h.getElements()) {
+ if (HeaderConstants.STALE_WHILE_REVALIDATE.equalsIgnoreCase(elt.getName())) {
+ try {
+ final int allowedStalenessLifetime = Integer.parseInt(elt.getValue());
+ if (getStalenessSecs(entry, now) <= allowedStalenessLifetime) {
+ return true;
+ }
+ } catch (final NumberFormatException nfe) {
+ // skip malformed directive
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+
+ public boolean mayReturnStaleIfError(final HttpRequest request,
+ final HttpCacheEntry entry, final Date now) {
+ final long stalenessSecs = getStalenessSecs(entry, now);
+ return mayReturnStaleIfError(request.getHeaders(HeaderConstants.CACHE_CONTROL),
+ stalenessSecs)
+ || mayReturnStaleIfError(entry.getHeaders(HeaderConstants.CACHE_CONTROL),
+ stalenessSecs);
+ }
+
+ private boolean mayReturnStaleIfError(final Header[] headers, final long stalenessSecs) {
+ boolean result = false;
+ for(final Header h : headers) {
+ for(final HeaderElement elt : h.getElements()) {
+ if (HeaderConstants.STALE_IF_ERROR.equals(elt.getName())) {
+ try {
+ final int staleIfErrorSecs = Integer.parseInt(elt.getValue());
+ if (stalenessSecs <= staleIfErrorSecs) {
+ result = true;
+ break;
+ }
+ } catch (final NumberFormatException nfe) {
+ // skip malformed directive
+ }
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * @deprecated (4.3) use {@link HttpCacheEntry#getDate()}.
+ * @param entry
+ * @return the Date of the entry
+ */
+ @Deprecated
+ protected Date getDateValue(final HttpCacheEntry entry) {
+ return entry.getDate();
+ }
+
+ protected Date getLastModifiedValue(final HttpCacheEntry entry) {
+ final Header dateHdr = entry.getFirstHeader(HeaderConstants.LAST_MODIFIED);
+ if (dateHdr == null) {
+ return null;
+ }
+ return DateUtils.parseDate(dateHdr.getValue());
+ }
+
+ protected long getContentLengthValue(final HttpCacheEntry entry) {
+ final Header cl = entry.getFirstHeader(HTTP.CONTENT_LEN);
+ if (cl == null) {
+ return -1;
+ }
+
+ try {
+ return Long.parseLong(cl.getValue());
+ } catch (final NumberFormatException ex) {
+ return -1;
+ }
+ }
+
+ protected boolean hasContentLengthHeader(final HttpCacheEntry entry) {
+ return null != entry.getFirstHeader(HTTP.CONTENT_LEN);
+ }
+
+ /**
+ * This matters for deciding whether the cache entry is valid to serve as a
+ * response. If these values do not match, we might have a partial response
+ *
+ * @param entry The cache entry we are currently working with
+ * @return boolean indicating whether actual length matches Content-Length
+ */
+ protected boolean contentLengthHeaderMatchesActualLength(final HttpCacheEntry entry) {
+ return !hasContentLengthHeader(entry) || getContentLengthValue(entry) == entry.getResource().length();
+ }
+
+ protected long getApparentAgeSecs(final HttpCacheEntry entry) {
+ final Date dateValue = entry.getDate();
+ if (dateValue == null) {
+ return MAX_AGE;
+ }
+ final long diff = entry.getResponseDate().getTime() - dateValue.getTime();
+ if (diff < 0L) {
+ return 0;
+ }
+ return (diff / 1000);
+ }
+
+ protected long getAgeValue(final HttpCacheEntry entry) {
+ long ageValue = 0;
+ for (final Header hdr : entry.getHeaders(HeaderConstants.AGE)) {
+ long hdrAge;
+ try {
+ hdrAge = Long.parseLong(hdr.getValue());
+ if (hdrAge < 0) {
+ hdrAge = MAX_AGE;
+ }
+ } catch (final NumberFormatException nfe) {
+ hdrAge = MAX_AGE;
+ }
+ ageValue = (hdrAge > ageValue) ? hdrAge : ageValue;
+ }
+ return ageValue;
+ }
+
+ protected long getCorrectedReceivedAgeSecs(final HttpCacheEntry entry) {
+ final long apparentAge = getApparentAgeSecs(entry);
+ final long ageValue = getAgeValue(entry);
+ return (apparentAge > ageValue) ? apparentAge : ageValue;
+ }
+
+ protected long getResponseDelaySecs(final HttpCacheEntry entry) {
+ final long diff = entry.getResponseDate().getTime() - entry.getRequestDate().getTime();
+ return (diff / 1000L);
+ }
+
+ protected long getCorrectedInitialAgeSecs(final HttpCacheEntry entry) {
+ return getCorrectedReceivedAgeSecs(entry) + getResponseDelaySecs(entry);
+ }
+
+ protected long getResidentTimeSecs(final HttpCacheEntry entry, final Date now) {
+ final long diff = now.getTime() - entry.getResponseDate().getTime();
+ return (diff / 1000L);
+ }
+
+ protected long getMaxAge(final HttpCacheEntry entry) {
+ long maxage = -1;
+ for (final Header hdr : entry.getHeaders(HeaderConstants.CACHE_CONTROL)) {
+ for (final HeaderElement elt : hdr.getElements()) {
+ if (HeaderConstants.CACHE_CONTROL_MAX_AGE.equals(elt.getName())
+ || "s-maxage".equals(elt.getName())) {
+ try {
+ final long currMaxAge = Long.parseLong(elt.getValue());
+ if (maxage == -1 || currMaxAge < maxage) {
+ maxage = currMaxAge;
+ }
+ } catch (final NumberFormatException nfe) {
+ // be conservative if can't parse
+ maxage = 0;
+ }
+ }
+ }
+ }
+ return maxage;
+ }
+
+ protected Date getExpirationDate(final HttpCacheEntry entry) {
+ final Header expiresHeader = entry.getFirstHeader(HeaderConstants.EXPIRES);
+ if (expiresHeader == null) {
+ return null;
+ }
+ return DateUtils.parseDate(expiresHeader.getValue());
+ }
+
+ public boolean hasCacheControlDirective(final HttpCacheEntry entry,
+ final String directive) {
+ for (final Header h : entry.getHeaders(HeaderConstants.CACHE_CONTROL)) {
+ for(final HeaderElement elt : h.getElements()) {
+ if (directive.equalsIgnoreCase(elt.getName())) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public long getStalenessSecs(final HttpCacheEntry entry, final Date now) {
+ final long age = getCurrentAgeSecs(entry, now);
+ final long freshness = getFreshnessLifetimeSecs(entry);
+ if (age <= freshness) {
+ return 0L;
+ }
+ return (age - freshness);
+ }
+
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheableRequestPolicy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheableRequestPolicy.java
new file mode 100644
index 000000000..500da01dc
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CacheableRequestPolicy.java
@@ -0,0 +1,96 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HeaderElement;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpVersion;
+import ch.boye.httpclientandroidlib.ProtocolVersion;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.cache.HeaderConstants;
+
+/**
+ * Determines if an HttpRequest is allowed to be served from the cache.
+ *
+ * @since 4.1
+ */
+@Immutable
+class CacheableRequestPolicy {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ /**
+ * Determines if an HttpRequest can be served from the cache.
+ *
+ * @param request
+ * an HttpRequest
+ * @return boolean Is it possible to serve this request from cache
+ */
+ public boolean isServableFromCache(final HttpRequest request) {
+ final String method = request.getRequestLine().getMethod();
+
+ final ProtocolVersion pv = request.getRequestLine().getProtocolVersion();
+ if (HttpVersion.HTTP_1_1.compareToVersion(pv) != 0) {
+ log.trace("non-HTTP/1.1 request was not serveable from cache");
+ return false;
+ }
+
+ if (!method.equals(HeaderConstants.GET_METHOD)) {
+ log.trace("non-GET request was not serveable from cache");
+ return false;
+ }
+
+ if (request.getHeaders(HeaderConstants.PRAGMA).length > 0) {
+ log.trace("request with Pragma header was not serveable from cache");
+ return false;
+ }
+
+ final Header[] cacheControlHeaders = request.getHeaders(HeaderConstants.CACHE_CONTROL);
+ for (final Header cacheControl : cacheControlHeaders) {
+ for (final HeaderElement cacheControlElement : cacheControl.getElements()) {
+ if (HeaderConstants.CACHE_CONTROL_NO_STORE.equalsIgnoreCase(cacheControlElement
+ .getName())) {
+ log.trace("Request with no-store was not serveable from cache");
+ return false;
+ }
+
+ if (HeaderConstants.CACHE_CONTROL_NO_CACHE.equalsIgnoreCase(cacheControlElement
+ .getName())) {
+ log.trace("Request with no-cache was not serveable from cache");
+ return false;
+ }
+ }
+ }
+
+ log.trace("Request was serveable from cache");
+ return true;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CachedHttpResponseGenerator.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CachedHttpResponseGenerator.java
new file mode 100644
index 000000000..f42529e57
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CachedHttpResponseGenerator.java
@@ -0,0 +1,166 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.util.Date;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.HttpVersion;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.cache.HeaderConstants;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.client.methods.CloseableHttpResponse;
+import ch.boye.httpclientandroidlib.client.utils.DateUtils;
+import ch.boye.httpclientandroidlib.message.BasicHeader;
+import ch.boye.httpclientandroidlib.message.BasicHttpResponse;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+
+/**
+ * Rebuilds an {@link HttpResponse} from a {@link net.sf.ehcache.CacheEntry}
+ *
+ * @since 4.1
+ */
+@Immutable
+class CachedHttpResponseGenerator {
+
+ private final CacheValidityPolicy validityStrategy;
+
+ CachedHttpResponseGenerator(final CacheValidityPolicy validityStrategy) {
+ super();
+ this.validityStrategy = validityStrategy;
+ }
+
+ CachedHttpResponseGenerator() {
+ this(new CacheValidityPolicy());
+ }
+
+ /**
+ * If I was able to use a {@link CacheEntity} to response to the {@link ch.boye.httpclientandroidlib.HttpRequest} then
+ * generate an {@link HttpResponse} based on the cache entry.
+ * @param entry
+ * {@link CacheEntity} to transform into an {@link HttpResponse}
+ * @return {@link HttpResponse} that was constructed
+ */
+ CloseableHttpResponse generateResponse(final HttpCacheEntry entry) {
+
+ final Date now = new Date();
+ final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, entry
+ .getStatusCode(), entry.getReasonPhrase());
+
+ response.setHeaders(entry.getAllHeaders());
+
+ if (entry.getResource() != null) {
+ final HttpEntity entity = new CacheEntity(entry);
+ addMissingContentLengthHeader(response, entity);
+ response.setEntity(entity);
+ }
+
+ final long age = this.validityStrategy.getCurrentAgeSecs(entry, now);
+ if (age > 0) {
+ if (age >= Integer.MAX_VALUE) {
+ response.setHeader(HeaderConstants.AGE, "2147483648");
+ } else {
+ response.setHeader(HeaderConstants.AGE, "" + ((int) age));
+ }
+ }
+
+ return Proxies.enhanceResponse(response);
+ }
+
+ /**
+ * Generate a 304 - Not Modified response from a {@link CacheEntity}. This should be
+ * used to respond to conditional requests, when the entry exists or has been re-validated.
+ */
+ CloseableHttpResponse generateNotModifiedResponse(final HttpCacheEntry entry) {
+
+ final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,
+ HttpStatus.SC_NOT_MODIFIED, "Not Modified");
+
+ // The response MUST include the following headers
+ // (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)
+
+ // - Date, unless its omission is required by section 14.8.1
+ Header dateHeader = entry.getFirstHeader(HTTP.DATE_HEADER);
+ if (dateHeader == null) {
+ dateHeader = new BasicHeader(HTTP.DATE_HEADER, DateUtils.formatDate(new Date()));
+ }
+ response.addHeader(dateHeader);
+
+ // - ETag and/or Content-Location, if the header would have been sent
+ // in a 200 response to the same request
+ final Header etagHeader = entry.getFirstHeader(HeaderConstants.ETAG);
+ if (etagHeader != null) {
+ response.addHeader(etagHeader);
+ }
+
+ final Header contentLocationHeader = entry.getFirstHeader("Content-Location");
+ if (contentLocationHeader != null) {
+ response.addHeader(contentLocationHeader);
+ }
+
+ // - Expires, Cache-Control, and/or Vary, if the field-value might
+ // differ from that sent in any previous response for the same
+ // variant
+ final Header expiresHeader = entry.getFirstHeader(HeaderConstants.EXPIRES);
+ if (expiresHeader != null) {
+ response.addHeader(expiresHeader);
+ }
+
+ final Header cacheControlHeader = entry.getFirstHeader(HeaderConstants.CACHE_CONTROL);
+ if (cacheControlHeader != null) {
+ response.addHeader(cacheControlHeader);
+ }
+
+ final Header varyHeader = entry.getFirstHeader(HeaderConstants.VARY);
+ if (varyHeader != null) {
+ response.addHeader(varyHeader);
+ }
+
+ return Proxies.enhanceResponse(response);
+ }
+
+ private void addMissingContentLengthHeader(final HttpResponse response, final HttpEntity entity) {
+ if (transferEncodingIsPresent(response)) {
+ return;
+ }
+
+ Header contentLength = response.getFirstHeader(HTTP.CONTENT_LEN);
+ if (contentLength == null) {
+ contentLength = new BasicHeader(HTTP.CONTENT_LEN, Long.toString(entity
+ .getContentLength()));
+ response.setHeader(contentLength);
+ }
+ }
+
+ private boolean transferEncodingIsPresent(final HttpResponse response) {
+ final Header hdr = response.getFirstHeader(HTTP.TRANSFER_ENCODING);
+ return hdr != null;
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CachedResponseSuitabilityChecker.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CachedResponseSuitabilityChecker.java
new file mode 100644
index 000000000..a289729d3
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CachedResponseSuitabilityChecker.java
@@ -0,0 +1,346 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.util.Date;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HeaderElement;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.cache.HeaderConstants;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.client.utils.DateUtils;
+
+/**
+ * Determines whether a given {@link HttpCacheEntry} is suitable to be
+ * used as a response for a given {@link HttpRequest}.
+ *
+ * @since 4.1
+ */
+@Immutable
+class CachedResponseSuitabilityChecker {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ private final boolean sharedCache;
+ private final boolean useHeuristicCaching;
+ private final float heuristicCoefficient;
+ private final long heuristicDefaultLifetime;
+ private final CacheValidityPolicy validityStrategy;
+
+ CachedResponseSuitabilityChecker(final CacheValidityPolicy validityStrategy,
+ final CacheConfig config) {
+ super();
+ this.validityStrategy = validityStrategy;
+ this.sharedCache = config.isSharedCache();
+ this.useHeuristicCaching = config.isHeuristicCachingEnabled();
+ this.heuristicCoefficient = config.getHeuristicCoefficient();
+ this.heuristicDefaultLifetime = config.getHeuristicDefaultLifetime();
+ }
+
+ CachedResponseSuitabilityChecker(final CacheConfig config) {
+ this(new CacheValidityPolicy(), config);
+ }
+
+ private boolean isFreshEnough(final HttpCacheEntry entry, final HttpRequest request, final Date now) {
+ if (validityStrategy.isResponseFresh(entry, now)) {
+ return true;
+ }
+ if (useHeuristicCaching &&
+ validityStrategy.isResponseHeuristicallyFresh(entry, now, heuristicCoefficient, heuristicDefaultLifetime)) {
+ return true;
+ }
+ if (originInsistsOnFreshness(entry)) {
+ return false;
+ }
+ final long maxstale = getMaxStale(request);
+ if (maxstale == -1) {
+ return false;
+ }
+ return (maxstale > validityStrategy.getStalenessSecs(entry, now));
+ }
+
+ private boolean originInsistsOnFreshness(final HttpCacheEntry entry) {
+ if (validityStrategy.mustRevalidate(entry)) {
+ return true;
+ }
+ if (!sharedCache) {
+ return false;
+ }
+ return validityStrategy.proxyRevalidate(entry) ||
+ validityStrategy.hasCacheControlDirective(entry, "s-maxage");
+ }
+
+ private long getMaxStale(final HttpRequest request) {
+ long maxstale = -1;
+ for(final Header h : request.getHeaders(HeaderConstants.CACHE_CONTROL)) {
+ for(final HeaderElement elt : h.getElements()) {
+ if (HeaderConstants.CACHE_CONTROL_MAX_STALE.equals(elt.getName())) {
+ if ((elt.getValue() == null || "".equals(elt.getValue().trim()))
+ && maxstale == -1) {
+ maxstale = Long.MAX_VALUE;
+ } else {
+ try {
+ long val = Long.parseLong(elt.getValue());
+ if (val < 0) {
+ val = 0;
+ }
+ if (maxstale == -1 || val < maxstale) {
+ maxstale = val;
+ }
+ } catch (final NumberFormatException nfe) {
+ // err on the side of preserving semantic transparency
+ maxstale = 0;
+ }
+ }
+ }
+ }
+ }
+ return maxstale;
+ }
+
+ /**
+ * Determine if I can utilize a {@link HttpCacheEntry} to respond to the given
+ * {@link HttpRequest}
+ *
+ * @param host
+ * {@link HttpHost}
+ * @param request
+ * {@link HttpRequest}
+ * @param entry
+ * {@link HttpCacheEntry}
+ * @param now
+ * Right now in time
+ * @return boolean yes/no answer
+ */
+ public boolean canCachedResponseBeUsed(final HttpHost host, final HttpRequest request, final HttpCacheEntry entry, final Date now) {
+
+ if (!isFreshEnough(entry, request, now)) {
+ log.trace("Cache entry was not fresh enough");
+ return false;
+ }
+
+ if (!validityStrategy.contentLengthHeaderMatchesActualLength(entry)) {
+ log.debug("Cache entry Content-Length and header information do not match");
+ return false;
+ }
+
+ if (hasUnsupportedConditionalHeaders(request)) {
+ log.debug("Request contained conditional headers we don't handle");
+ return false;
+ }
+
+ if (!isConditional(request) && entry.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
+ return false;
+ }
+
+ if (isConditional(request) && !allConditionalsMatch(request, entry, now)) {
+ return false;
+ }
+
+ for (final Header ccHdr : request.getHeaders(HeaderConstants.CACHE_CONTROL)) {
+ for (final HeaderElement elt : ccHdr.getElements()) {
+ if (HeaderConstants.CACHE_CONTROL_NO_CACHE.equals(elt.getName())) {
+ log.trace("Response contained NO CACHE directive, cache was not suitable");
+ return false;
+ }
+
+ if (HeaderConstants.CACHE_CONTROL_NO_STORE.equals(elt.getName())) {
+ log.trace("Response contained NO STORE directive, cache was not suitable");
+ return false;
+ }
+
+ if (HeaderConstants.CACHE_CONTROL_MAX_AGE.equals(elt.getName())) {
+ try {
+ final int maxage = Integer.parseInt(elt.getValue());
+ if (validityStrategy.getCurrentAgeSecs(entry, now) > maxage) {
+ log.trace("Response from cache was NOT suitable due to max age");
+ return false;
+ }
+ } catch (final NumberFormatException ex) {
+ // err conservatively
+ log.debug("Response from cache was malformed" + ex.getMessage());
+ return false;
+ }
+ }
+
+ if (HeaderConstants.CACHE_CONTROL_MAX_STALE.equals(elt.getName())) {
+ try {
+ final int maxstale = Integer.parseInt(elt.getValue());
+ if (validityStrategy.getFreshnessLifetimeSecs(entry) > maxstale) {
+ log.trace("Response from cache was not suitable due to Max stale freshness");
+ return false;
+ }
+ } catch (final NumberFormatException ex) {
+ // err conservatively
+ log.debug("Response from cache was malformed: " + ex.getMessage());
+ return false;
+ }
+ }
+
+ if (HeaderConstants.CACHE_CONTROL_MIN_FRESH.equals(elt.getName())) {
+ try {
+ final long minfresh = Long.parseLong(elt.getValue());
+ if (minfresh < 0L) {
+ return false;
+ }
+ final long age = validityStrategy.getCurrentAgeSecs(entry, now);
+ final long freshness = validityStrategy.getFreshnessLifetimeSecs(entry);
+ if (freshness - age < minfresh) {
+ log.trace("Response from cache was not suitable due to min fresh " +
+ "freshness requirement");
+ return false;
+ }
+ } catch (final NumberFormatException ex) {
+ // err conservatively
+ log.debug("Response from cache was malformed: " + ex.getMessage());
+ return false;
+ }
+ }
+ }
+ }
+
+ log.trace("Response from cache was suitable");
+ return true;
+ }
+
+ /**
+ * Is this request the type of conditional request we support?
+ * @param request The current httpRequest being made
+ * @return {@code true} if the request is supported
+ */
+ public boolean isConditional(final HttpRequest request) {
+ return hasSupportedEtagValidator(request) || hasSupportedLastModifiedValidator(request);
+ }
+
+ /**
+ * Check that conditionals that are part of this request match
+ * @param request The current httpRequest being made
+ * @param entry the cache entry
+ * @param now right NOW in time
+ * @return {@code true} if the request matches all conditionals
+ */
+ public boolean allConditionalsMatch(final HttpRequest request, final HttpCacheEntry entry, final Date now) {
+ final boolean hasEtagValidator = hasSupportedEtagValidator(request);
+ final boolean hasLastModifiedValidator = hasSupportedLastModifiedValidator(request);
+
+ final boolean etagValidatorMatches = (hasEtagValidator) && etagValidatorMatches(request, entry);
+ final boolean lastModifiedValidatorMatches = (hasLastModifiedValidator) && lastModifiedValidatorMatches(request, entry, now);
+
+ if ((hasEtagValidator && hasLastModifiedValidator)
+ && !(etagValidatorMatches && lastModifiedValidatorMatches)) {
+ return false;
+ } else if (hasEtagValidator && !etagValidatorMatches) {
+ return false;
+ }
+
+ if (hasLastModifiedValidator && !lastModifiedValidatorMatches) {
+ return false;
+ }
+ return true;
+ }
+
+ private boolean hasUnsupportedConditionalHeaders(final HttpRequest request) {
+ return (request.getFirstHeader(HeaderConstants.IF_RANGE) != null
+ || request.getFirstHeader(HeaderConstants.IF_MATCH) != null
+ || hasValidDateField(request, HeaderConstants.IF_UNMODIFIED_SINCE));
+ }
+
+ private boolean hasSupportedEtagValidator(final HttpRequest request) {
+ return request.containsHeader(HeaderConstants.IF_NONE_MATCH);
+ }
+
+ private boolean hasSupportedLastModifiedValidator(final HttpRequest request) {
+ return hasValidDateField(request, HeaderConstants.IF_MODIFIED_SINCE);
+ }
+
+ /**
+ * Check entry against If-None-Match
+ * @param request The current httpRequest being made
+ * @param entry the cache entry
+ * @return boolean does the etag validator match
+ */
+ private boolean etagValidatorMatches(final HttpRequest request, final HttpCacheEntry entry) {
+ final Header etagHeader = entry.getFirstHeader(HeaderConstants.ETAG);
+ final String etag = (etagHeader != null) ? etagHeader.getValue() : null;
+ final Header[] ifNoneMatch = request.getHeaders(HeaderConstants.IF_NONE_MATCH);
+ if (ifNoneMatch != null) {
+ for (final Header h : ifNoneMatch) {
+ for (final HeaderElement elt : h.getElements()) {
+ final String reqEtag = elt.toString();
+ if (("*".equals(reqEtag) && etag != null)
+ || reqEtag.equals(etag)) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Check entry against If-Modified-Since, if If-Modified-Since is in the future it is invalid as per
+ * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
+ * @param request The current httpRequest being made
+ * @param entry the cache entry
+ * @param now right NOW in time
+ * @return boolean Does the last modified header match
+ */
+ private boolean lastModifiedValidatorMatches(final HttpRequest request, final HttpCacheEntry entry, final Date now) {
+ final Header lastModifiedHeader = entry.getFirstHeader(HeaderConstants.LAST_MODIFIED);
+ Date lastModified = null;
+ if (lastModifiedHeader != null) {
+ lastModified = DateUtils.parseDate(lastModifiedHeader.getValue());
+ }
+ if (lastModified == null) {
+ return false;
+ }
+
+ for (final Header h : request.getHeaders(HeaderConstants.IF_MODIFIED_SINCE)) {
+ final Date ifModifiedSince = DateUtils.parseDate(h.getValue());
+ if (ifModifiedSince != null) {
+ if (ifModifiedSince.after(now) || lastModified.after(ifModifiedSince)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private boolean hasValidDateField(final HttpRequest request, final String headerName) {
+ for(final Header h : request.getHeaders(headerName)) {
+ final Date date = DateUtils.parseDate(h.getValue());
+ return date != null;
+ }
+ return false;
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CachingExec.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CachingExec.java
new file mode 100644
index 000000000..cf9b8154a
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CachingExec.java
@@ -0,0 +1,870 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.IOException;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HeaderElement;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpMessage;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.HttpVersion;
+import ch.boye.httpclientandroidlib.ProtocolVersion;
+import ch.boye.httpclientandroidlib.RequestLine;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.client.cache.CacheResponseStatus;
+import ch.boye.httpclientandroidlib.client.cache.HeaderConstants;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheContext;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheStorage;
+import ch.boye.httpclientandroidlib.client.cache.ResourceFactory;
+import ch.boye.httpclientandroidlib.client.methods.CloseableHttpResponse;
+import ch.boye.httpclientandroidlib.client.methods.HttpExecutionAware;
+import ch.boye.httpclientandroidlib.client.methods.HttpRequestWrapper;
+import ch.boye.httpclientandroidlib.client.protocol.HttpClientContext;
+import ch.boye.httpclientandroidlib.client.utils.DateUtils;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.impl.execchain.ClientExecChain;
+import ch.boye.httpclientandroidlib.message.BasicHttpResponse;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.VersionInfo;
+
+/**
+ * Request executor in the request execution chain that is responsible for
+ * transparent client-side caching. The current implementation is conditionally
+ * compliant with HTTP/1.1 (meaning all the MUST and MUST NOTs are obeyed),
+ * although quite a lot, though not all, of the SHOULDs and SHOULD NOTs
+ * are obeyed too.
+ *
+ * Folks that would like to experiment with alternative storage backends
+ * should look at the {@link HttpCacheStorage} interface and the related
+ * package documentation there. You may also be interested in the provided
+ * {@link ch.boye.httpclientandroidlib.impl.client.cache.ehcache.EhcacheHttpCacheStorage
+ * EhCache} and {@link
+ * ch.boye.httpclientandroidlib.impl.client.cache.memcached.MemcachedHttpCacheStorage
+ * memcached} storage backends.
+ *
+ * Further responsibilities such as communication with the opposite
+ * endpoint is delegated to the next executor in the request execution
+ * chain.
+ *
+ * @since 4.3
+ */
+@ThreadSafe // So long as the responseCache implementation is threadsafe
+public class CachingExec implements ClientExecChain {
+
+ private final static boolean SUPPORTS_RANGE_AND_CONTENT_RANGE_HEADERS = false;
+
+ private final AtomicLong cacheHits = new AtomicLong();
+ private final AtomicLong cacheMisses = new AtomicLong();
+ private final AtomicLong cacheUpdates = new AtomicLong();
+
+ private final Map viaHeaders = new HashMap(4);
+
+ private final CacheConfig cacheConfig;
+ private final ClientExecChain backend;
+ private final HttpCache responseCache;
+ private final CacheValidityPolicy validityPolicy;
+ private final CachedHttpResponseGenerator responseGenerator;
+ private final CacheableRequestPolicy cacheableRequestPolicy;
+ private final CachedResponseSuitabilityChecker suitabilityChecker;
+ private final ConditionalRequestBuilder conditionalRequestBuilder;
+ private final ResponseProtocolCompliance responseCompliance;
+ private final RequestProtocolCompliance requestCompliance;
+ private final ResponseCachingPolicy responseCachingPolicy;
+
+ private final AsynchronousValidator asynchRevalidator;
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ public CachingExec(
+ final ClientExecChain backend,
+ final HttpCache cache,
+ final CacheConfig config) {
+ this(backend, cache, config, null);
+ }
+
+ public CachingExec(
+ final ClientExecChain backend,
+ final HttpCache cache,
+ final CacheConfig config,
+ final AsynchronousValidator asynchRevalidator) {
+ super();
+ Args.notNull(backend, "HTTP backend");
+ Args.notNull(cache, "HttpCache");
+ this.cacheConfig = config != null ? config : CacheConfig.DEFAULT;
+ this.backend = backend;
+ this.responseCache = cache;
+ this.validityPolicy = new CacheValidityPolicy();
+ this.responseGenerator = new CachedHttpResponseGenerator(this.validityPolicy);
+ this.cacheableRequestPolicy = new CacheableRequestPolicy();
+ this.suitabilityChecker = new CachedResponseSuitabilityChecker(this.validityPolicy, this.cacheConfig);
+ this.conditionalRequestBuilder = new ConditionalRequestBuilder();
+ this.responseCompliance = new ResponseProtocolCompliance();
+ this.requestCompliance = new RequestProtocolCompliance(this.cacheConfig.isWeakETagOnPutDeleteAllowed());
+ this.responseCachingPolicy = new ResponseCachingPolicy(
+ this.cacheConfig.getMaxObjectSize(), this.cacheConfig.isSharedCache(),
+ this.cacheConfig.isNeverCacheHTTP10ResponsesWithQuery(), this.cacheConfig.is303CachingEnabled());
+ this.asynchRevalidator = asynchRevalidator;
+ }
+
+ public CachingExec(
+ final ClientExecChain backend,
+ final ResourceFactory resourceFactory,
+ final HttpCacheStorage storage,
+ final CacheConfig config) {
+ this(backend, new BasicHttpCache(resourceFactory, storage, config), config);
+ }
+
+ public CachingExec(final ClientExecChain backend) {
+ this(backend, new BasicHttpCache(), CacheConfig.DEFAULT);
+ }
+
+ CachingExec(
+ final ClientExecChain backend,
+ final HttpCache responseCache,
+ final CacheValidityPolicy validityPolicy,
+ final ResponseCachingPolicy responseCachingPolicy,
+ final CachedHttpResponseGenerator responseGenerator,
+ final CacheableRequestPolicy cacheableRequestPolicy,
+ final CachedResponseSuitabilityChecker suitabilityChecker,
+ final ConditionalRequestBuilder conditionalRequestBuilder,
+ final ResponseProtocolCompliance responseCompliance,
+ final RequestProtocolCompliance requestCompliance,
+ final CacheConfig config,
+ final AsynchronousValidator asynchRevalidator) {
+ this.cacheConfig = config != null ? config : CacheConfig.DEFAULT;
+ this.backend = backend;
+ this.responseCache = responseCache;
+ this.validityPolicy = validityPolicy;
+ this.responseCachingPolicy = responseCachingPolicy;
+ this.responseGenerator = responseGenerator;
+ this.cacheableRequestPolicy = cacheableRequestPolicy;
+ this.suitabilityChecker = suitabilityChecker;
+ this.conditionalRequestBuilder = conditionalRequestBuilder;
+ this.responseCompliance = responseCompliance;
+ this.requestCompliance = requestCompliance;
+ this.asynchRevalidator = asynchRevalidator;
+ }
+
+ /**
+ * Reports the number of times that the cache successfully responded
+ * to an {@link HttpRequest} without contacting the origin server.
+ * @return the number of cache hits
+ */
+ public long getCacheHits() {
+ return cacheHits.get();
+ }
+
+ /**
+ * Reports the number of times that the cache contacted the origin
+ * server because it had no appropriate response cached.
+ * @return the number of cache misses
+ */
+ public long getCacheMisses() {
+ return cacheMisses.get();
+ }
+
+ /**
+ * Reports the number of times that the cache was able to satisfy
+ * a response by revalidating an existing but stale cache entry.
+ * @return the number of cache revalidations
+ */
+ public long getCacheUpdates() {
+ return cacheUpdates.get();
+ }
+
+ public CloseableHttpResponse execute(
+ final HttpRoute route,
+ final HttpRequestWrapper request) throws IOException, HttpException {
+ return execute(route, request, HttpClientContext.create(), null);
+ }
+
+ public CloseableHttpResponse execute(
+ final HttpRoute route,
+ final HttpRequestWrapper request,
+ final HttpClientContext context) throws IOException, HttpException {
+ return execute(route, request, context, null);
+ }
+
+ public CloseableHttpResponse execute(
+ final HttpRoute route,
+ final HttpRequestWrapper request,
+ final HttpClientContext context,
+ final HttpExecutionAware execAware) throws IOException, HttpException {
+
+ final HttpHost target = context.getTargetHost();
+ final String via = generateViaHeader(request.getOriginal());
+
+ // default response context
+ setResponseStatus(context, CacheResponseStatus.CACHE_MISS);
+
+ if (clientRequestsOurOptions(request)) {
+ setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE);
+ return Proxies.enhanceResponse(new OptionsHttp11Response());
+ }
+
+ final HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse(request, context);
+ if (fatalErrorResponse != null) {
+ return Proxies.enhanceResponse(fatalErrorResponse);
+ }
+
+ requestCompliance.makeRequestCompliant(request);
+ request.addHeader("Via",via);
+
+ flushEntriesInvalidatedByRequest(context.getTargetHost(), request);
+
+ if (!cacheableRequestPolicy.isServableFromCache(request)) {
+ log.debug("Request is not servable from cache");
+ return callBackend(route, request, context, execAware);
+ }
+
+ final HttpCacheEntry entry = satisfyFromCache(target, request);
+ if (entry == null) {
+ log.debug("Cache miss");
+ return handleCacheMiss(route, request, context, execAware);
+ } else {
+ return handleCacheHit(route, request, context, execAware, entry);
+ }
+ }
+
+ private CloseableHttpResponse handleCacheHit(
+ final HttpRoute route,
+ final HttpRequestWrapper request,
+ final HttpClientContext context,
+ final HttpExecutionAware execAware,
+ final HttpCacheEntry entry) throws IOException, HttpException {
+ final HttpHost target = context.getTargetHost();
+ recordCacheHit(target, request);
+ CloseableHttpResponse out = null;
+ final Date now = getCurrentDate();
+ if (suitabilityChecker.canCachedResponseBeUsed(target, request, entry, now)) {
+ log.debug("Cache hit");
+ out = generateCachedResponse(request, context, entry, now);
+ } else if (!mayCallBackend(request)) {
+ log.debug("Cache entry not suitable but only-if-cached requested");
+ out = generateGatewayTimeout(context);
+ } else if (!(entry.getStatusCode() == HttpStatus.SC_NOT_MODIFIED
+ && !suitabilityChecker.isConditional(request))) {
+ log.debug("Revalidating cache entry");
+ return revalidateCacheEntry(route, request, context, execAware, entry, now);
+ } else {
+ log.debug("Cache entry not usable; calling backend");
+ return callBackend(route, request, context, execAware);
+ }
+ context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
+ context.setAttribute(HttpClientContext.HTTP_TARGET_HOST, target);
+ context.setAttribute(HttpClientContext.HTTP_REQUEST, request);
+ context.setAttribute(HttpClientContext.HTTP_RESPONSE, out);
+ context.setAttribute(HttpClientContext.HTTP_REQ_SENT, Boolean.TRUE);
+ return out;
+ }
+
+ private CloseableHttpResponse revalidateCacheEntry(
+ final HttpRoute route,
+ final HttpRequestWrapper request,
+ final HttpClientContext context,
+ final HttpExecutionAware execAware,
+ final HttpCacheEntry entry,
+ final Date now) throws HttpException {
+
+ try {
+ if (asynchRevalidator != null
+ && !staleResponseNotAllowed(request, entry, now)
+ && validityPolicy.mayReturnStaleWhileRevalidating(entry, now)) {
+ log.trace("Serving stale with asynchronous revalidation");
+ final CloseableHttpResponse resp = generateCachedResponse(request, context, entry, now);
+ asynchRevalidator.revalidateCacheEntry(this, route, request, context, execAware, entry);
+ return resp;
+ }
+ return revalidateCacheEntry(route, request, context, execAware, entry);
+ } catch (final IOException ioex) {
+ return handleRevalidationFailure(request, context, entry, now);
+ }
+ }
+
+ private CloseableHttpResponse handleCacheMiss(
+ final HttpRoute route,
+ final HttpRequestWrapper request,
+ final HttpClientContext context,
+ final HttpExecutionAware execAware) throws IOException, HttpException {
+ final HttpHost target = context.getTargetHost();
+ recordCacheMiss(target, request);
+
+ if (!mayCallBackend(request)) {
+ return Proxies.enhanceResponse(
+ new BasicHttpResponse(
+ HttpVersion.HTTP_1_1, HttpStatus.SC_GATEWAY_TIMEOUT, "Gateway Timeout"));
+ }
+
+ final Map variants = getExistingCacheVariants(target, request);
+ if (variants != null && variants.size() > 0) {
+ return negotiateResponseFromVariants(route, request, context,
+ execAware, variants);
+ }
+
+ return callBackend(route, request, context, execAware);
+ }
+
+ private HttpCacheEntry satisfyFromCache(
+ final HttpHost target, final HttpRequestWrapper request) {
+ HttpCacheEntry entry = null;
+ try {
+ entry = responseCache.getCacheEntry(target, request);
+ } catch (final IOException ioe) {
+ log.warn("Unable to retrieve entries from cache", ioe);
+ }
+ return entry;
+ }
+
+ private HttpResponse getFatallyNoncompliantResponse(
+ final HttpRequestWrapper request,
+ final HttpContext context) {
+ HttpResponse fatalErrorResponse = null;
+ final List fatalError = requestCompliance.requestIsFatallyNonCompliant(request);
+
+ for (final RequestProtocolError error : fatalError) {
+ setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE);
+ fatalErrorResponse = requestCompliance.getErrorForRequest(error);
+ }
+ return fatalErrorResponse;
+ }
+
+ private Map getExistingCacheVariants(
+ final HttpHost target,
+ final HttpRequestWrapper request) {
+ Map variants = null;
+ try {
+ variants = responseCache.getVariantCacheEntriesWithEtags(target, request);
+ } catch (final IOException ioe) {
+ log.warn("Unable to retrieve variant entries from cache", ioe);
+ }
+ return variants;
+ }
+
+ private void recordCacheMiss(final HttpHost target, final HttpRequestWrapper request) {
+ cacheMisses.getAndIncrement();
+ if (log.isTraceEnabled()) {
+ final RequestLine rl = request.getRequestLine();
+ log.trace("Cache miss [host: " + target + "; uri: " + rl.getUri() + "]");
+ }
+ }
+
+ private void recordCacheHit(final HttpHost target, final HttpRequestWrapper request) {
+ cacheHits.getAndIncrement();
+ if (log.isTraceEnabled()) {
+ final RequestLine rl = request.getRequestLine();
+ log.trace("Cache hit [host: " + target + "; uri: " + rl.getUri() + "]");
+ }
+ }
+
+ private void recordCacheUpdate(final HttpContext context) {
+ cacheUpdates.getAndIncrement();
+ setResponseStatus(context, CacheResponseStatus.VALIDATED);
+ }
+
+ private void flushEntriesInvalidatedByRequest(
+ final HttpHost target,
+ final HttpRequestWrapper request) {
+ try {
+ responseCache.flushInvalidatedCacheEntriesFor(target, request);
+ } catch (final IOException ioe) {
+ log.warn("Unable to flush invalidated entries from cache", ioe);
+ }
+ }
+
+ private CloseableHttpResponse generateCachedResponse(final HttpRequestWrapper request,
+ final HttpContext context, final HttpCacheEntry entry, final Date now) {
+ final CloseableHttpResponse cachedResponse;
+ if (request.containsHeader(HeaderConstants.IF_NONE_MATCH)
+ || request.containsHeader(HeaderConstants.IF_MODIFIED_SINCE)) {
+ cachedResponse = responseGenerator.generateNotModifiedResponse(entry);
+ } else {
+ cachedResponse = responseGenerator.generateResponse(entry);
+ }
+ setResponseStatus(context, CacheResponseStatus.CACHE_HIT);
+ if (validityPolicy.getStalenessSecs(entry, now) > 0L) {
+ cachedResponse.addHeader(HeaderConstants.WARNING,"110 localhost \"Response is stale\"");
+ }
+ return cachedResponse;
+ }
+
+ private CloseableHttpResponse handleRevalidationFailure(
+ final HttpRequestWrapper request,
+ final HttpContext context,
+ final HttpCacheEntry entry,
+ final Date now) {
+ if (staleResponseNotAllowed(request, entry, now)) {
+ return generateGatewayTimeout(context);
+ } else {
+ return unvalidatedCacheHit(context, entry);
+ }
+ }
+
+ private CloseableHttpResponse generateGatewayTimeout(
+ final HttpContext context) {
+ setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE);
+ return Proxies.enhanceResponse(new BasicHttpResponse(
+ HttpVersion.HTTP_1_1, HttpStatus.SC_GATEWAY_TIMEOUT,
+ "Gateway Timeout"));
+ }
+
+ private CloseableHttpResponse unvalidatedCacheHit(
+ final HttpContext context, final HttpCacheEntry entry) {
+ final CloseableHttpResponse cachedResponse = responseGenerator.generateResponse(entry);
+ setResponseStatus(context, CacheResponseStatus.CACHE_HIT);
+ cachedResponse.addHeader(HeaderConstants.WARNING, "111 localhost \"Revalidation failed\"");
+ return cachedResponse;
+ }
+
+ private boolean staleResponseNotAllowed(
+ final HttpRequestWrapper request,
+ final HttpCacheEntry entry,
+ final Date now) {
+ return validityPolicy.mustRevalidate(entry)
+ || (cacheConfig.isSharedCache() && validityPolicy.proxyRevalidate(entry))
+ || explicitFreshnessRequest(request, entry, now);
+ }
+
+ private boolean mayCallBackend(final HttpRequestWrapper request) {
+ for (final Header h: request.getHeaders(HeaderConstants.CACHE_CONTROL)) {
+ for (final HeaderElement elt : h.getElements()) {
+ if ("only-if-cached".equals(elt.getName())) {
+ log.trace("Request marked only-if-cached");
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private boolean explicitFreshnessRequest(
+ final HttpRequestWrapper request,
+ final HttpCacheEntry entry,
+ final Date now) {
+ for(final Header h : request.getHeaders(HeaderConstants.CACHE_CONTROL)) {
+ for(final HeaderElement elt : h.getElements()) {
+ if (HeaderConstants.CACHE_CONTROL_MAX_STALE.equals(elt.getName())) {
+ try {
+ final int maxstale = Integer.parseInt(elt.getValue());
+ final long age = validityPolicy.getCurrentAgeSecs(entry, now);
+ final long lifetime = validityPolicy.getFreshnessLifetimeSecs(entry);
+ if (age - lifetime > maxstale) {
+ return true;
+ }
+ } catch (final NumberFormatException nfe) {
+ return true;
+ }
+ } else if (HeaderConstants.CACHE_CONTROL_MIN_FRESH.equals(elt.getName())
+ || HeaderConstants.CACHE_CONTROL_MAX_AGE.equals(elt.getName())) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private String generateViaHeader(final HttpMessage msg) {
+
+ final ProtocolVersion pv = msg.getProtocolVersion();
+ final String existingEntry = viaHeaders.get(pv);
+ if (existingEntry != null) {
+ return existingEntry;
+ }
+
+ final VersionInfo vi = VersionInfo.loadVersionInfo("ch.boye.httpclientandroidlib.client", getClass().getClassLoader());
+ final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
+
+ String value;
+ if ("http".equalsIgnoreCase(pv.getProtocol())) {
+ value = String.format("%d.%d localhost (Apache-HttpClient/%s (cache))", pv.getMajor(), pv.getMinor(),
+ release);
+ } else {
+ value = String.format("%s/%d.%d localhost (Apache-HttpClient/%s (cache))", pv.getProtocol(), pv.getMajor(),
+ pv.getMinor(), release);
+ }
+ viaHeaders.put(pv, value);
+
+ return value;
+ }
+
+ private void setResponseStatus(final HttpContext context, final CacheResponseStatus value) {
+ if (context != null) {
+ context.setAttribute(HttpCacheContext.CACHE_RESPONSE_STATUS, value);
+ }
+ }
+
+ /**
+ * Reports whether this {@code CachingHttpClient} implementation
+ * supports byte-range requests as specified by the {@code Range}
+ * and {@code Content-Range} headers.
+ * @return {@code true} if byte-range requests are supported
+ */
+ public boolean supportsRangeAndContentRangeHeaders() {
+ return SUPPORTS_RANGE_AND_CONTENT_RANGE_HEADERS;
+ }
+
+ Date getCurrentDate() {
+ return new Date();
+ }
+
+ boolean clientRequestsOurOptions(final HttpRequest request) {
+ final RequestLine line = request.getRequestLine();
+
+ if (!HeaderConstants.OPTIONS_METHOD.equals(line.getMethod())) {
+ return false;
+ }
+
+ if (!"*".equals(line.getUri())) {
+ return false;
+ }
+
+ if (!"0".equals(request.getFirstHeader(HeaderConstants.MAX_FORWARDS).getValue())) {
+ return false;
+ }
+
+ return true;
+ }
+
+ CloseableHttpResponse callBackend(
+ final HttpRoute route,
+ final HttpRequestWrapper request,
+ final HttpClientContext context,
+ final HttpExecutionAware execAware) throws IOException, HttpException {
+
+ final Date requestDate = getCurrentDate();
+
+ log.trace("Calling the backend");
+ final CloseableHttpResponse backendResponse = backend.execute(route, request, context, execAware);
+ try {
+ backendResponse.addHeader("Via", generateViaHeader(backendResponse));
+ return handleBackendResponse(route, request, context, execAware,
+ requestDate, getCurrentDate(), backendResponse);
+ } catch (final IOException ex) {
+ backendResponse.close();
+ throw ex;
+ } catch (final RuntimeException ex) {
+ backendResponse.close();
+ throw ex;
+ }
+ }
+
+ private boolean revalidationResponseIsTooOld(final HttpResponse backendResponse,
+ final HttpCacheEntry cacheEntry) {
+ final Header entryDateHeader = cacheEntry.getFirstHeader(HTTP.DATE_HEADER);
+ final Header responseDateHeader = backendResponse.getFirstHeader(HTTP.DATE_HEADER);
+ if (entryDateHeader != null && responseDateHeader != null) {
+ final Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
+ final Date respDate = DateUtils.parseDate(responseDateHeader.getValue());
+ if (entryDate == null || respDate == null) {
+ // either backend response or cached entry did not have a valid
+ // Date header, so we can't tell if they are out of order
+ // according to the origin clock; thus we can skip the
+ // unconditional retry recommended in 13.2.6 of RFC 2616.
+ return false;
+ }
+ if (respDate.before(entryDate)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ CloseableHttpResponse negotiateResponseFromVariants(
+ final HttpRoute route,
+ final HttpRequestWrapper request,
+ final HttpClientContext context,
+ final HttpExecutionAware execAware,
+ final Map variants) throws IOException, HttpException {
+ final HttpRequestWrapper conditionalRequest = conditionalRequestBuilder
+ .buildConditionalRequestFromVariants(request, variants);
+
+ final Date requestDate = getCurrentDate();
+ final CloseableHttpResponse backendResponse = backend.execute(
+ route, conditionalRequest, context, execAware);
+ try {
+ final Date responseDate = getCurrentDate();
+
+ backendResponse.addHeader("Via", generateViaHeader(backendResponse));
+
+ if (backendResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_MODIFIED) {
+ return handleBackendResponse(
+ route, request, context, execAware,
+ requestDate, responseDate, backendResponse);
+ }
+
+ final Header resultEtagHeader = backendResponse.getFirstHeader(HeaderConstants.ETAG);
+ if (resultEtagHeader == null) {
+ log.warn("304 response did not contain ETag");
+ IOUtils.consume(backendResponse.getEntity());
+ backendResponse.close();
+ return callBackend(route, request, context, execAware);
+ }
+
+ final String resultEtag = resultEtagHeader.getValue();
+ final Variant matchingVariant = variants.get(resultEtag);
+ if (matchingVariant == null) {
+ log.debug("304 response did not contain ETag matching one sent in If-None-Match");
+ IOUtils.consume(backendResponse.getEntity());
+ backendResponse.close();
+ return callBackend(route, request, context, execAware);
+ }
+
+ final HttpCacheEntry matchedEntry = matchingVariant.getEntry();
+
+ if (revalidationResponseIsTooOld(backendResponse, matchedEntry)) {
+ IOUtils.consume(backendResponse.getEntity());
+ backendResponse.close();
+ return retryRequestUnconditionally(route, request, context, execAware, matchedEntry);
+ }
+
+ recordCacheUpdate(context);
+
+ final HttpCacheEntry responseEntry = getUpdatedVariantEntry(
+ context.getTargetHost(), conditionalRequest, requestDate, responseDate,
+ backendResponse, matchingVariant, matchedEntry);
+ backendResponse.close();
+
+ final CloseableHttpResponse resp = responseGenerator.generateResponse(responseEntry);
+ tryToUpdateVariantMap(context.getTargetHost(), request, matchingVariant);
+
+ if (shouldSendNotModifiedResponse(request, responseEntry)) {
+ return responseGenerator.generateNotModifiedResponse(responseEntry);
+ }
+ return resp;
+ } catch (final IOException ex) {
+ backendResponse.close();
+ throw ex;
+ } catch (final RuntimeException ex) {
+ backendResponse.close();
+ throw ex;
+ }
+ }
+
+ private CloseableHttpResponse retryRequestUnconditionally(
+ final HttpRoute route,
+ final HttpRequestWrapper request,
+ final HttpClientContext context,
+ final HttpExecutionAware execAware,
+ final HttpCacheEntry matchedEntry) throws IOException, HttpException {
+ final HttpRequestWrapper unconditional = conditionalRequestBuilder
+ .buildUnconditionalRequest(request, matchedEntry);
+ return callBackend(route, unconditional, context, execAware);
+ }
+
+ private HttpCacheEntry getUpdatedVariantEntry(
+ final HttpHost target,
+ final HttpRequestWrapper conditionalRequest,
+ final Date requestDate,
+ final Date responseDate,
+ final CloseableHttpResponse backendResponse,
+ final Variant matchingVariant,
+ final HttpCacheEntry matchedEntry) throws IOException {
+ HttpCacheEntry responseEntry = matchedEntry;
+ try {
+ responseEntry = responseCache.updateVariantCacheEntry(target, conditionalRequest,
+ matchedEntry, backendResponse, requestDate, responseDate, matchingVariant.getCacheKey());
+ } catch (final IOException ioe) {
+ log.warn("Could not update cache entry", ioe);
+ } finally {
+ backendResponse.close();
+ }
+ return responseEntry;
+ }
+
+ private void tryToUpdateVariantMap(
+ final HttpHost target,
+ final HttpRequestWrapper request,
+ final Variant matchingVariant) {
+ try {
+ responseCache.reuseVariantEntryFor(target, request, matchingVariant);
+ } catch (final IOException ioe) {
+ log.warn("Could not update cache entry to reuse variant", ioe);
+ }
+ }
+
+ private boolean shouldSendNotModifiedResponse(
+ final HttpRequestWrapper request,
+ final HttpCacheEntry responseEntry) {
+ return (suitabilityChecker.isConditional(request)
+ && suitabilityChecker.allConditionalsMatch(request, responseEntry, new Date()));
+ }
+
+ CloseableHttpResponse revalidateCacheEntry(
+ final HttpRoute route,
+ final HttpRequestWrapper request,
+ final HttpClientContext context,
+ final HttpExecutionAware execAware,
+ final HttpCacheEntry cacheEntry) throws IOException, HttpException {
+
+ final HttpRequestWrapper conditionalRequest = conditionalRequestBuilder.buildConditionalRequest(request, cacheEntry);
+
+ Date requestDate = getCurrentDate();
+ CloseableHttpResponse backendResponse = backend.execute(
+ route, conditionalRequest, context, execAware);
+ Date responseDate = getCurrentDate();
+
+ if (revalidationResponseIsTooOld(backendResponse, cacheEntry)) {
+ backendResponse.close();
+ final HttpRequestWrapper unconditional = conditionalRequestBuilder
+ .buildUnconditionalRequest(request, cacheEntry);
+ requestDate = getCurrentDate();
+ backendResponse = backend.execute(route, unconditional, context, execAware);
+ responseDate = getCurrentDate();
+ }
+
+ backendResponse.addHeader(HeaderConstants.VIA, generateViaHeader(backendResponse));
+
+ final int statusCode = backendResponse.getStatusLine().getStatusCode();
+ if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_OK) {
+ recordCacheUpdate(context);
+ }
+
+ if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
+ final HttpCacheEntry updatedEntry = responseCache.updateCacheEntry(
+ context.getTargetHost(), request, cacheEntry,
+ backendResponse, requestDate, responseDate);
+ if (suitabilityChecker.isConditional(request)
+ && suitabilityChecker.allConditionalsMatch(request, updatedEntry, new Date())) {
+ return responseGenerator
+ .generateNotModifiedResponse(updatedEntry);
+ }
+ return responseGenerator.generateResponse(updatedEntry);
+ }
+
+ if (staleIfErrorAppliesTo(statusCode)
+ && !staleResponseNotAllowed(request, cacheEntry, getCurrentDate())
+ && validityPolicy.mayReturnStaleIfError(request, cacheEntry, responseDate)) {
+ try {
+ final CloseableHttpResponse cachedResponse = responseGenerator.generateResponse(cacheEntry);
+ cachedResponse.addHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\"");
+ return cachedResponse;
+ } finally {
+ backendResponse.close();
+ }
+ }
+ return handleBackendResponse(
+ route, conditionalRequest, context, execAware,
+ requestDate, responseDate, backendResponse);
+ }
+
+ private boolean staleIfErrorAppliesTo(final int statusCode) {
+ return statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR
+ || statusCode == HttpStatus.SC_BAD_GATEWAY
+ || statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE
+ || statusCode == HttpStatus.SC_GATEWAY_TIMEOUT;
+ }
+
+ CloseableHttpResponse handleBackendResponse(
+ final HttpRoute route,
+ final HttpRequestWrapper request,
+ final HttpClientContext context,
+ final HttpExecutionAware execAware,
+ final Date requestDate,
+ final Date responseDate,
+ final CloseableHttpResponse backendResponse) throws IOException {
+
+ log.trace("Handling Backend response");
+ responseCompliance.ensureProtocolCompliance(request, backendResponse);
+
+ final HttpHost target = context.getTargetHost();
+ final boolean cacheable = responseCachingPolicy.isResponseCacheable(request, backendResponse);
+ responseCache.flushInvalidatedCacheEntriesFor(target, request, backendResponse);
+ if (cacheable && !alreadyHaveNewerCacheEntry(target, request, backendResponse)) {
+ storeRequestIfModifiedSinceFor304Response(request, backendResponse);
+ return responseCache.cacheAndReturnResponse(target, request,
+ backendResponse, requestDate, responseDate);
+ }
+ if (!cacheable) {
+ try {
+ responseCache.flushCacheEntriesFor(target, request);
+ } catch (final IOException ioe) {
+ log.warn("Unable to flush invalid cache entries", ioe);
+ }
+ }
+ return backendResponse;
+ }
+
+ /**
+ * For 304 Not modified responses, adds a "Last-Modified" header with the
+ * value of the "If-Modified-Since" header passed in the request. This
+ * header is required to be able to reuse match the cache entry for
+ * subsequent requests but as defined in http specifications it is not
+ * included in 304 responses by backend servers. This header will not be
+ * included in the resulting response.
+ */
+ private void storeRequestIfModifiedSinceFor304Response(
+ final HttpRequest request, final HttpResponse backendResponse) {
+ if (backendResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
+ final Header h = request.getFirstHeader("If-Modified-Since");
+ if (h != null) {
+ backendResponse.addHeader("Last-Modified", h.getValue());
+ }
+ }
+ }
+
+ private boolean alreadyHaveNewerCacheEntry(final HttpHost target, final HttpRequestWrapper request,
+ final HttpResponse backendResponse) {
+ HttpCacheEntry existing = null;
+ try {
+ existing = responseCache.getCacheEntry(target, request);
+ } catch (final IOException ioe) {
+ // nop
+ }
+ if (existing == null) {
+ return false;
+ }
+ final Header entryDateHeader = existing.getFirstHeader(HTTP.DATE_HEADER);
+ if (entryDateHeader == null) {
+ return false;
+ }
+ final Header responseDateHeader = backendResponse.getFirstHeader(HTTP.DATE_HEADER);
+ if (responseDateHeader == null) {
+ return false;
+ }
+ final Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
+ final Date responseDate = DateUtils.parseDate(responseDateHeader.getValue());
+ if (entryDate == null || responseDate == null) {
+ return false;
+ }
+ return responseDate.before(entryDate);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CachingHttpClientBuilder.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CachingHttpClientBuilder.java
new file mode 100644
index 000000000..385324f32
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CachingHttpClientBuilder.java
@@ -0,0 +1,149 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.File;
+
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheInvalidator;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheStorage;
+import ch.boye.httpclientandroidlib.client.cache.ResourceFactory;
+import ch.boye.httpclientandroidlib.impl.client.HttpClientBuilder;
+import ch.boye.httpclientandroidlib.impl.execchain.ClientExecChain;
+
+/**
+ * Builder for {@link ch.boye.httpclientandroidlib.impl.client.CloseableHttpClient}
+ * instances capable of client-side caching.
+ *
+ * @since 4.3
+ */
+public class CachingHttpClientBuilder extends HttpClientBuilder {
+
+ private ResourceFactory resourceFactory;
+ private HttpCacheStorage storage;
+ private File cacheDir;
+ private CacheConfig cacheConfig;
+ private SchedulingStrategy schedulingStrategy;
+ private HttpCacheInvalidator httpCacheInvalidator;
+
+ public static CachingHttpClientBuilder create() {
+ return new CachingHttpClientBuilder();
+ }
+
+ protected CachingHttpClientBuilder() {
+ super();
+ }
+
+ public final CachingHttpClientBuilder setResourceFactory(
+ final ResourceFactory resourceFactory) {
+ this.resourceFactory = resourceFactory;
+ return this;
+ }
+
+ public final CachingHttpClientBuilder setHttpCacheStorage(
+ final HttpCacheStorage storage) {
+ this.storage = storage;
+ return this;
+ }
+
+ public final CachingHttpClientBuilder setCacheDir(
+ final File cacheDir) {
+ this.cacheDir = cacheDir;
+ return this;
+ }
+
+ public final CachingHttpClientBuilder setCacheConfig(
+ final CacheConfig cacheConfig) {
+ this.cacheConfig = cacheConfig;
+ return this;
+ }
+
+ public final CachingHttpClientBuilder setSchedulingStrategy(
+ final SchedulingStrategy schedulingStrategy) {
+ this.schedulingStrategy = schedulingStrategy;
+ return this;
+ }
+
+ public final CachingHttpClientBuilder setHttpCacheInvalidator(
+ final HttpCacheInvalidator cacheInvalidator) {
+ this.httpCacheInvalidator = cacheInvalidator;
+ return this;
+ }
+
+ @Override
+ protected ClientExecChain decorateMainExec(final ClientExecChain mainExec) {
+ final CacheConfig config = this.cacheConfig != null ? this.cacheConfig : CacheConfig.DEFAULT;
+ ResourceFactory resourceFactory = this.resourceFactory;
+ if (resourceFactory == null) {
+ if (this.cacheDir == null) {
+ resourceFactory = new HeapResourceFactory();
+ } else {
+ resourceFactory = new FileResourceFactory(cacheDir);
+ }
+ }
+ HttpCacheStorage storage = this.storage;
+ if (storage == null) {
+ if (this.cacheDir == null) {
+ storage = new BasicHttpCacheStorage(config);
+ } else {
+ final ManagedHttpCacheStorage managedStorage = new ManagedHttpCacheStorage(config);
+ addCloseable(managedStorage);
+ storage = managedStorage;
+ }
+ }
+ final AsynchronousValidator revalidator = createAsynchronousRevalidator(config);
+ final CacheKeyGenerator uriExtractor = new CacheKeyGenerator();
+
+ HttpCacheInvalidator cacheInvalidator = this.httpCacheInvalidator;
+ if (cacheInvalidator == null) {
+ cacheInvalidator = new CacheInvalidator(uriExtractor, storage);
+ }
+
+ return new CachingExec(mainExec,
+ new BasicHttpCache(
+ resourceFactory,
+ storage, config,
+ uriExtractor,
+ cacheInvalidator), config, revalidator);
+ }
+
+ private AsynchronousValidator createAsynchronousRevalidator(final CacheConfig config) {
+ if (config.getAsynchronousWorkersMax() > 0) {
+ final SchedulingStrategy configuredSchedulingStrategy = createSchedulingStrategy(config);
+ final AsynchronousValidator revalidator = new AsynchronousValidator(
+ configuredSchedulingStrategy);
+ addCloseable(revalidator);
+ return revalidator;
+ }
+ return null;
+ }
+
+ @SuppressWarnings("resource")
+ private SchedulingStrategy createSchedulingStrategy(final CacheConfig config) {
+ return schedulingStrategy != null ? schedulingStrategy : new ImmediateSchedulingStrategy(config);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CachingHttpClients.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CachingHttpClients.java
new file mode 100644
index 000000000..328c147f3
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CachingHttpClients.java
@@ -0,0 +1,74 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.File;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.impl.client.CloseableHttpClient;
+
+/**
+ * Factory methods for {@link CloseableHttpClient} instances
+ * capable of client-side caching.
+ *
+ * @since 4.3
+ */
+@Immutable
+public class CachingHttpClients {
+
+ private CachingHttpClients() {
+ super();
+ }
+
+ /**
+ * Creates builder object for construction of custom
+ * {@link CloseableHttpClient} instances.
+ */
+ public static CachingHttpClientBuilder custom() {
+ return CachingHttpClientBuilder.create();
+ }
+
+ /**
+ * Creates {@link CloseableHttpClient} instance that uses a memory bound
+ * response cache.
+ */
+ public static CloseableHttpClient createMemoryBound() {
+ return CachingHttpClientBuilder.create().build();
+ }
+
+ /**
+ * Creates {@link CloseableHttpClient} instance that uses a file system
+ * bound response cache.
+ *
+ * @param cacheDir location of response cache.
+ */
+ public static CloseableHttpClient createFileBound(final File cacheDir) {
+ return CachingHttpClientBuilder.create().setCacheDir(cacheDir).build();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CombinedEntity.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CombinedEntity.java
new file mode 100644
index 000000000..62bfaff3e
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/CombinedEntity.java
@@ -0,0 +1,104 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.SequenceInputStream;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.client.cache.Resource;
+import ch.boye.httpclientandroidlib.entity.AbstractHttpEntity;
+import ch.boye.httpclientandroidlib.util.Args;
+
+@NotThreadSafe
+class CombinedEntity extends AbstractHttpEntity {
+
+ private final Resource resource;
+ private final InputStream combinedStream;
+
+ CombinedEntity(final Resource resource, final InputStream instream) throws IOException {
+ super();
+ this.resource = resource;
+ this.combinedStream = new SequenceInputStream(
+ new ResourceStream(resource.getInputStream()), instream);
+ }
+
+ public long getContentLength() {
+ return -1;
+ }
+
+ public boolean isRepeatable() {
+ return false;
+ }
+
+ public boolean isStreaming() {
+ return true;
+ }
+
+ public InputStream getContent() throws IOException, IllegalStateException {
+ return this.combinedStream;
+ }
+
+ public void writeTo(final OutputStream outstream) throws IOException {
+ Args.notNull(outstream, "Output stream");
+ final InputStream instream = getContent();
+ try {
+ int l;
+ final byte[] tmp = new byte[2048];
+ while ((l = instream.read(tmp)) != -1) {
+ outstream.write(tmp, 0, l);
+ }
+ } finally {
+ instream.close();
+ }
+ }
+
+ private void dispose() {
+ this.resource.dispose();
+ }
+
+ class ResourceStream extends FilterInputStream {
+
+ protected ResourceStream(final InputStream in) {
+ super(in);
+ }
+
+ @Override
+ public void close() throws IOException {
+ try {
+ super.close();
+ } finally {
+ dispose();
+ }
+ }
+
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ConditionalRequestBuilder.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ConditionalRequestBuilder.java
new file mode 100644
index 000000000..0edc4fb85
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ConditionalRequestBuilder.java
@@ -0,0 +1,140 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.util.Map;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HeaderElement;
+import ch.boye.httpclientandroidlib.ProtocolException;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.cache.HeaderConstants;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.client.methods.HttpRequestWrapper;
+
+/**
+ * @since 4.1
+ */
+@Immutable
+class ConditionalRequestBuilder {
+
+ /**
+ * When a {@link HttpCacheEntry} is stale but 'might' be used as a response
+ * to an {@link ch.boye.httpclientandroidlib.HttpRequest} we will attempt to revalidate
+ * the entry with the origin. Build the origin {@link ch.boye.httpclientandroidlib.HttpRequest}
+ * here and return it.
+ *
+ * @param request the original request from the caller
+ * @param cacheEntry the entry that needs to be re-validated
+ * @return the wrapped request
+ * @throws ProtocolException when I am unable to build a new origin request.
+ */
+ public HttpRequestWrapper buildConditionalRequest(final HttpRequestWrapper request, final HttpCacheEntry cacheEntry)
+ throws ProtocolException {
+ final HttpRequestWrapper newRequest = HttpRequestWrapper.wrap(request.getOriginal());
+ newRequest.setHeaders(request.getAllHeaders());
+ final Header eTag = cacheEntry.getFirstHeader(HeaderConstants.ETAG);
+ if (eTag != null) {
+ newRequest.setHeader(HeaderConstants.IF_NONE_MATCH, eTag.getValue());
+ }
+ final Header lastModified = cacheEntry.getFirstHeader(HeaderConstants.LAST_MODIFIED);
+ if (lastModified != null) {
+ newRequest.setHeader(HeaderConstants.IF_MODIFIED_SINCE, lastModified.getValue());
+ }
+ boolean mustRevalidate = false;
+ for(final Header h : cacheEntry.getHeaders(HeaderConstants.CACHE_CONTROL)) {
+ for(final HeaderElement elt : h.getElements()) {
+ if (HeaderConstants.CACHE_CONTROL_MUST_REVALIDATE.equalsIgnoreCase(elt.getName())
+ || HeaderConstants.CACHE_CONTROL_PROXY_REVALIDATE.equalsIgnoreCase(elt.getName())) {
+ mustRevalidate = true;
+ break;
+ }
+ }
+ }
+ if (mustRevalidate) {
+ newRequest.addHeader(HeaderConstants.CACHE_CONTROL, HeaderConstants.CACHE_CONTROL_MAX_AGE + "=0");
+ }
+ return newRequest;
+
+ }
+
+ /**
+ * When a {@link HttpCacheEntry} does not exist for a specific
+ * {@link ch.boye.httpclientandroidlib.HttpRequest} we attempt to see if an existing
+ * {@link HttpCacheEntry} is appropriate by building a conditional
+ * {@link ch.boye.httpclientandroidlib.HttpRequest} using the variants' ETag values.
+ * If no such values exist, the request is unmodified
+ *
+ * @param request the original request from the caller
+ * @param variants
+ * @return the wrapped request
+ */
+ public HttpRequestWrapper buildConditionalRequestFromVariants(final HttpRequestWrapper request,
+ final Map variants) {
+ final HttpRequestWrapper newRequest = HttpRequestWrapper.wrap(request.getOriginal());
+ newRequest.setHeaders(request.getAllHeaders());
+
+ // we do not support partial content so all etags are used
+ final StringBuilder etags = new StringBuilder();
+ boolean first = true;
+ for(final String etag : variants.keySet()) {
+ if (!first) {
+ etags.append(",");
+ }
+ first = false;
+ etags.append(etag);
+ }
+
+ newRequest.setHeader(HeaderConstants.IF_NONE_MATCH, etags.toString());
+ return newRequest;
+ }
+
+ /**
+ * Returns a request to unconditionally validate a cache entry with
+ * the origin. In certain cases (due to multiple intervening caches)
+ * our cache may actually receive a response to a normal conditional
+ * validation where the Date header is actually older than that of
+ * our current cache entry. In this case, the protocol recommendation
+ * is to retry the validation and force syncup with the origin.
+ * @param request client request we are trying to satisfy
+ * @param entry existing cache entry we are trying to validate
+ * @return an unconditional validation request
+ */
+ public HttpRequestWrapper buildUnconditionalRequest(final HttpRequestWrapper request, final HttpCacheEntry entry) {
+ final HttpRequestWrapper newRequest = HttpRequestWrapper.wrap(request.getOriginal());
+ newRequest.setHeaders(request.getAllHeaders());
+ newRequest.addHeader(HeaderConstants.CACHE_CONTROL,HeaderConstants.CACHE_CONTROL_NO_CACHE);
+ newRequest.addHeader(HeaderConstants.PRAGMA,HeaderConstants.CACHE_CONTROL_NO_CACHE);
+ newRequest.removeHeaders(HeaderConstants.IF_RANGE);
+ newRequest.removeHeaders(HeaderConstants.IF_MATCH);
+ newRequest.removeHeaders(HeaderConstants.IF_NONE_MATCH);
+ newRequest.removeHeaders(HeaderConstants.IF_UNMODIFIED_SINCE);
+ newRequest.removeHeaders(HeaderConstants.IF_MODIFIED_SINCE);
+ return newRequest;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/DefaultFailureCache.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/DefaultFailureCache.java
new file mode 100644
index 000000000..3646c3c32
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/DefaultFailureCache.java
@@ -0,0 +1,143 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+/**
+ * Implements a bounded failure cache. The oldest entries are discarded when
+ * the maximum size is exceeded.
+ *
+ * @since 4.3
+ */
+@ThreadSafe
+public class DefaultFailureCache implements FailureCache {
+
+ static final int DEFAULT_MAX_SIZE = 1000;
+ static final int MAX_UPDATE_TRIES = 10;
+
+ private final int maxSize;
+ private final ConcurrentMap storage;
+
+ /**
+ * Create a new failure cache with the maximum size of
+ * {@link #DEFAULT_MAX_SIZE}.
+ */
+ public DefaultFailureCache() {
+ this(DEFAULT_MAX_SIZE);
+ }
+
+ /**
+ * Creates a new failure cache with the specified maximum size.
+ * @param maxSize the maximum number of entries the cache should store
+ */
+ public DefaultFailureCache(final int maxSize) {
+ this.maxSize = maxSize;
+ this.storage = new ConcurrentHashMap();
+ }
+
+ public int getErrorCount(final String identifier) {
+ if (identifier == null) {
+ throw new IllegalArgumentException("identifier may not be null");
+ }
+ final FailureCacheValue storedErrorCode = storage.get(identifier);
+ return storedErrorCode != null ? storedErrorCode.getErrorCount() : 0;
+ }
+
+ public void resetErrorCount(final String identifier) {
+ if (identifier == null) {
+ throw new IllegalArgumentException("identifier may not be null");
+ }
+ storage.remove(identifier);
+ }
+
+ public void increaseErrorCount(final String identifier) {
+ if (identifier == null) {
+ throw new IllegalArgumentException("identifier may not be null");
+ }
+ updateValue(identifier);
+ removeOldestEntryIfMapSizeExceeded();
+ }
+
+ private void updateValue(final String identifier) {
+ /**
+ * Due to concurrency it is possible that someone else is modifying an
+ * entry before we could write back our updated value. So we keep
+ * trying until it is our turn.
+ *
+ * In case there is a lot of contention on that identifier, a thread
+ * might starve. Thus it gives up after a certain number of failed
+ * update tries.
+ */
+ for (int i = 0; i < MAX_UPDATE_TRIES; i++) {
+ final FailureCacheValue oldValue = storage.get(identifier);
+ if (oldValue == null) {
+ final FailureCacheValue newValue = new FailureCacheValue(identifier, 1);
+ if (storage.putIfAbsent(identifier, newValue) == null) {
+ return;
+ }
+ }
+ else {
+ final int errorCount = oldValue.getErrorCount();
+ if (errorCount == Integer.MAX_VALUE) {
+ return;
+ }
+ final FailureCacheValue newValue = new FailureCacheValue(identifier, errorCount + 1);
+ if (storage.replace(identifier, oldValue, newValue)) {
+ return;
+ }
+ }
+ }
+ }
+
+ private void removeOldestEntryIfMapSizeExceeded() {
+ if (storage.size() > maxSize) {
+ final FailureCacheValue valueWithOldestTimestamp = findValueWithOldestTimestamp();
+ if (valueWithOldestTimestamp != null) {
+ storage.remove(valueWithOldestTimestamp.getKey(), valueWithOldestTimestamp);
+ }
+ }
+ }
+
+ private FailureCacheValue findValueWithOldestTimestamp() {
+ long oldestTimestamp = Long.MAX_VALUE;
+ FailureCacheValue oldestValue = null;
+ for (final Map.Entry storageEntry : storage.entrySet()) {
+ final FailureCacheValue value = storageEntry.getValue();
+ final long creationTimeInNanos = value.getCreationTimeInNanos();
+ if (creationTimeInNanos < oldestTimestamp) {
+ oldestTimestamp = creationTimeInNanos;
+ oldestValue = storageEntry.getValue();
+ }
+ }
+ return oldestValue;
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/DefaultHttpCacheEntrySerializer.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/DefaultHttpCacheEntrySerializer.java
new file mode 100644
index 000000000..0d78a2eb1
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/DefaultHttpCacheEntrySerializer.java
@@ -0,0 +1,71 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntrySerializationException;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntrySerializer;
+
+/**
+ * {@link HttpCacheEntrySerializer} implementation that uses the default (native)
+ * serialization.
+ *
+ * @see java.io.Serializable
+ *
+ * @since 4.1
+ */
+@Immutable
+public class DefaultHttpCacheEntrySerializer implements HttpCacheEntrySerializer {
+
+ public void writeTo(final HttpCacheEntry cacheEntry, final OutputStream os) throws IOException {
+ final ObjectOutputStream oos = new ObjectOutputStream(os);
+ try {
+ oos.writeObject(cacheEntry);
+ } finally {
+ oos.close();
+ }
+ }
+
+ public HttpCacheEntry readFrom(final InputStream is) throws IOException {
+ final ObjectInputStream ois = new ObjectInputStream(is);
+ try {
+ return (HttpCacheEntry) ois.readObject();
+ } catch (final ClassNotFoundException ex) {
+ throw new HttpCacheEntrySerializationException("Class not found: " + ex.getMessage(), ex);
+ } finally {
+ ois.close();
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ExponentialBackOffSchedulingStrategy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ExponentialBackOffSchedulingStrategy.java
new file mode 100644
index 000000000..286205583
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ExponentialBackOffSchedulingStrategy.java
@@ -0,0 +1,174 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * An implementation that backs off exponentially based on the number of
+ * consecutive failed attempts stored in the
+ * {@link AsynchronousValidationRequest}. It uses the following defaults:
+ *
+ * no delay in case it was never tried or didn't fail so far
+ * 6 secs delay for one failed attempt (= {@link #getInitialExpiryInMillis()})
+ * 60 secs delay for two failed attempts
+ * 10 mins delay for three failed attempts
+ * 100 mins delay for four failed attempts
+ * ~16 hours delay for five failed attempts
+ * 24 hours delay for six or more failed attempts (= {@link #getMaxExpiryInMillis()})
+ *
+ *
+ * The following equation is used to calculate the delay for a specific revalidation request:
+ *
+ * The resulting delay won't exceed {@link #getMaxExpiryInMillis()}.
+ *
+ * @since 4.3
+ */
+@ThreadSafe
+public class ExponentialBackOffSchedulingStrategy implements SchedulingStrategy {
+
+ public static final long DEFAULT_BACK_OFF_RATE = 10;
+ public static final long DEFAULT_INITIAL_EXPIRY_IN_MILLIS = TimeUnit.SECONDS.toMillis(6);
+ public static final long DEFAULT_MAX_EXPIRY_IN_MILLIS = TimeUnit.SECONDS.toMillis(86400);
+
+ private final long backOffRate;
+ private final long initialExpiryInMillis;
+ private final long maxExpiryInMillis;
+
+ private final ScheduledExecutorService executor;
+
+ /**
+ * Create a new scheduling strategy using a fixed pool of worker threads.
+ * @param cacheConfig the thread pool configuration to be used; not null
+ * @see ch.boye.httpclientandroidlib.impl.client.cache.CacheConfig#getAsynchronousWorkersMax()
+ * @see #DEFAULT_BACK_OFF_RATE
+ * @see #DEFAULT_INITIAL_EXPIRY_IN_MILLIS
+ * @see #DEFAULT_MAX_EXPIRY_IN_MILLIS
+ */
+ public ExponentialBackOffSchedulingStrategy(final CacheConfig cacheConfig) {
+ this(cacheConfig,
+ DEFAULT_BACK_OFF_RATE,
+ DEFAULT_INITIAL_EXPIRY_IN_MILLIS,
+ DEFAULT_MAX_EXPIRY_IN_MILLIS);
+ }
+
+ /**
+ * Create a new scheduling strategy by using a fixed pool of worker threads and the
+ * given parameters to calculated the delay.
+ *
+ * @param cacheConfig the thread pool configuration to be used; not null
+ * @param backOffRate the back off rate to be used; not negative
+ * @param initialExpiryInMillis the initial expiry in milli seconds; not negative
+ * @param maxExpiryInMillis the upper limit of the delay in milli seconds; not negative
+ * @see ch.boye.httpclientandroidlib.impl.client.cache.CacheConfig#getAsynchronousWorkersMax()
+ * @see ExponentialBackOffSchedulingStrategy
+ */
+ public ExponentialBackOffSchedulingStrategy(
+ final CacheConfig cacheConfig,
+ final long backOffRate,
+ final long initialExpiryInMillis,
+ final long maxExpiryInMillis) {
+ this(createThreadPoolFromCacheConfig(cacheConfig),
+ backOffRate,
+ initialExpiryInMillis,
+ maxExpiryInMillis);
+ }
+
+ private static ScheduledThreadPoolExecutor createThreadPoolFromCacheConfig(
+ final CacheConfig cacheConfig) {
+ final ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(
+ cacheConfig.getAsynchronousWorkersMax());
+ scheduledThreadPoolExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
+ return scheduledThreadPoolExecutor;
+ }
+
+ ExponentialBackOffSchedulingStrategy(
+ final ScheduledExecutorService executor,
+ final long backOffRate,
+ final long initialExpiryInMillis,
+ final long maxExpiryInMillis) {
+ this.executor = checkNotNull("executor", executor);
+ this.backOffRate = checkNotNegative("backOffRate", backOffRate);
+ this.initialExpiryInMillis = checkNotNegative("initialExpiryInMillis", initialExpiryInMillis);
+ this.maxExpiryInMillis = checkNotNegative("maxExpiryInMillis", maxExpiryInMillis);
+ }
+
+ public void schedule(
+ final AsynchronousValidationRequest revalidationRequest) {
+ checkNotNull("revalidationRequest", revalidationRequest);
+ final int consecutiveFailedAttempts = revalidationRequest.getConsecutiveFailedAttempts();
+ final long delayInMillis = calculateDelayInMillis(consecutiveFailedAttempts);
+ executor.schedule(revalidationRequest, delayInMillis, TimeUnit.MILLISECONDS);
+ }
+
+ public void close() {
+ executor.shutdown();
+ }
+
+ public long getBackOffRate() {
+ return backOffRate;
+ }
+
+ public long getInitialExpiryInMillis() {
+ return initialExpiryInMillis;
+ }
+
+ public long getMaxExpiryInMillis() {
+ return maxExpiryInMillis;
+ }
+
+ protected long calculateDelayInMillis(final int consecutiveFailedAttempts) {
+ if (consecutiveFailedAttempts > 0) {
+ final long delayInSeconds = (long) (initialExpiryInMillis *
+ Math.pow(backOffRate, consecutiveFailedAttempts - 1));
+ return Math.min(delayInSeconds, maxExpiryInMillis);
+ }
+ else {
+ return 0;
+ }
+ }
+
+ protected static T checkNotNull(final String parameterName, final T value) {
+ if (value == null) {
+ throw new IllegalArgumentException(parameterName + " may not be null");
+ }
+ return value;
+ }
+
+ protected static long checkNotNegative(final String parameterName, final long value) {
+ if (value < 0) {
+ throw new IllegalArgumentException(parameterName + " may not be negative");
+ }
+ return value;
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/FailureCache.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/FailureCache.java
new file mode 100644
index 000000000..a30fc54d9
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/FailureCache.java
@@ -0,0 +1,57 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+/**
+ * Increase and reset the number of errors associated with a specific
+ * identifier.
+ *
+ * @since 4.3
+ */
+public interface FailureCache {
+
+ /**
+ * Get the current error count.
+ * @param identifier the identifier for which the error count is requested
+ * @return the currently known error count or zero if there is no record
+ */
+ int getErrorCount(String identifier);
+
+ /**
+ * Reset the error count back to zero.
+ * @param identifier the identifier for which the error count should be
+ * reset
+ */
+ void resetErrorCount(String identifier);
+
+ /**
+ * Increases the error count by one.
+ * @param identifier the identifier for which the error count should be
+ * increased
+ */
+ void increaseErrorCount(String identifier);
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/FailureCacheValue.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/FailureCacheValue.java
new file mode 100644
index 000000000..48bbf55fc
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/FailureCacheValue.java
@@ -0,0 +1,67 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+
+/**
+ * The error count with a creation timestamp and its associated key.
+ *
+ * @since 4.3
+ */
+@Immutable
+public class FailureCacheValue {
+
+ private final long creationTimeInNanos;
+ private final String key;
+ private final int errorCount;
+
+ public FailureCacheValue(final String key, final int errorCount) {
+ this.creationTimeInNanos = System.nanoTime();
+ this.key = key;
+ this.errorCount = errorCount;
+ }
+
+ public long getCreationTimeInNanos() {
+ return creationTimeInNanos;
+ }
+
+ public String getKey()
+ {
+ return key;
+ }
+
+ public int getErrorCount() {
+ return errorCount;
+ }
+
+ @Override
+ public String toString() {
+ return "[entry creationTimeInNanos=" + creationTimeInNanos + "; " +
+ "key=" + key + "; errorCount=" + errorCount + ']';
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/FileResource.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/FileResource.java
new file mode 100644
index 000000000..934ecd13d
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/FileResource.java
@@ -0,0 +1,77 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.client.cache.Resource;
+
+/**
+ * Cache resource backed by a file.
+ *
+ * @since 4.1
+ */
+@ThreadSafe
+public class FileResource implements Resource {
+
+ private static final long serialVersionUID = 4132244415919043397L;
+
+ private final File file;
+
+ private volatile boolean disposed;
+
+ public FileResource(final File file) {
+ super();
+ this.file = file;
+ this.disposed = false;
+ }
+
+ synchronized File getFile() {
+ return this.file;
+ }
+
+ public synchronized InputStream getInputStream() throws IOException {
+ return new FileInputStream(this.file);
+ }
+
+ public synchronized long length() {
+ return this.file.length();
+ }
+
+ public synchronized void dispose() {
+ if (this.disposed) {
+ return;
+ }
+ this.disposed = true;
+ this.file.delete();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/FileResourceFactory.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/FileResourceFactory.java
new file mode 100644
index 000000000..8522c54b5
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/FileResourceFactory.java
@@ -0,0 +1,111 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.cache.InputLimit;
+import ch.boye.httpclientandroidlib.client.cache.Resource;
+import ch.boye.httpclientandroidlib.client.cache.ResourceFactory;
+
+/**
+ * Generates {@link Resource} instances whose body is stored in a temporary file.
+ *
+ * @since 4.1
+ */
+@Immutable
+public class FileResourceFactory implements ResourceFactory {
+
+ private final File cacheDir;
+ private final BasicIdGenerator idgen;
+
+ public FileResourceFactory(final File cacheDir) {
+ super();
+ this.cacheDir = cacheDir;
+ this.idgen = new BasicIdGenerator();
+ }
+
+ private File generateUniqueCacheFile(final String requestId) {
+ final StringBuilder buffer = new StringBuilder();
+ this.idgen.generate(buffer);
+ buffer.append('.');
+ final int len = Math.min(requestId.length(), 100);
+ for (int i = 0; i < len; i++) {
+ final char ch = requestId.charAt(i);
+ if (Character.isLetterOrDigit(ch) || ch == '.') {
+ buffer.append(ch);
+ } else {
+ buffer.append('-');
+ }
+ }
+ return new File(this.cacheDir, buffer.toString());
+ }
+
+ public Resource generate(
+ final String requestId,
+ final InputStream instream,
+ final InputLimit limit) throws IOException {
+ final File file = generateUniqueCacheFile(requestId);
+ final FileOutputStream outstream = new FileOutputStream(file);
+ try {
+ final byte[] buf = new byte[2048];
+ long total = 0;
+ int l;
+ while ((l = instream.read(buf)) != -1) {
+ outstream.write(buf, 0, l);
+ total += l;
+ if (limit != null && total > limit.getValue()) {
+ limit.reached();
+ break;
+ }
+ }
+ } finally {
+ outstream.close();
+ }
+ return new FileResource(file);
+ }
+
+ public Resource copy(
+ final String requestId,
+ final Resource resource) throws IOException {
+ final File file = generateUniqueCacheFile(requestId);
+
+ if (resource instanceof FileResource) {
+ final File src = ((FileResource) resource).getFile();
+ IOUtils.copyFile(src, file);
+ } else {
+ final FileOutputStream out = new FileOutputStream(file);
+ IOUtils.copyAndClose(resource.getInputStream(), out);
+ }
+ return new FileResource(file);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/HeapResource.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/HeapResource.java
new file mode 100644
index 000000000..e4b353a3c
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/HeapResource.java
@@ -0,0 +1,67 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.cache.Resource;
+
+/**
+ * Cache resource backed by a byte array on the heap.
+ *
+ * @since 4.1
+ */
+@Immutable
+public class HeapResource implements Resource {
+
+ private static final long serialVersionUID = -2078599905620463394L;
+
+ private final byte[] b;
+
+ public HeapResource(final byte[] b) {
+ super();
+ this.b = b;
+ }
+
+ byte[] getByteArray() {
+ return this.b;
+ }
+
+ public InputStream getInputStream() {
+ return new ByteArrayInputStream(this.b);
+ }
+
+ public long length() {
+ return this.b.length;
+ }
+
+ public void dispose() {
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/HeapResourceFactory.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/HeapResourceFactory.java
new file mode 100644
index 000000000..f45cc0965
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/HeapResourceFactory.java
@@ -0,0 +1,83 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.cache.InputLimit;
+import ch.boye.httpclientandroidlib.client.cache.Resource;
+import ch.boye.httpclientandroidlib.client.cache.ResourceFactory;
+
+/**
+ * Generates {@link Resource} instances stored entirely in heap.
+ *
+ * @since 4.1
+ */
+@Immutable
+public class HeapResourceFactory implements ResourceFactory {
+
+ public Resource generate(
+ final String requestId,
+ final InputStream instream,
+ final InputLimit limit) throws IOException {
+ final ByteArrayOutputStream outstream = new ByteArrayOutputStream();
+ final byte[] buf = new byte[2048];
+ long total = 0;
+ int l;
+ while ((l = instream.read(buf)) != -1) {
+ outstream.write(buf, 0, l);
+ total += l;
+ if (limit != null && total > limit.getValue()) {
+ limit.reached();
+ break;
+ }
+ }
+ return createResource(outstream.toByteArray());
+ }
+
+ public Resource copy(
+ final String requestId,
+ final Resource resource) throws IOException {
+ byte[] body;
+ if (resource instanceof HeapResource) {
+ body = ((HeapResource) resource).getByteArray();
+ } else {
+ final ByteArrayOutputStream outstream = new ByteArrayOutputStream();
+ IOUtils.copyAndClose(resource.getInputStream(), outstream);
+ body = outstream.toByteArray();
+ }
+ return createResource(body);
+ }
+
+ Resource createResource(final byte[] buf) {
+ return new HeapResource(buf);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/HttpCache.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/HttpCache.java
new file mode 100644
index 000000000..48037b5f5
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/HttpCache.java
@@ -0,0 +1,166 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.IOException;
+import java.util.Date;
+import java.util.Map;
+
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.client.methods.CloseableHttpResponse;
+
+/**
+ * @since 4.1
+ */
+interface HttpCache {
+
+ /**
+ * Clear all matching {@link HttpCacheEntry}s.
+ * @param host
+ * @param request
+ * @throws IOException
+ */
+ void flushCacheEntriesFor(HttpHost host, HttpRequest request)
+ throws IOException;
+
+ /**
+ * Clear invalidated matching {@link HttpCacheEntry}s
+ * @param host
+ * @param request
+ * @throws IOException
+ */
+ void flushInvalidatedCacheEntriesFor(HttpHost host, HttpRequest request)
+ throws IOException;
+
+ /** Clear any entries that may be invalidated by the given response to
+ * a particular request.
+ * @param host
+ * @param request
+ * @param response
+ */
+ void flushInvalidatedCacheEntriesFor(HttpHost host, HttpRequest request,
+ HttpResponse response);
+
+ /**
+ * Retrieve matching {@link HttpCacheEntry} from the cache if it exists
+ * @param host
+ * @param request
+ * @return the matching {@link HttpCacheEntry} or {@code null}
+ * @throws IOException
+ */
+ HttpCacheEntry getCacheEntry(HttpHost host, HttpRequest request)
+ throws IOException;
+
+ /**
+ * Retrieve all variants from the cache, if there are no variants then an empty
+ * {@link Map} is returned
+ * @param host
+ * @param request
+ * @return a Map mapping Etags to variant cache entries
+ * @throws IOException
+ */
+ Map getVariantCacheEntriesWithEtags(HttpHost host, HttpRequest request)
+ throws IOException;
+
+ /**
+ * Store a {@link HttpResponse} in the cache if possible, and return
+ * @param host
+ * @param request
+ * @param originResponse
+ * @param requestSent
+ * @param responseReceived
+ * @return the {@link HttpResponse}
+ * @throws IOException
+ */
+ HttpResponse cacheAndReturnResponse(
+ HttpHost host, HttpRequest request, HttpResponse originResponse,
+ Date requestSent, Date responseReceived)
+ throws IOException;
+
+ /**
+ * Store a {@link HttpResponse} in the cache if possible, and return
+ * @param host
+ * @param request
+ * @param originResponse
+ * @param requestSent
+ * @param responseReceived
+ * @return the {@link HttpResponse}
+ * @throws IOException
+ */
+ CloseableHttpResponse cacheAndReturnResponse(HttpHost host,
+ HttpRequest request, CloseableHttpResponse originResponse,
+ Date requestSent, Date responseReceived)
+ throws IOException;
+
+ /**
+ * Update a {@link HttpCacheEntry} using a 304 {@link HttpResponse}.
+ * @param target
+ * @param request
+ * @param stale
+ * @param originResponse
+ * @param requestSent
+ * @param responseReceived
+ * @return the updated {@link HttpCacheEntry}
+ * @throws IOException
+ */
+ HttpCacheEntry updateCacheEntry(
+ HttpHost target, HttpRequest request, HttpCacheEntry stale, HttpResponse originResponse,
+ Date requestSent, Date responseReceived)
+ throws IOException;
+
+ /**
+ * Update a specific {@link HttpCacheEntry} representing a cached variant
+ * using a 304 {@link HttpResponse}.
+ * @param target host for client request
+ * @param request actual request from upstream client
+ * @param stale current variant cache entry
+ * @param originResponse 304 response received from origin
+ * @param requestSent when the validating request was sent
+ * @param responseReceived when the validating response was received
+ * @param cacheKey where in the cache this entry is currently stored
+ * @return the updated {@link HttpCacheEntry}
+ * @throws IOException
+ */
+ HttpCacheEntry updateVariantCacheEntry(HttpHost target, HttpRequest request,
+ HttpCacheEntry stale, HttpResponse originResponse, Date requestSent,
+ Date responseReceived, String cacheKey)
+ throws IOException;
+
+ /**
+ * Specifies cache should reuse the given cached variant to satisfy
+ * requests whose varying headers match those of the given client request.
+ * @param target host of the upstream client request
+ * @param req request sent by upstream client
+ * @param variant variant cache entry to reuse
+ * @throws IOException may be thrown during cache update
+ */
+ void reuseVariantEntryFor(HttpHost target, final HttpRequest req,
+ final Variant variant) throws IOException;
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/IOUtils.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/IOUtils.java
new file mode 100644
index 000000000..aaf41b2c9
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/IOUtils.java
@@ -0,0 +1,109 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.RandomAccessFile;
+import java.nio.channels.FileChannel;
+
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+
+@Immutable
+class IOUtils {
+
+ static void consume(final HttpEntity entity) throws IOException {
+ if (entity == null) {
+ return;
+ }
+ if (entity.isStreaming()) {
+ final InputStream instream = entity.getContent();
+ if (instream != null) {
+ instream.close();
+ }
+ }
+ }
+
+ static void copy(final InputStream in, final OutputStream out) throws IOException {
+ final byte[] buf = new byte[2048];
+ int len;
+ while ((len = in.read(buf)) != -1) {
+ out.write(buf, 0, len);
+ }
+ }
+
+ static void closeSilently(final Closeable closable) {
+ try {
+ closable.close();
+ } catch (final IOException ignore) {
+ }
+ }
+
+ static void copyAndClose(final InputStream in, final OutputStream out) throws IOException {
+ try {
+ copy(in, out);
+ in.close();
+ out.close();
+ } catch (final IOException ex) {
+ closeSilently(in);
+ closeSilently(out);
+ // Propagate the original exception
+ throw ex;
+ }
+ }
+
+ static void copyFile(final File in, final File out) throws IOException {
+ final RandomAccessFile f1 = new RandomAccessFile(in, "r");
+ final RandomAccessFile f2 = new RandomAccessFile(out, "rw");
+ try {
+ final FileChannel c1 = f1.getChannel();
+ final FileChannel c2 = f2.getChannel();
+ try {
+ c1.transferTo(0, f1.length(), c2);
+ c1.close();
+ c2.close();
+ } catch (final IOException ex) {
+ closeSilently(c1);
+ closeSilently(c2);
+ // Propagate the original exception
+ throw ex;
+ }
+ f1.close();
+ f2.close();
+ } catch (final IOException ex) {
+ closeSilently(f1);
+ closeSilently(f2);
+ // Propagate the original exception
+ throw ex;
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ImmediateSchedulingStrategy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ImmediateSchedulingStrategy.java
new file mode 100644
index 000000000..71d633825
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ImmediateSchedulingStrategy.java
@@ -0,0 +1,88 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Immediately schedules any incoming validation request. Relies on
+ * {@link CacheConfig} to configure the used {@link java.util.concurrent.ThreadPoolExecutor}.
+ *
+ * @since 4.3
+ */
+@ThreadSafe
+public class ImmediateSchedulingStrategy implements SchedulingStrategy {
+
+ private final ExecutorService executor;
+
+ /**
+ * Uses a {@link java.util.concurrent.ThreadPoolExecutor} which is configured according to the
+ * given {@link CacheConfig}.
+ * @param cacheConfig specifies thread pool settings. See
+ * {@link CacheConfig#getAsynchronousWorkersMax()},
+ * {@link CacheConfig#getAsynchronousWorkersCore()},
+ * {@link CacheConfig#getAsynchronousWorkerIdleLifetimeSecs()},
+ * and {@link CacheConfig#getRevalidationQueueSize()}.
+ */
+ public ImmediateSchedulingStrategy(final CacheConfig cacheConfig) {
+ this(new ThreadPoolExecutor(
+ cacheConfig.getAsynchronousWorkersCore(),
+ cacheConfig.getAsynchronousWorkersMax(),
+ cacheConfig.getAsynchronousWorkerIdleLifetimeSecs(),
+ TimeUnit.SECONDS,
+ new ArrayBlockingQueue(cacheConfig.getRevalidationQueueSize()))
+ );
+ }
+
+ ImmediateSchedulingStrategy(final ExecutorService executor) {
+ this.executor = executor;
+ }
+
+ public void schedule(final AsynchronousValidationRequest revalidationRequest) {
+ if (revalidationRequest == null) {
+ throw new IllegalArgumentException("AsynchronousValidationRequest may not be null");
+ }
+
+ executor.execute(revalidationRequest);
+ }
+
+ public void close() {
+ executor.shutdown();
+ }
+
+ /**
+ * Visible for testing.
+ */
+ void awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException {
+ executor.awaitTermination(timeout, unit);
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ManagedHttpCacheStorage.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ManagedHttpCacheStorage.java
new file mode 100644
index 000000000..3a2589cc3
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ManagedHttpCacheStorage.java
@@ -0,0 +1,163 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.lang.ref.ReferenceQueue;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheStorage;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheUpdateCallback;
+import ch.boye.httpclientandroidlib.client.cache.Resource;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * {@link HttpCacheStorage} implementation capable of deallocating resources associated with
+ * the cache entries. This cache keeps track of cache entries using
+ * {@link java.lang.ref.PhantomReference} and maintains a collection of all resources that
+ * are no longer in use. The cache, however, does not automatically deallocates associated
+ * resources by invoking {@link Resource#dispose()} method. The consumer MUST periodically
+ * call {@link #cleanResources()} method to trigger resource deallocation. The cache can be
+ * permanently shut down using {@link #shutdown()} method. All resources associated with
+ * the entries used by the cache will be deallocated.
+ *
+ * This {@link HttpCacheStorage} implementation is intended for use with {@link FileResource}
+ * and similar.
+ *
+ * @since 4.1
+ */
+@ThreadSafe
+public class ManagedHttpCacheStorage implements HttpCacheStorage, Closeable {
+
+ private final CacheMap entries;
+ private final ReferenceQueue morque;
+ private final Set resources;
+ private final AtomicBoolean active;
+
+ public ManagedHttpCacheStorage(final CacheConfig config) {
+ super();
+ this.entries = new CacheMap(config.getMaxCacheEntries());
+ this.morque = new ReferenceQueue();
+ this.resources = new HashSet();
+ this.active = new AtomicBoolean(true);
+ }
+
+ private void ensureValidState() throws IllegalStateException {
+ if (!this.active.get()) {
+ throw new IllegalStateException("Cache has been shut down");
+ }
+ }
+
+ private void keepResourceReference(final HttpCacheEntry entry) {
+ final Resource resource = entry.getResource();
+ if (resource != null) {
+ // Must deallocate the resource when the entry is no longer in used
+ final ResourceReference ref = new ResourceReference(entry, this.morque);
+ this.resources.add(ref);
+ }
+ }
+
+ public void putEntry(final String url, final HttpCacheEntry entry) throws IOException {
+ Args.notNull(url, "URL");
+ Args.notNull(entry, "Cache entry");
+ ensureValidState();
+ synchronized (this) {
+ this.entries.put(url, entry);
+ keepResourceReference(entry);
+ }
+ }
+
+ public HttpCacheEntry getEntry(final String url) throws IOException {
+ Args.notNull(url, "URL");
+ ensureValidState();
+ synchronized (this) {
+ return this.entries.get(url);
+ }
+ }
+
+ public void removeEntry(final String url) throws IOException {
+ Args.notNull(url, "URL");
+ ensureValidState();
+ synchronized (this) {
+ // Cannot deallocate the associated resources immediately as the
+ // cache entry may still be in use
+ this.entries.remove(url);
+ }
+ }
+
+ public void updateEntry(
+ final String url,
+ final HttpCacheUpdateCallback callback) throws IOException {
+ Args.notNull(url, "URL");
+ Args.notNull(callback, "Callback");
+ ensureValidState();
+ synchronized (this) {
+ final HttpCacheEntry existing = this.entries.get(url);
+ final HttpCacheEntry updated = callback.update(existing);
+ this.entries.put(url, updated);
+ if (existing != updated) {
+ keepResourceReference(updated);
+ }
+ }
+ }
+
+ public void cleanResources() {
+ if (this.active.get()) {
+ ResourceReference ref;
+ while ((ref = (ResourceReference) this.morque.poll()) != null) {
+ synchronized (this) {
+ this.resources.remove(ref);
+ }
+ ref.getResource().dispose();
+ }
+ }
+ }
+
+ public void shutdown() {
+ if (this.active.compareAndSet(true, false)) {
+ synchronized (this) {
+ this.entries.clear();
+ for (final ResourceReference ref: this.resources) {
+ ref.getResource().dispose();
+ }
+ this.resources.clear();
+ while (this.morque.poll() != null) {
+ }
+ }
+ }
+ }
+
+ public void close() {
+ shutdown();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/OptionsHttp11Response.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/OptionsHttp11Response.java
new file mode 100644
index 000000000..c2e07b52d
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/OptionsHttp11Response.java
@@ -0,0 +1,182 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.util.Locale;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HeaderIterator;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.HttpVersion;
+import ch.boye.httpclientandroidlib.ProtocolVersion;
+import ch.boye.httpclientandroidlib.StatusLine;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.message.AbstractHttpMessage;
+import ch.boye.httpclientandroidlib.message.BasicStatusLine;
+import ch.boye.httpclientandroidlib.params.BasicHttpParams;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+
+/**
+ * @since 4.1
+ */
+@SuppressWarnings("deprecation")
+@Immutable
+final class OptionsHttp11Response extends AbstractHttpMessage implements HttpResponse {
+
+ private final StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1,
+ HttpStatus.SC_NOT_IMPLEMENTED, "");
+ private final ProtocolVersion version = HttpVersion.HTTP_1_1;
+
+ public StatusLine getStatusLine() {
+ return statusLine;
+ }
+
+ public void setStatusLine(final StatusLine statusline) {
+ // No-op on purpose, this class is not going to be doing any work.
+ }
+
+ public void setStatusLine(final ProtocolVersion ver, final int code) {
+ // No-op on purpose, this class is not going to be doing any work.
+ }
+
+ public void setStatusLine(final ProtocolVersion ver, final int code, final String reason) {
+ // No-op on purpose, this class is not going to be doing any work.
+ }
+
+ public void setStatusCode(final int code) throws IllegalStateException {
+ // No-op on purpose, this class is not going to be doing any work.
+ }
+
+ public void setReasonPhrase(final String reason) throws IllegalStateException {
+ // No-op on purpose, this class is not going to be doing any work.
+ }
+
+ public HttpEntity getEntity() {
+ return null;
+ }
+
+ public void setEntity(final HttpEntity entity) {
+ // No-op on purpose, this class is not going to be doing any work.
+ }
+
+ public Locale getLocale() {
+ return null;
+ }
+
+ public void setLocale(final Locale loc) {
+ // No-op on purpose, this class is not going to be doing any work.
+ }
+
+ public ProtocolVersion getProtocolVersion() {
+ return version;
+ }
+
+ @Override
+ public boolean containsHeader(final String name) {
+ return this.headergroup.containsHeader(name);
+ }
+
+ @Override
+ public Header[] getHeaders(final String name) {
+ return this.headergroup.getHeaders(name);
+ }
+
+ @Override
+ public Header getFirstHeader(final String name) {
+ return this.headergroup.getFirstHeader(name);
+ }
+
+ @Override
+ public Header getLastHeader(final String name) {
+ return this.headergroup.getLastHeader(name);
+ }
+
+ @Override
+ public Header[] getAllHeaders() {
+ return this.headergroup.getAllHeaders();
+ }
+
+ @Override
+ public void addHeader(final Header header) {
+ // No-op on purpose, this class is not going to be doing any work.
+ }
+
+ @Override
+ public void addHeader(final String name, final String value) {
+ // No-op on purpose, this class is not going to be doing any work.
+ }
+
+ @Override
+ public void setHeader(final Header header) {
+ // No-op on purpose, this class is not going to be doing any work.
+ }
+
+ @Override
+ public void setHeader(final String name, final String value) {
+ // No-op on purpose, this class is not going to be doing any work.
+ }
+
+ @Override
+ public void setHeaders(final Header[] headers) {
+ // No-op on purpose, this class is not going to be doing any work.
+ }
+
+ @Override
+ public void removeHeader(final Header header) {
+ // No-op on purpose, this class is not going to be doing any work.
+ }
+
+ @Override
+ public void removeHeaders(final String name) {
+ // No-op on purpose, this class is not going to be doing any work.
+ }
+
+ @Override
+ public HeaderIterator headerIterator() {
+ return this.headergroup.iterator();
+ }
+
+ @Override
+ public HeaderIterator headerIterator(final String name) {
+ return this.headergroup.iterator(name);
+ }
+
+ @Override
+ public HttpParams getParams() {
+ if (this.params == null) {
+ this.params = new BasicHttpParams();
+ }
+ return this.params;
+ }
+
+ @Override
+ public void setParams(final HttpParams params) {
+ // No-op on purpose, this class is not going to be doing any work.
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/Proxies.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/Proxies.java
new file mode 100644
index 000000000..4499d8288
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/Proxies.java
@@ -0,0 +1,56 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.lang.reflect.Proxy;
+
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.client.methods.CloseableHttpResponse;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Proxies for HTTP message objects.
+ *
+ * @since 4.3
+ */
+@NotThreadSafe
+class Proxies {
+
+ public static CloseableHttpResponse enhanceResponse(final HttpResponse original) {
+ Args.notNull(original, "HTTP response");
+ if (original instanceof CloseableHttpResponse) {
+ return (CloseableHttpResponse) original;
+ } else {
+ return (CloseableHttpResponse) Proxy.newProxyInstance(
+ ResponseProxyHandler.class.getClassLoader(),
+ new Class>[] { CloseableHttpResponse.class },
+ new ResponseProxyHandler(original));
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/RequestProtocolCompliance.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/RequestProtocolCompliance.java
new file mode 100644
index 000000000..ac7ab439c
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/RequestProtocolCompliance.java
@@ -0,0 +1,376 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HeaderElement;
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.HttpVersion;
+import ch.boye.httpclientandroidlib.ProtocolVersion;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.ClientProtocolException;
+import ch.boye.httpclientandroidlib.client.cache.HeaderConstants;
+import ch.boye.httpclientandroidlib.client.methods.HttpRequestWrapper;
+import ch.boye.httpclientandroidlib.entity.AbstractHttpEntity;
+import ch.boye.httpclientandroidlib.entity.ContentType;
+import ch.boye.httpclientandroidlib.message.BasicHeader;
+import ch.boye.httpclientandroidlib.message.BasicHttpResponse;
+import ch.boye.httpclientandroidlib.message.BasicStatusLine;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+
+/**
+ * @since 4.1
+ */
+@Immutable
+class RequestProtocolCompliance {
+ private final boolean weakETagOnPutDeleteAllowed;
+
+ public RequestProtocolCompliance() {
+ super();
+ this.weakETagOnPutDeleteAllowed = false;
+ }
+
+ public RequestProtocolCompliance(final boolean weakETagOnPutDeleteAllowed) {
+ super();
+ this.weakETagOnPutDeleteAllowed = weakETagOnPutDeleteAllowed;
+ }
+
+ private static final List disallowedWithNoCache =
+ Arrays.asList(HeaderConstants.CACHE_CONTROL_MIN_FRESH, HeaderConstants.CACHE_CONTROL_MAX_STALE, HeaderConstants.CACHE_CONTROL_MAX_AGE);
+
+ /**
+ * Test to see if the {@link HttpRequest} is HTTP1.1 compliant or not
+ * and if not, we can not continue.
+ *
+ * @param request the HttpRequest Object
+ * @return list of {@link RequestProtocolError}
+ */
+ public List requestIsFatallyNonCompliant(final HttpRequest request) {
+ final List theErrors = new ArrayList();
+
+ RequestProtocolError anError = requestHasWeakETagAndRange(request);
+ if (anError != null) {
+ theErrors.add(anError);
+ }
+
+ if (!weakETagOnPutDeleteAllowed) {
+ anError = requestHasWeekETagForPUTOrDELETEIfMatch(request);
+ if (anError != null) {
+ theErrors.add(anError);
+ }
+ }
+
+ anError = requestContainsNoCacheDirectiveWithFieldName(request);
+ if (anError != null) {
+ theErrors.add(anError);
+ }
+
+ return theErrors;
+ }
+
+ /**
+ * If the {@link HttpRequest} is non-compliant but 'fixable' we go ahead and
+ * fix the request here.
+ *
+ * @param request the request to check for compliance
+ * @throws ClientProtocolException when we have trouble making the request compliant
+ */
+ public void makeRequestCompliant(final HttpRequestWrapper request)
+ throws ClientProtocolException {
+
+ if (requestMustNotHaveEntity(request)) {
+ ((HttpEntityEnclosingRequest) request).setEntity(null);
+ }
+
+ verifyRequestWithExpectContinueFlagHas100continueHeader(request);
+ verifyOPTIONSRequestWithBodyHasContentType(request);
+ decrementOPTIONSMaxForwardsIfGreaterThen0(request);
+ stripOtherFreshnessDirectivesWithNoCache(request);
+
+ if (requestVersionIsTooLow(request)
+ || requestMinorVersionIsTooHighMajorVersionsMatch(request)) {
+ request.setProtocolVersion(HttpVersion.HTTP_1_1);
+ }
+ }
+
+ private void stripOtherFreshnessDirectivesWithNoCache(final HttpRequest request) {
+ final List outElts = new ArrayList();
+ boolean shouldStrip = false;
+ for(final Header h : request.getHeaders(HeaderConstants.CACHE_CONTROL)) {
+ for(final HeaderElement elt : h.getElements()) {
+ if (!disallowedWithNoCache.contains(elt.getName())) {
+ outElts.add(elt);
+ }
+ if (HeaderConstants.CACHE_CONTROL_NO_CACHE.equals(elt.getName())) {
+ shouldStrip = true;
+ }
+ }
+ }
+ if (!shouldStrip) {
+ return;
+ }
+ request.removeHeaders(HeaderConstants.CACHE_CONTROL);
+ request.setHeader(HeaderConstants.CACHE_CONTROL, buildHeaderFromElements(outElts));
+ }
+
+ private String buildHeaderFromElements(final List outElts) {
+ final StringBuilder newHdr = new StringBuilder("");
+ boolean first = true;
+ for(final HeaderElement elt : outElts) {
+ if (!first) {
+ newHdr.append(",");
+ } else {
+ first = false;
+ }
+ newHdr.append(elt.toString());
+ }
+ return newHdr.toString();
+ }
+
+ private boolean requestMustNotHaveEntity(final HttpRequest request) {
+ return HeaderConstants.TRACE_METHOD.equals(request.getRequestLine().getMethod())
+ && request instanceof HttpEntityEnclosingRequest;
+ }
+
+ private void decrementOPTIONSMaxForwardsIfGreaterThen0(final HttpRequest request) {
+ if (!HeaderConstants.OPTIONS_METHOD.equals(request.getRequestLine().getMethod())) {
+ return;
+ }
+
+ final Header maxForwards = request.getFirstHeader(HeaderConstants.MAX_FORWARDS);
+ if (maxForwards == null) {
+ return;
+ }
+
+ request.removeHeaders(HeaderConstants.MAX_FORWARDS);
+ final int currentMaxForwards = Integer.parseInt(maxForwards.getValue());
+
+ request.setHeader(HeaderConstants.MAX_FORWARDS, Integer.toString(currentMaxForwards - 1));
+ }
+
+ private void verifyOPTIONSRequestWithBodyHasContentType(final HttpRequest request) {
+ if (!HeaderConstants.OPTIONS_METHOD.equals(request.getRequestLine().getMethod())) {
+ return;
+ }
+
+ if (!(request instanceof HttpEntityEnclosingRequest)) {
+ return;
+ }
+
+ addContentTypeHeaderIfMissing((HttpEntityEnclosingRequest) request);
+ }
+
+ private void addContentTypeHeaderIfMissing(final HttpEntityEnclosingRequest request) {
+ if (request.getEntity().getContentType() == null) {
+ ((AbstractHttpEntity) request.getEntity()).setContentType(
+ ContentType.APPLICATION_OCTET_STREAM.getMimeType());
+ }
+ }
+
+ private void verifyRequestWithExpectContinueFlagHas100continueHeader(final HttpRequest request) {
+ if (request instanceof HttpEntityEnclosingRequest) {
+
+ if (((HttpEntityEnclosingRequest) request).expectContinue()
+ && ((HttpEntityEnclosingRequest) request).getEntity() != null) {
+ add100ContinueHeaderIfMissing(request);
+ } else {
+ remove100ContinueHeaderIfExists(request);
+ }
+ } else {
+ remove100ContinueHeaderIfExists(request);
+ }
+ }
+
+ private void remove100ContinueHeaderIfExists(final HttpRequest request) {
+ boolean hasHeader = false;
+
+ final Header[] expectHeaders = request.getHeaders(HTTP.EXPECT_DIRECTIVE);
+ List expectElementsThatAreNot100Continue = new ArrayList();
+
+ for (final Header h : expectHeaders) {
+ for (final HeaderElement elt : h.getElements()) {
+ if (!(HTTP.EXPECT_CONTINUE.equalsIgnoreCase(elt.getName()))) {
+ expectElementsThatAreNot100Continue.add(elt);
+ } else {
+ hasHeader = true;
+ }
+ }
+
+ if (hasHeader) {
+ request.removeHeader(h);
+ for (final HeaderElement elt : expectElementsThatAreNot100Continue) {
+ final BasicHeader newHeader = new BasicHeader(HTTP.EXPECT_DIRECTIVE, elt.getName());
+ request.addHeader(newHeader);
+ }
+ return;
+ } else {
+ expectElementsThatAreNot100Continue = new ArrayList();
+ }
+ }
+ }
+
+ private void add100ContinueHeaderIfMissing(final HttpRequest request) {
+ boolean hasHeader = false;
+
+ for (final Header h : request.getHeaders(HTTP.EXPECT_DIRECTIVE)) {
+ for (final HeaderElement elt : h.getElements()) {
+ if (HTTP.EXPECT_CONTINUE.equalsIgnoreCase(elt.getName())) {
+ hasHeader = true;
+ }
+ }
+ }
+
+ if (!hasHeader) {
+ request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE);
+ }
+ }
+
+ protected boolean requestMinorVersionIsTooHighMajorVersionsMatch(final HttpRequest request) {
+ final ProtocolVersion requestProtocol = request.getProtocolVersion();
+ if (requestProtocol.getMajor() != HttpVersion.HTTP_1_1.getMajor()) {
+ return false;
+ }
+
+ if (requestProtocol.getMinor() > HttpVersion.HTTP_1_1.getMinor()) {
+ return true;
+ }
+
+ return false;
+ }
+
+ protected boolean requestVersionIsTooLow(final HttpRequest request) {
+ return request.getProtocolVersion().compareToVersion(HttpVersion.HTTP_1_1) < 0;
+ }
+
+ /**
+ * Extract error information about the {@link HttpRequest} telling the 'caller'
+ * that a problem occured.
+ *
+ * @param errorCheck What type of error should I get
+ * @return The {@link HttpResponse} that is the error generated
+ */
+ public HttpResponse getErrorForRequest(final RequestProtocolError errorCheck) {
+ switch (errorCheck) {
+ case BODY_BUT_NO_LENGTH_ERROR:
+ return new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1,
+ HttpStatus.SC_LENGTH_REQUIRED, ""));
+
+ case WEAK_ETAG_AND_RANGE_ERROR:
+ return new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1,
+ HttpStatus.SC_BAD_REQUEST, "Weak eTag not compatible with byte range"));
+
+ case WEAK_ETAG_ON_PUTDELETE_METHOD_ERROR:
+ return new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1,
+ HttpStatus.SC_BAD_REQUEST,
+ "Weak eTag not compatible with PUT or DELETE requests"));
+
+ case NO_CACHE_DIRECTIVE_WITH_FIELD_NAME:
+ return new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1,
+ HttpStatus.SC_BAD_REQUEST,
+ "No-Cache directive MUST NOT include a field name"));
+
+ default:
+ throw new IllegalStateException(
+ "The request was compliant, therefore no error can be generated for it.");
+
+ }
+ }
+
+ private RequestProtocolError requestHasWeakETagAndRange(final HttpRequest request) {
+ // TODO: Should these be looking at all the headers marked as Range?
+ final String method = request.getRequestLine().getMethod();
+ if (!(HeaderConstants.GET_METHOD.equals(method))) {
+ return null;
+ }
+
+ final Header range = request.getFirstHeader(HeaderConstants.RANGE);
+ if (range == null) {
+ return null;
+ }
+
+ final Header ifRange = request.getFirstHeader(HeaderConstants.IF_RANGE);
+ if (ifRange == null) {
+ return null;
+ }
+
+ final String val = ifRange.getValue();
+ if (val.startsWith("W/")) {
+ return RequestProtocolError.WEAK_ETAG_AND_RANGE_ERROR;
+ }
+
+ return null;
+ }
+
+ private RequestProtocolError requestHasWeekETagForPUTOrDELETEIfMatch(final HttpRequest request) {
+ // TODO: Should these be looking at all the headers marked as If-Match/If-None-Match?
+
+ final String method = request.getRequestLine().getMethod();
+ if (!(HeaderConstants.PUT_METHOD.equals(method) || HeaderConstants.DELETE_METHOD
+ .equals(method))) {
+ return null;
+ }
+
+ final Header ifMatch = request.getFirstHeader(HeaderConstants.IF_MATCH);
+ if (ifMatch != null) {
+ final String val = ifMatch.getValue();
+ if (val.startsWith("W/")) {
+ return RequestProtocolError.WEAK_ETAG_ON_PUTDELETE_METHOD_ERROR;
+ }
+ } else {
+ final Header ifNoneMatch = request.getFirstHeader(HeaderConstants.IF_NONE_MATCH);
+ if (ifNoneMatch == null) {
+ return null;
+ }
+
+ final String val2 = ifNoneMatch.getValue();
+ if (val2.startsWith("W/")) {
+ return RequestProtocolError.WEAK_ETAG_ON_PUTDELETE_METHOD_ERROR;
+ }
+ }
+
+ return null;
+ }
+
+ private RequestProtocolError requestContainsNoCacheDirectiveWithFieldName(final HttpRequest request) {
+ for(final Header h : request.getHeaders(HeaderConstants.CACHE_CONTROL)) {
+ for(final HeaderElement elt : h.getElements()) {
+ if (HeaderConstants.CACHE_CONTROL_NO_CACHE.equalsIgnoreCase(elt.getName())
+ && elt.getValue() != null) {
+ return RequestProtocolError.NO_CACHE_DIRECTIVE_WITH_FIELD_NAME;
+ }
+ }
+ }
+ return null;
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/RequestProtocolError.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/RequestProtocolError.java
new file mode 100644
index 000000000..1cc5668c7
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/RequestProtocolError.java
@@ -0,0 +1,40 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+/**
+ * @since 4.1
+ */
+enum RequestProtocolError {
+
+ UNKNOWN,
+ BODY_BUT_NO_LENGTH_ERROR,
+ WEAK_ETAG_ON_PUTDELETE_METHOD_ERROR,
+ WEAK_ETAG_AND_RANGE_ERROR,
+ NO_CACHE_DIRECTIVE_WITH_FIELD_NAME
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ResourceReference.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ResourceReference.java
new file mode 100644
index 000000000..5e3f368f1
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ResourceReference.java
@@ -0,0 +1,62 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.lang.ref.PhantomReference;
+import java.lang.ref.ReferenceQueue;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+import ch.boye.httpclientandroidlib.client.cache.Resource;
+import ch.boye.httpclientandroidlib.util.Args;
+
+@Immutable
+class ResourceReference extends PhantomReference {
+
+ private final Resource resource;
+
+ public ResourceReference(final HttpCacheEntry entry, final ReferenceQueue q) {
+ super(entry, q);
+ Args.notNull(entry.getResource(), "Resource");
+ this.resource = entry.getResource();
+ }
+
+ public Resource getResource() {
+ return this.resource;
+ }
+
+ @Override
+ public int hashCode() {
+ return this.resource.hashCode();
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ return this.resource.equals(obj);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ResponseCachingPolicy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ResponseCachingPolicy.java
new file mode 100644
index 000000000..abadb88d4
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ResponseCachingPolicy.java
@@ -0,0 +1,311 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Set;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HeaderElement;
+import ch.boye.httpclientandroidlib.HttpMessage;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.HttpVersion;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.cache.HeaderConstants;
+import ch.boye.httpclientandroidlib.client.utils.DateUtils;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+
+/**
+ * Determines if an HttpResponse can be cached.
+ *
+ * @since 4.1
+ */
+@Immutable
+class ResponseCachingPolicy {
+
+ private static final String[] AUTH_CACHEABLE_PARAMS = {
+ "s-maxage", HeaderConstants.CACHE_CONTROL_MUST_REVALIDATE, HeaderConstants.PUBLIC
+ };
+ private final long maxObjectSizeBytes;
+ private final boolean sharedCache;
+ private final boolean neverCache1_0ResponsesWithQueryString;
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+ private static final Set cacheableStatuses =
+ new HashSet(Arrays.asList(HttpStatus.SC_OK,
+ HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION,
+ HttpStatus.SC_MULTIPLE_CHOICES,
+ HttpStatus.SC_MOVED_PERMANENTLY,
+ HttpStatus.SC_GONE));
+ private final Set uncacheableStatuses;
+ /**
+ * Define a cache policy that limits the size of things that should be stored
+ * in the cache to a maximum of {@link HttpResponse} bytes in size.
+ *
+ * @param maxObjectSizeBytes the size to limit items into the cache
+ * @param sharedCache whether to behave as a shared cache (true) or a
+ * non-shared/private cache (false)
+ * @param neverCache1_0ResponsesWithQueryString true to never cache HTTP 1.0 responses with a query string, false
+ * to cache if explicit cache headers are found.
+ * @param allow303Caching if this policy is permitted to cache 303 response
+ */
+ public ResponseCachingPolicy(final long maxObjectSizeBytes,
+ final boolean sharedCache,
+ final boolean neverCache1_0ResponsesWithQueryString,
+ final boolean allow303Caching) {
+ this.maxObjectSizeBytes = maxObjectSizeBytes;
+ this.sharedCache = sharedCache;
+ this.neverCache1_0ResponsesWithQueryString = neverCache1_0ResponsesWithQueryString;
+ if (allow303Caching) {
+ uncacheableStatuses = new HashSet(
+ Arrays.asList(HttpStatus.SC_PARTIAL_CONTENT));
+ } else {
+ uncacheableStatuses = new HashSet(Arrays.asList(
+ HttpStatus.SC_PARTIAL_CONTENT, HttpStatus.SC_SEE_OTHER));
+ }
+ }
+
+ /**
+ * Determines if an HttpResponse can be cached.
+ *
+ * @param httpMethod What type of request was this, a GET, PUT, other?
+ * @param response The origin response
+ * @return true if response is cacheable
+ */
+ public boolean isResponseCacheable(final String httpMethod, final HttpResponse response) {
+ boolean cacheable = false;
+
+ if (!HeaderConstants.GET_METHOD.equals(httpMethod)) {
+ log.debug("Response was not cacheable.");
+ return false;
+ }
+
+ final int status = response.getStatusLine().getStatusCode();
+ if (cacheableStatuses.contains(status)) {
+ // these response codes MAY be cached
+ cacheable = true;
+ } else if (uncacheableStatuses.contains(status)) {
+ return false;
+ } else if (unknownStatusCode(status)) {
+ // a response with an unknown status code MUST NOT be
+ // cached
+ return false;
+ }
+
+ final Header contentLength = response.getFirstHeader(HTTP.CONTENT_LEN);
+ if (contentLength != null) {
+ final int contentLengthValue = Integer.parseInt(contentLength.getValue());
+ if (contentLengthValue > this.maxObjectSizeBytes) {
+ return false;
+ }
+ }
+
+ final Header[] ageHeaders = response.getHeaders(HeaderConstants.AGE);
+
+ if (ageHeaders.length > 1) {
+ return false;
+ }
+
+ final Header[] expiresHeaders = response.getHeaders(HeaderConstants.EXPIRES);
+
+ if (expiresHeaders.length > 1) {
+ return false;
+ }
+
+ final Header[] dateHeaders = response.getHeaders(HTTP.DATE_HEADER);
+
+ if (dateHeaders.length != 1) {
+ return false;
+ }
+
+ final Date date = DateUtils.parseDate(dateHeaders[0].getValue());
+ if (date == null) {
+ return false;
+ }
+
+ for (final Header varyHdr : response.getHeaders(HeaderConstants.VARY)) {
+ for (final HeaderElement elem : varyHdr.getElements()) {
+ if ("*".equals(elem.getName())) {
+ return false;
+ }
+ }
+ }
+
+ if (isExplicitlyNonCacheable(response)) {
+ return false;
+ }
+
+ return (cacheable || isExplicitlyCacheable(response));
+ }
+
+ private boolean unknownStatusCode(final int status) {
+ if (status >= 100 && status <= 101) {
+ return false;
+ }
+ if (status >= 200 && status <= 206) {
+ return false;
+ }
+ if (status >= 300 && status <= 307) {
+ return false;
+ }
+ if (status >= 400 && status <= 417) {
+ return false;
+ }
+ if (status >= 500 && status <= 505) {
+ return false;
+ }
+ return true;
+ }
+
+ protected boolean isExplicitlyNonCacheable(final HttpResponse response) {
+ final Header[] cacheControlHeaders = response.getHeaders(HeaderConstants.CACHE_CONTROL);
+ for (final Header header : cacheControlHeaders) {
+ for (final HeaderElement elem : header.getElements()) {
+ if (HeaderConstants.CACHE_CONTROL_NO_STORE.equals(elem.getName())
+ || HeaderConstants.CACHE_CONTROL_NO_CACHE.equals(elem.getName())
+ || (sharedCache && HeaderConstants.PRIVATE.equals(elem.getName()))) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ protected boolean hasCacheControlParameterFrom(final HttpMessage msg, final String[] params) {
+ final Header[] cacheControlHeaders = msg.getHeaders(HeaderConstants.CACHE_CONTROL);
+ for (final Header header : cacheControlHeaders) {
+ for (final HeaderElement elem : header.getElements()) {
+ for (final String param : params) {
+ if (param.equalsIgnoreCase(elem.getName())) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ protected boolean isExplicitlyCacheable(final HttpResponse response) {
+ if (response.getFirstHeader(HeaderConstants.EXPIRES) != null) {
+ return true;
+ }
+ final String[] cacheableParams = { HeaderConstants.CACHE_CONTROL_MAX_AGE, "s-maxage",
+ HeaderConstants.CACHE_CONTROL_MUST_REVALIDATE,
+ HeaderConstants.CACHE_CONTROL_PROXY_REVALIDATE,
+ HeaderConstants.PUBLIC
+ };
+ return hasCacheControlParameterFrom(response, cacheableParams);
+ }
+
+ /**
+ * Determine if the {@link HttpResponse} gotten from the origin is a
+ * cacheable response.
+ *
+ * @param request the {@link HttpRequest} that generated an origin hit
+ * @param response the {@link HttpResponse} from the origin
+ * @return true if response is cacheable
+ */
+ public boolean isResponseCacheable(final HttpRequest request, final HttpResponse response) {
+ if (requestProtocolGreaterThanAccepted(request)) {
+ log.debug("Response was not cacheable.");
+ return false;
+ }
+
+ final String[] uncacheableRequestDirectives = { HeaderConstants.CACHE_CONTROL_NO_STORE };
+ if (hasCacheControlParameterFrom(request,uncacheableRequestDirectives)) {
+ return false;
+ }
+
+ if (request.getRequestLine().getUri().contains("?")) {
+ if (neverCache1_0ResponsesWithQueryString && from1_0Origin(response)) {
+ log.debug("Response was not cacheable as it had a query string.");
+ return false;
+ } else if (!isExplicitlyCacheable(response)) {
+ log.debug("Response was not cacheable as it is missing explicit caching headers.");
+ return false;
+ }
+ }
+
+ if (expiresHeaderLessOrEqualToDateHeaderAndNoCacheControl(response)) {
+ return false;
+ }
+
+ if (sharedCache) {
+ final Header[] authNHeaders = request.getHeaders(HeaderConstants.AUTHORIZATION);
+ if (authNHeaders != null && authNHeaders.length > 0
+ && !hasCacheControlParameterFrom(response, AUTH_CACHEABLE_PARAMS)) {
+ return false;
+ }
+ }
+
+ final String method = request.getRequestLine().getMethod();
+ return isResponseCacheable(method, response);
+ }
+
+ private boolean expiresHeaderLessOrEqualToDateHeaderAndNoCacheControl(
+ final HttpResponse response) {
+ if (response.getFirstHeader(HeaderConstants.CACHE_CONTROL) != null) {
+ return false;
+ }
+ final Header expiresHdr = response.getFirstHeader(HeaderConstants.EXPIRES);
+ final Header dateHdr = response.getFirstHeader(HTTP.DATE_HEADER);
+ if (expiresHdr == null || dateHdr == null) {
+ return false;
+ }
+ final Date expires = DateUtils.parseDate(expiresHdr.getValue());
+ final Date date = DateUtils.parseDate(dateHdr.getValue());
+ if (expires == null || date == null) {
+ return false;
+ }
+ return expires.equals(date) || expires.before(date);
+ }
+
+ private boolean from1_0Origin(final HttpResponse response) {
+ final Header via = response.getFirstHeader(HeaderConstants.VIA);
+ if (via != null) {
+ for(final HeaderElement elt : via.getElements()) {
+ final String proto = elt.toString().split("\\s")[0];
+ if (proto.contains("/")) {
+ return proto.equals("HTTP/1.0");
+ } else {
+ return proto.equals("1.0");
+ }
+ }
+ }
+ return HttpVersion.HTTP_1_0.equals(response.getProtocolVersion());
+ }
+
+ private boolean requestProtocolGreaterThanAccepted(final HttpRequest req) {
+ return req.getProtocolVersion().compareToVersion(HttpVersion.HTTP_1_1) > 0;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ResponseProtocolCompliance.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ResponseProtocolCompliance.java
new file mode 100644
index 000000000..7f5ebb483
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ResponseProtocolCompliance.java
@@ -0,0 +1,251 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HeaderElement;
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpStatus;
+import ch.boye.httpclientandroidlib.HttpVersion;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.ClientProtocolException;
+import ch.boye.httpclientandroidlib.client.cache.HeaderConstants;
+import ch.boye.httpclientandroidlib.client.methods.HttpRequestWrapper;
+import ch.boye.httpclientandroidlib.client.utils.DateUtils;
+import ch.boye.httpclientandroidlib.message.BasicHeader;
+import ch.boye.httpclientandroidlib.protocol.HTTP;
+
+/**
+ * @since 4.1
+ */
+@Immutable
+class ResponseProtocolCompliance {
+
+ private static final String UNEXPECTED_100_CONTINUE = "The incoming request did not contain a "
+ + "100-continue header, but the response was a Status 100, continue.";
+ private static final String UNEXPECTED_PARTIAL_CONTENT = "partial content was returned for a request that did not ask for it";
+
+ /**
+ * When we get a response from a down stream server (Origin Server)
+ * we attempt to see if it is HTTP 1.1 Compliant and if not, attempt to
+ * make it so.
+ *
+ * @param request The {@link HttpRequest} that generated an origin hit and response
+ * @param response The {@link HttpResponse} from the origin server
+ * @throws IOException Bad things happened
+ */
+ public void ensureProtocolCompliance(final HttpRequestWrapper request, final HttpResponse response)
+ throws IOException {
+ if (backendResponseMustNotHaveBody(request, response)) {
+ consumeBody(response);
+ response.setEntity(null);
+ }
+
+ requestDidNotExpect100ContinueButResponseIsOne(request, response);
+
+ transferEncodingIsNotReturnedTo1_0Client(request, response);
+
+ ensurePartialContentIsNotSentToAClientThatDidNotRequestIt(request, response);
+
+ ensure200ForOPTIONSRequestWithNoBodyHasContentLengthZero(request, response);
+
+ ensure206ContainsDateHeader(response);
+
+ ensure304DoesNotContainExtraEntityHeaders(response);
+
+ identityIsNotUsedInContentEncoding(response);
+
+ warningsWithNonMatchingWarnDatesAreRemoved(response);
+ }
+
+ private void consumeBody(final HttpResponse response) throws IOException {
+ final HttpEntity body = response.getEntity();
+ if (body != null) {
+ IOUtils.consume(body);
+ }
+ }
+
+ private void warningsWithNonMatchingWarnDatesAreRemoved(
+ final HttpResponse response) {
+ final Date responseDate = DateUtils.parseDate(response.getFirstHeader(HTTP.DATE_HEADER).getValue());
+ if (responseDate == null) {
+ return;
+ }
+
+ final Header[] warningHeaders = response.getHeaders(HeaderConstants.WARNING);
+
+ if (warningHeaders == null || warningHeaders.length == 0) {
+ return;
+ }
+
+ final List newWarningHeaders = new ArrayList();
+ boolean modified = false;
+ for(final Header h : warningHeaders) {
+ for(final WarningValue wv : WarningValue.getWarningValues(h)) {
+ final Date warnDate = wv.getWarnDate();
+ if (warnDate == null || warnDate.equals(responseDate)) {
+ newWarningHeaders.add(new BasicHeader(HeaderConstants.WARNING,wv.toString()));
+ } else {
+ modified = true;
+ }
+ }
+ }
+ if (modified) {
+ response.removeHeaders(HeaderConstants.WARNING);
+ for(final Header h : newWarningHeaders) {
+ response.addHeader(h);
+ }
+ }
+ }
+
+ private void identityIsNotUsedInContentEncoding(final HttpResponse response) {
+ final Header[] hdrs = response.getHeaders(HTTP.CONTENT_ENCODING);
+ if (hdrs == null || hdrs.length == 0) {
+ return;
+ }
+ final List newHeaders = new ArrayList();
+ boolean modified = false;
+ for (final Header h : hdrs) {
+ final StringBuilder buf = new StringBuilder();
+ boolean first = true;
+ for (final HeaderElement elt : h.getElements()) {
+ if ("identity".equalsIgnoreCase(elt.getName())) {
+ modified = true;
+ } else {
+ if (!first) {
+ buf.append(",");
+ }
+ buf.append(elt.toString());
+ first = false;
+ }
+ }
+ final String newHeaderValue = buf.toString();
+ if (!"".equals(newHeaderValue)) {
+ newHeaders.add(new BasicHeader(HTTP.CONTENT_ENCODING, newHeaderValue));
+ }
+ }
+ if (!modified) {
+ return;
+ }
+ response.removeHeaders(HTTP.CONTENT_ENCODING);
+ for (final Header h : newHeaders) {
+ response.addHeader(h);
+ }
+ }
+
+ private void ensure206ContainsDateHeader(final HttpResponse response) {
+ if (response.getFirstHeader(HTTP.DATE_HEADER) == null) {
+ response.addHeader(HTTP.DATE_HEADER, DateUtils.formatDate(new Date()));
+ }
+
+ }
+
+ private void ensurePartialContentIsNotSentToAClientThatDidNotRequestIt(final HttpRequest request,
+ final HttpResponse response) throws IOException {
+ if (request.getFirstHeader(HeaderConstants.RANGE) != null
+ || response.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT) {
+ return;
+ }
+
+ consumeBody(response);
+ throw new ClientProtocolException(UNEXPECTED_PARTIAL_CONTENT);
+ }
+
+ private void ensure200ForOPTIONSRequestWithNoBodyHasContentLengthZero(final HttpRequest request,
+ final HttpResponse response) {
+ if (!request.getRequestLine().getMethod().equalsIgnoreCase(HeaderConstants.OPTIONS_METHOD)) {
+ return;
+ }
+
+ if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
+ return;
+ }
+
+ if (response.getFirstHeader(HTTP.CONTENT_LEN) == null) {
+ response.addHeader(HTTP.CONTENT_LEN, "0");
+ }
+ }
+
+ private void ensure304DoesNotContainExtraEntityHeaders(final HttpResponse response) {
+ final String[] disallowedEntityHeaders = { HeaderConstants.ALLOW, HTTP.CONTENT_ENCODING,
+ "Content-Language", HTTP.CONTENT_LEN, "Content-MD5",
+ "Content-Range", HTTP.CONTENT_TYPE, HeaderConstants.LAST_MODIFIED
+ };
+ if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
+ for(final String hdr : disallowedEntityHeaders) {
+ response.removeHeaders(hdr);
+ }
+ }
+ }
+
+ private boolean backendResponseMustNotHaveBody(final HttpRequest request, final HttpResponse backendResponse) {
+ return HeaderConstants.HEAD_METHOD.equals(request.getRequestLine().getMethod())
+ || backendResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT
+ || backendResponse.getStatusLine().getStatusCode() == HttpStatus.SC_RESET_CONTENT
+ || backendResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED;
+ }
+
+ private void requestDidNotExpect100ContinueButResponseIsOne(final HttpRequestWrapper request,
+ final HttpResponse response) throws IOException {
+ if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CONTINUE) {
+ return;
+ }
+
+ final HttpRequest originalRequest = request.getOriginal();
+ if (originalRequest instanceof HttpEntityEnclosingRequest) {
+ if (((HttpEntityEnclosingRequest)originalRequest).expectContinue()) {
+ return;
+ }
+ }
+ consumeBody(response);
+ throw new ClientProtocolException(UNEXPECTED_100_CONTINUE);
+ }
+
+ private void transferEncodingIsNotReturnedTo1_0Client(final HttpRequestWrapper request,
+ final HttpResponse response) {
+ final HttpRequest originalRequest = request.getOriginal();
+ if (originalRequest.getProtocolVersion().compareToVersion(HttpVersion.HTTP_1_1) >= 0) {
+ return;
+ }
+
+ removeResponseTransferEncoding(response);
+ }
+
+ private void removeResponseTransferEncoding(final HttpResponse response) {
+ response.removeHeaders("TE");
+ response.removeHeaders(HTTP.TRANSFER_ENCODING);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ResponseProxyHandler.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ResponseProxyHandler.java
new file mode 100644
index 000000000..a541b2778
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/ResponseProxyHandler.java
@@ -0,0 +1,88 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+
+/**
+ * A proxy class that can enhance an arbitrary {@link HttpResponse} with
+ * {@link Closeable#close()} method.
+ *
+ * @since 4.3
+ */
+@NotThreadSafe
+class ResponseProxyHandler implements InvocationHandler {
+
+ private static final Method CLOSE_METHOD;
+
+ static {
+ try {
+ CLOSE_METHOD = Closeable.class.getMethod("close");
+ } catch (final NoSuchMethodException ex) {
+ throw new Error(ex);
+ }
+ }
+
+ private final HttpResponse original;
+
+ ResponseProxyHandler(final HttpResponse original) {
+ super();
+ this.original = original;
+ }
+
+ public void close() throws IOException {
+ IOUtils.consume(original.getEntity());
+ }
+
+ public Object invoke(
+ final Object proxy, final Method method, final Object[] args) throws Throwable {
+ if (method.equals(CLOSE_METHOD)) {
+ close();
+ return null;
+ } else {
+ try {
+ return method.invoke(this.original, args);
+ } catch (final InvocationTargetException ex) {
+ final Throwable cause = ex.getCause();
+ if (cause != null) {
+ throw cause;
+ } else {
+ throw ex;
+ }
+ }
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/SchedulingStrategy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/SchedulingStrategy.java
new file mode 100644
index 000000000..0940fbc83
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/SchedulingStrategy.java
@@ -0,0 +1,45 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.Closeable;
+
+/**
+ * Specifies when revalidation requests are scheduled.
+ *
+ * @since 4.3
+ */
+public interface SchedulingStrategy extends Closeable
+{
+ /**
+ * Schedule an {@link AsynchronousValidationRequest} to be executed.
+ *
+ * @param revalidationRequest the request to be executed; not null
+ * @throws java.util.concurrent.RejectedExecutionException if the request could not be scheduled for execution
+ */
+ void schedule(AsynchronousValidationRequest revalidationRequest);
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/SizeLimitedResponseReader.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/SizeLimitedResponseReader.java
new file mode 100644
index 000000000..4c36ebb48
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/SizeLimitedResponseReader.java
@@ -0,0 +1,150 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Proxy;
+
+import ch.boye.httpclientandroidlib.HttpEntity;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.client.cache.InputLimit;
+import ch.boye.httpclientandroidlib.client.cache.Resource;
+import ch.boye.httpclientandroidlib.client.cache.ResourceFactory;
+import ch.boye.httpclientandroidlib.client.methods.CloseableHttpResponse;
+import ch.boye.httpclientandroidlib.message.BasicHttpResponse;
+
+/**
+ * @since 4.1
+ */
+@NotThreadSafe
+class SizeLimitedResponseReader {
+
+ private final ResourceFactory resourceFactory;
+ private final long maxResponseSizeBytes;
+ private final HttpRequest request;
+ private final CloseableHttpResponse response;
+
+ private InputStream instream;
+ private InputLimit limit;
+ private Resource resource;
+ private boolean consumed;
+
+ /**
+ * Create an {@link HttpResponse} that is limited in size, this allows for checking
+ * the size of objects that will be stored in the cache.
+ */
+ public SizeLimitedResponseReader(
+ final ResourceFactory resourceFactory,
+ final long maxResponseSizeBytes,
+ final HttpRequest request,
+ final CloseableHttpResponse response) {
+ super();
+ this.resourceFactory = resourceFactory;
+ this.maxResponseSizeBytes = maxResponseSizeBytes;
+ this.request = request;
+ this.response = response;
+ }
+
+ protected void readResponse() throws IOException {
+ if (!consumed) {
+ doConsume();
+ }
+ }
+
+ private void ensureNotConsumed() {
+ if (consumed) {
+ throw new IllegalStateException("Response has already been consumed");
+ }
+ }
+
+ private void ensureConsumed() {
+ if (!consumed) {
+ throw new IllegalStateException("Response has not been consumed");
+ }
+ }
+
+ private void doConsume() throws IOException {
+ ensureNotConsumed();
+ consumed = true;
+
+ limit = new InputLimit(maxResponseSizeBytes);
+
+ final HttpEntity entity = response.getEntity();
+ if (entity == null) {
+ return;
+ }
+ final String uri = request.getRequestLine().getUri();
+ instream = entity.getContent();
+ try {
+ resource = resourceFactory.generate(uri, instream, limit);
+ } finally {
+ if (!limit.isReached()) {
+ instream.close();
+ }
+ }
+ }
+
+ boolean isLimitReached() {
+ ensureConsumed();
+ return limit.isReached();
+ }
+
+ Resource getResource() {
+ ensureConsumed();
+ return resource;
+ }
+
+ CloseableHttpResponse getReconstructedResponse() throws IOException {
+ ensureConsumed();
+ final HttpResponse reconstructed = new BasicHttpResponse(response.getStatusLine());
+ reconstructed.setHeaders(response.getAllHeaders());
+
+ final CombinedEntity combinedEntity = new CombinedEntity(resource, instream);
+ final HttpEntity entity = response.getEntity();
+ if (entity != null) {
+ combinedEntity.setContentType(entity.getContentType());
+ combinedEntity.setContentEncoding(entity.getContentEncoding());
+ combinedEntity.setChunked(entity.isChunked());
+ }
+ reconstructed.setEntity(combinedEntity);
+ return (CloseableHttpResponse) Proxy.newProxyInstance(
+ ResponseProxyHandler.class.getClassLoader(),
+ new Class>[] { CloseableHttpResponse.class },
+ new ResponseProxyHandler(reconstructed) {
+
+ @Override
+ public void close() throws IOException {
+ response.close();
+ }
+
+ });
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/Variant.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/Variant.java
new file mode 100644
index 000000000..f631b0211
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/Variant.java
@@ -0,0 +1,55 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import ch.boye.httpclientandroidlib.client.cache.HttpCacheEntry;
+
+/** Records a set of information describing a cached variant. */
+class Variant {
+
+ private final String variantKey;
+ private final String cacheKey;
+ private final HttpCacheEntry entry;
+
+ public Variant(final String variantKey, final String cacheKey, final HttpCacheEntry entry) {
+ this.variantKey = variantKey;
+ this.cacheKey = cacheKey;
+ this.entry = entry;
+ }
+
+ public String getVariantKey() {
+ return variantKey;
+ }
+
+ public String getCacheKey() {
+ return cacheKey;
+ }
+
+ public HttpCacheEntry getEntry() {
+ return entry;
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/WarningValue.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/WarningValue.java
new file mode 100644
index 000000000..a3c2ce67d
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/cache/WarningValue.java
@@ -0,0 +1,370 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client.cache;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.client.utils.DateUtils;
+
+/** This class provides for parsing and understanding Warning headers. As
+ * the Warning header can be multi-valued, but the values can contain
+ * separators like commas inside quoted strings, we cannot use the regular
+ * {@link Header#getElements()} call to access the values.
+ */
+class WarningValue {
+
+ private int offs;
+ private int init_offs;
+ private final String src;
+ private int warnCode;
+ private String warnAgent;
+ private String warnText;
+ private Date warnDate;
+
+ WarningValue(final String s) {
+ this(s, 0);
+ }
+
+ WarningValue(final String s, final int offs) {
+ this.offs = this.init_offs = offs;
+ this.src = s;
+ consumeWarnValue();
+ }
+
+ /** Returns an array of the parseable warning values contained
+ * in the given header value, which is assumed to be a
+ * Warning header. Improperly formatted warning values will be
+ * skipped, in keeping with the philosophy of "ignore what you
+ * cannot understand."
+ * @param h Warning {@link Header} to parse
+ * @return array of WarnValue objects
+ */
+ public static WarningValue[] getWarningValues(final Header h) {
+ final List out = new ArrayList();
+ final String src = h.getValue();
+ int offs = 0;
+ while(offs < src.length()) {
+ try {
+ final WarningValue wv = new WarningValue(src, offs);
+ out.add(wv);
+ offs = wv.offs;
+ } catch (final IllegalArgumentException e) {
+ final int nextComma = src.indexOf(',', offs);
+ if (nextComma == -1) {
+ break;
+ }
+ offs = nextComma + 1;
+ }
+ }
+ final WarningValue[] wvs = {};
+ return out.toArray(wvs);
+ }
+
+ /*
+ * LWS = [CRLF] 1*( SP | HT )
+ * CRLF = CR LF
+ */
+ protected void consumeLinearWhitespace() {
+ while(offs < src.length()) {
+ switch(src.charAt(offs)) {
+ case '\r':
+ if (offs+2 >= src.length()
+ || src.charAt(offs+1) != '\n'
+ || (src.charAt(offs+2) != ' '
+ && src.charAt(offs+2) != '\t')) {
+ return;
+ }
+ offs += 2;
+ break;
+ case ' ':
+ case '\t':
+ break;
+ default:
+ return;
+ }
+ offs++;
+ }
+ }
+
+ /*
+ * CHAR =
+ */
+ private boolean isChar(final char c) {
+ final int i = c;
+ return (i >= 0 && i <= 127);
+ }
+
+ /*
+ * CTL =
+ */
+ private boolean isControl(final char c) {
+ final int i = c;
+ return (i == 127 || (i >=0 && i <= 31));
+ }
+
+ /*
+ * separators = "(" | ")" | "<" | ">" | "@"
+ * | "," | ";" | ":" | "\" | <">
+ * | "/" | "[" | "]" | "?" | "="
+ * | "{" | "}" | SP | HT
+ */
+ private boolean isSeparator(final char c) {
+ return (c == '(' || c == ')' || c == '<' || c == '>'
+ || c == '@' || c == ',' || c == ';' || c == ':'
+ || c == '\\' || c == '\"' || c == '/'
+ || c == '[' || c == ']' || c == '?' || c == '='
+ || c == '{' || c == '}' || c == ' ' || c == '\t');
+ }
+
+ /*
+ * token = 1*
+ */
+ protected void consumeToken() {
+ if (!isTokenChar(src.charAt(offs))) {
+ parseError();
+ }
+ while(offs < src.length()) {
+ if (!isTokenChar(src.charAt(offs))) {
+ break;
+ }
+ offs++;
+ }
+ }
+
+ private boolean isTokenChar(final char c) {
+ return (isChar(c) && !isControl(c) && !isSeparator(c));
+ }
+
+ private static final String TOPLABEL = "\\p{Alpha}([\\p{Alnum}-]*\\p{Alnum})?";
+ private static final String DOMAINLABEL = "\\p{Alnum}([\\p{Alnum}-]*\\p{Alnum})?";
+ private static final String HOSTNAME = "(" + DOMAINLABEL + "\\.)*" + TOPLABEL + "\\.?";
+ private static final String IPV4ADDRESS = "\\d+\\.\\d+\\.\\d+\\.\\d+";
+ private static final String HOST = "(" + HOSTNAME + ")|(" + IPV4ADDRESS + ")";
+ private static final String PORT = "\\d*";
+ private static final String HOSTPORT = "(" + HOST + ")(\\:" + PORT + ")?";
+ private static final Pattern HOSTPORT_PATTERN = Pattern.compile(HOSTPORT);
+
+ protected void consumeHostPort() {
+ final Matcher m = HOSTPORT_PATTERN.matcher(src.substring(offs));
+ if (!m.find()) {
+ parseError();
+ }
+ if (m.start() != 0) {
+ parseError();
+ }
+ offs += m.end();
+ }
+
+
+ /*
+ * warn-agent = ( host [ ":" port ] ) | pseudonym
+ * pseudonym = token
+ */
+ protected void consumeWarnAgent() {
+ final int curr_offs = offs;
+ try {
+ consumeHostPort();
+ warnAgent = src.substring(curr_offs, offs);
+ consumeCharacter(' ');
+ return;
+ } catch (final IllegalArgumentException e) {
+ offs = curr_offs;
+ }
+ consumeToken();
+ warnAgent = src.substring(curr_offs, offs);
+ consumeCharacter(' ');
+ }
+
+ /*
+ * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
+ * qdtext = >
+ */
+ protected void consumeQuotedString() {
+ if (src.charAt(offs) != '\"') {
+ parseError();
+ }
+ offs++;
+ boolean foundEnd = false;
+ while(offs < src.length() && !foundEnd) {
+ final char c = src.charAt(offs);
+ if (offs + 1 < src.length() && c == '\\'
+ && isChar(src.charAt(offs+1))) {
+ offs += 2; // consume quoted-pair
+ } else if (c == '\"') {
+ foundEnd = true;
+ offs++;
+ } else if (c != '\"' && !isControl(c)) {
+ offs++;
+ } else {
+ parseError();
+ }
+ }
+ if (!foundEnd) {
+ parseError();
+ }
+ }
+
+ /*
+ * warn-text = quoted-string
+ */
+ protected void consumeWarnText() {
+ final int curr = offs;
+ consumeQuotedString();
+ warnText = src.substring(curr, offs);
+ }
+
+ private static final String MONTH = "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec";
+ private static final String WEEKDAY = "Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday";
+ private static final String WKDAY = "Mon|Tue|Wed|Thu|Fri|Sat|Sun";
+ private static final String TIME = "\\d{2}:\\d{2}:\\d{2}";
+ private static final String DATE3 = "(" + MONTH + ") ( |\\d)\\d";
+ private static final String DATE2 = "\\d{2}-(" + MONTH + ")-\\d{2}";
+ private static final String DATE1 = "\\d{2} (" + MONTH + ") \\d{4}";
+ private static final String ASCTIME_DATE = "(" + WKDAY + ") (" + DATE3 + ") (" + TIME + ") \\d{4}";
+ private static final String RFC850_DATE = "(" + WEEKDAY + "), (" + DATE2 + ") (" + TIME + ") GMT";
+ private static final String RFC1123_DATE = "(" + WKDAY + "), (" + DATE1 + ") (" + TIME + ") GMT";
+ private static final String HTTP_DATE = "(" + RFC1123_DATE + ")|(" + RFC850_DATE + ")|(" + ASCTIME_DATE + ")";
+ private static final String WARN_DATE = "\"(" + HTTP_DATE + ")\"";
+ private static final Pattern WARN_DATE_PATTERN = Pattern.compile(WARN_DATE);
+
+ /*
+ * warn-date = <"> HTTP-date <">
+ */
+ protected void consumeWarnDate() {
+ final int curr = offs;
+ final Matcher m = WARN_DATE_PATTERN.matcher(src.substring(offs));
+ if (!m.lookingAt()) {
+ parseError();
+ }
+ offs += m.end();
+ warnDate = DateUtils.parseDate(src.substring(curr+1,offs-1));
+ }
+
+ /*
+ * warning-value = warn-code SP warn-agent SP warn-text [SP warn-date]
+ */
+ protected void consumeWarnValue() {
+ consumeLinearWhitespace();
+ consumeWarnCode();
+ consumeWarnAgent();
+ consumeWarnText();
+ if (offs + 1 < src.length() && src.charAt(offs) == ' ' && src.charAt(offs+1) == '\"') {
+ consumeCharacter(' ');
+ consumeWarnDate();
+ }
+ consumeLinearWhitespace();
+ if (offs != src.length()) {
+ consumeCharacter(',');
+ }
+ }
+
+ protected void consumeCharacter(final char c) {
+ if (offs + 1 > src.length()
+ || c != src.charAt(offs)) {
+ parseError();
+ }
+ offs++;
+ }
+
+ /*
+ * warn-code = 3DIGIT
+ */
+ protected void consumeWarnCode() {
+ if (offs + 4 > src.length()
+ || !Character.isDigit(src.charAt(offs))
+ || !Character.isDigit(src.charAt(offs + 1))
+ || !Character.isDigit(src.charAt(offs + 2))
+ || src.charAt(offs + 3) != ' ') {
+ parseError();
+ }
+ warnCode = Integer.parseInt(src.substring(offs,offs+3));
+ offs += 4;
+ }
+
+ private void parseError() {
+ final String s = src.substring(init_offs);
+ throw new IllegalArgumentException("Bad warn code \"" + s + "\"");
+ }
+
+ /** Returns the 3-digit code associated with this warning.
+ * @return int
+ */
+ public int getWarnCode() { return warnCode; }
+
+ /** Returns the "warn-agent" string associated with this warning,
+ * which is either the name or pseudonym of the server that added
+ * this particular Warning header.
+ * @return {@link String}
+ */
+ public String getWarnAgent() { return warnAgent; }
+
+ /** Returns the human-readable warning text for this warning. Note
+ * that the original quoted-string is returned here, including
+ * escaping for any contained characters. In other words, if the
+ * header was:
+ *
+ * Warning: 110 fred "Response is stale"
+ *
+ * then this method will return "\"Response is stale\""
+ * (surrounding quotes included).
+ * @return {@link String}
+ */
+ public String getWarnText() { return warnText; }
+
+ /** Returns the date and time when this warning was added, or
+ * null if a warning date was not supplied in the
+ * header.
+ * @return {@link Date}
+ */
+ public Date getWarnDate() { return warnDate; }
+
+ /** Formats a WarningValue as a {@link String}
+ * suitable for including in a header. For example, you can:
+ *
+This package contains a cache module that can be used for HTTP/1.1
+client-side caching. The primary classes in this package are the
+{@link org.apache.http.impl.client.cache.CachingHttpClient},
+which is a drop-in replacement for
+a {@link org.apache.http.impl.client.DefaultHttpClient} that adds
+caching, and the {@link org.apache.http.impl.client.cache.CacheConfig}
+class that can be used for configuring it.
+
+
+
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/package-info.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/package-info.java
new file mode 100644
index 000000000..1efbf4cec
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/client/package-info.java
@@ -0,0 +1,51 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+/**
+ * Default HTTP client implementation.
+ *
+ * The usual execution flow can be demonstrated by the code snippet below:
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.client;
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/AbstractClientConnAdapter.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/AbstractClientConnAdapter.java
new file mode 100644
index 000000000..ea2524f6a
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/AbstractClientConnAdapter.java
@@ -0,0 +1,369 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.util.concurrent.TimeUnit;
+
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocket;
+
+import ch.boye.httpclientandroidlib.HttpConnectionMetrics;
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
+import ch.boye.httpclientandroidlib.conn.ManagedClientConnection;
+import ch.boye.httpclientandroidlib.conn.OperatedClientConnection;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+/**
+ * Abstract adapter from {@link OperatedClientConnection operated} to
+ * {@link ManagedClientConnection managed} client connections.
+ * Read and write methods are delegated to the wrapped connection.
+ * Operations affecting the connection state have to be implemented
+ * by derived classes. Operations for querying the connection state
+ * are delegated to the wrapped connection if there is one, or
+ * return a default value if there is none.
+ *
+ * This adapter tracks the checkpoints for reusable communication states,
+ * as indicated by {@link #markReusable markReusable} and queried by
+ * {@link #isMarkedReusable isMarkedReusable}.
+ * All send and receive operations will automatically clear the mark.
+ *
+ * Connection release calls are delegated to the connection manager,
+ * if there is one. {@link #abortConnection abortConnection} will
+ * clear the reusability mark first. The connection manager is
+ * expected to tolerate multiple calls to the release method.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.2) do not use
+ */
+@Deprecated
+@NotThreadSafe
+public abstract class AbstractClientConnAdapter implements ManagedClientConnection, HttpContext {
+
+ /**
+ * The connection manager.
+ */
+ private final ClientConnectionManager connManager;
+
+ /** The wrapped connection. */
+ private volatile OperatedClientConnection wrappedConnection;
+
+ /** The reusability marker. */
+ private volatile boolean markedReusable;
+
+ /** True if the connection has been shut down or released. */
+ private volatile boolean released;
+
+ /** The duration this is valid for while idle (in ms). */
+ private volatile long duration;
+
+ /**
+ * Creates a new connection adapter.
+ * The adapter is initially not
+ * {@link #isMarkedReusable marked} as reusable.
+ *
+ * @param mgr the connection manager, or null
+ * @param conn the connection to wrap, or null
+ */
+ protected AbstractClientConnAdapter(final ClientConnectionManager mgr,
+ final OperatedClientConnection conn) {
+ super();
+ connManager = mgr;
+ wrappedConnection = conn;
+ markedReusable = false;
+ released = false;
+ duration = Long.MAX_VALUE;
+ }
+
+ /**
+ * Detaches this adapter from the wrapped connection.
+ * This adapter becomes useless.
+ */
+ protected synchronized void detach() {
+ wrappedConnection = null;
+ duration = Long.MAX_VALUE;
+ }
+
+ protected OperatedClientConnection getWrappedConnection() {
+ return wrappedConnection;
+ }
+
+ protected ClientConnectionManager getManager() {
+ return connManager;
+ }
+
+ /**
+ * @deprecated (4.1) use {@link #assertValid(OperatedClientConnection)}
+ */
+ @Deprecated
+ protected final void assertNotAborted() throws InterruptedIOException {
+ if (isReleased()) {
+ throw new InterruptedIOException("Connection has been shut down");
+ }
+ }
+
+ /**
+ * @since 4.1
+ * @return value of released flag
+ */
+ protected boolean isReleased() {
+ return released;
+ }
+
+ /**
+ * Asserts that there is a valid wrapped connection to delegate to.
+ *
+ * @throws ConnectionShutdownException if there is no wrapped connection
+ * or connection has been aborted
+ */
+ protected final void assertValid(
+ final OperatedClientConnection wrappedConn) throws ConnectionShutdownException {
+ if (isReleased() || wrappedConn == null) {
+ throw new ConnectionShutdownException();
+ }
+ }
+
+ public boolean isOpen() {
+ final OperatedClientConnection conn = getWrappedConnection();
+ if (conn == null) {
+ return false;
+ }
+
+ return conn.isOpen();
+ }
+
+ public boolean isStale() {
+ if (isReleased()) {
+ return true;
+ }
+ final OperatedClientConnection conn = getWrappedConnection();
+ if (conn == null) {
+ return true;
+ }
+
+ return conn.isStale();
+ }
+
+ public void setSocketTimeout(final int timeout) {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ conn.setSocketTimeout(timeout);
+ }
+
+ public int getSocketTimeout() {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ return conn.getSocketTimeout();
+ }
+
+ public HttpConnectionMetrics getMetrics() {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ return conn.getMetrics();
+ }
+
+ public void flush() throws IOException {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ conn.flush();
+ }
+
+ public boolean isResponseAvailable(final int timeout) throws IOException {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ return conn.isResponseAvailable(timeout);
+ }
+
+ public void receiveResponseEntity(final HttpResponse response)
+ throws HttpException, IOException {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ unmarkReusable();
+ conn.receiveResponseEntity(response);
+ }
+
+ public HttpResponse receiveResponseHeader()
+ throws HttpException, IOException {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ unmarkReusable();
+ return conn.receiveResponseHeader();
+ }
+
+ public void sendRequestEntity(final HttpEntityEnclosingRequest request)
+ throws HttpException, IOException {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ unmarkReusable();
+ conn.sendRequestEntity(request);
+ }
+
+ public void sendRequestHeader(final HttpRequest request)
+ throws HttpException, IOException {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ unmarkReusable();
+ conn.sendRequestHeader(request);
+ }
+
+ public InetAddress getLocalAddress() {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ return conn.getLocalAddress();
+ }
+
+ public int getLocalPort() {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ return conn.getLocalPort();
+ }
+
+ public InetAddress getRemoteAddress() {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ return conn.getRemoteAddress();
+ }
+
+ public int getRemotePort() {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ return conn.getRemotePort();
+ }
+
+ public boolean isSecure() {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ return conn.isSecure();
+ }
+
+ public void bind(final Socket socket) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ public Socket getSocket() {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ if (!isOpen()) {
+ return null;
+ }
+ return conn.getSocket();
+ }
+
+ public SSLSession getSSLSession() {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ if (!isOpen()) {
+ return null;
+ }
+
+ SSLSession result = null;
+ final Socket sock = conn.getSocket();
+ if (sock instanceof SSLSocket) {
+ result = ((SSLSocket)sock).getSession();
+ }
+ return result;
+ }
+
+ public void markReusable() {
+ markedReusable = true;
+ }
+
+ public void unmarkReusable() {
+ markedReusable = false;
+ }
+
+ public boolean isMarkedReusable() {
+ return markedReusable;
+ }
+
+ public void setIdleDuration(final long duration, final TimeUnit unit) {
+ if(duration > 0) {
+ this.duration = unit.toMillis(duration);
+ } else {
+ this.duration = -1;
+ }
+ }
+
+ public synchronized void releaseConnection() {
+ if (released) {
+ return;
+ }
+ released = true;
+ connManager.releaseConnection(this, duration, TimeUnit.MILLISECONDS);
+ }
+
+ public synchronized void abortConnection() {
+ if (released) {
+ return;
+ }
+ released = true;
+ unmarkReusable();
+ try {
+ shutdown();
+ } catch (final IOException ignore) {
+ }
+ connManager.releaseConnection(this, duration, TimeUnit.MILLISECONDS);
+ }
+
+ public Object getAttribute(final String id) {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ if (conn instanceof HttpContext) {
+ return ((HttpContext) conn).getAttribute(id);
+ } else {
+ return null;
+ }
+ }
+
+ public Object removeAttribute(final String id) {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ if (conn instanceof HttpContext) {
+ return ((HttpContext) conn).removeAttribute(id);
+ } else {
+ return null;
+ }
+ }
+
+ public void setAttribute(final String id, final Object obj) {
+ final OperatedClientConnection conn = getWrappedConnection();
+ assertValid(conn);
+ if (conn instanceof HttpContext) {
+ ((HttpContext) conn).setAttribute(id, obj);
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/AbstractPoolEntry.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/AbstractPoolEntry.java
new file mode 100644
index 000000000..cbbe727b5
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/AbstractPoolEntry.java
@@ -0,0 +1,262 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionOperator;
+import ch.boye.httpclientandroidlib.conn.OperatedClientConnection;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.conn.routing.RouteTracker;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.Asserts;
+
+/**
+ * A pool entry for use by connection manager implementations.
+ * Pool entries work in conjunction with an
+ * {@link AbstractClientConnAdapter adapter}.
+ * The adapter is handed out to applications that obtain a connection.
+ * The pool entry stores the underlying connection and tracks the
+ * {@link HttpRoute route} established.
+ * The adapter delegates methods for establishing the route to
+ * its pool entry.
+ *
+ * If the managed connections is released or revoked, the adapter
+ * gets disconnected, but the pool entry still contains the
+ * underlying connection and the established route.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.2) do not use
+ */
+@Deprecated
+public abstract class AbstractPoolEntry {
+
+ /** The connection operator. */
+ protected final ClientConnectionOperator connOperator;
+
+ /** The underlying connection being pooled or used. */
+ protected final OperatedClientConnection connection;
+
+ /** The route for which this entry gets allocated. */
+ //@@@ currently accessed from connection manager(s) as attribute
+ //@@@ avoid that, derived classes should decide whether update is allowed
+ //@@@ SCCM: yes, TSCCM: no
+ protected volatile HttpRoute route;
+
+ /** Connection state object */
+ protected volatile Object state;
+
+ /** The tracked route, or null before tracking starts. */
+ protected volatile RouteTracker tracker;
+
+
+ /**
+ * Creates a new pool entry.
+ *
+ * @param connOperator the Connection Operator for this entry
+ * @param route the planned route for the connection,
+ * or null
+ */
+ protected AbstractPoolEntry(final ClientConnectionOperator connOperator,
+ final HttpRoute route) {
+ super();
+ Args.notNull(connOperator, "Connection operator");
+ this.connOperator = connOperator;
+ this.connection = connOperator.createConnection();
+ this.route = route;
+ this.tracker = null;
+ }
+
+ /**
+ * Returns the state object associated with this pool entry.
+ *
+ * @return The state object
+ */
+ public Object getState() {
+ return state;
+ }
+
+ /**
+ * Assigns a state object to this pool entry.
+ *
+ * @param state The state object
+ */
+ public void setState(final Object state) {
+ this.state = state;
+ }
+
+ /**
+ * Opens the underlying connection.
+ *
+ * @param route the route along which to open the connection
+ * @param context the context for opening the connection
+ * @param params the parameters for opening the connection
+ *
+ * @throws IOException in case of a problem
+ */
+ public void open(final HttpRoute route,
+ final HttpContext context, final HttpParams params)
+ throws IOException {
+
+ Args.notNull(route, "Route");
+ Args.notNull(params, "HTTP parameters");
+ if (this.tracker != null) {
+ Asserts.check(!this.tracker.isConnected(), "Connection already open");
+ }
+ // - collect the arguments
+ // - call the operator
+ // - update the tracking data
+ // In this order, we can be sure that only a successful
+ // opening of the connection will be tracked.
+
+ this.tracker = new RouteTracker(route);
+ final HttpHost proxy = route.getProxyHost();
+
+ connOperator.openConnection
+ (this.connection,
+ (proxy != null) ? proxy : route.getTargetHost(),
+ route.getLocalAddress(),
+ context, params);
+
+ final RouteTracker localTracker = tracker; // capture volatile
+
+ // If this tracker was reset while connecting,
+ // fail early.
+ if (localTracker == null) {
+ throw new InterruptedIOException("Request aborted");
+ }
+
+ if (proxy == null) {
+ localTracker.connectTarget(this.connection.isSecure());
+ } else {
+ localTracker.connectProxy(proxy, this.connection.isSecure());
+ }
+
+ }
+
+ /**
+ * Tracks tunnelling of the connection to the target.
+ * The tunnel has to be established outside by sending a CONNECT
+ * request to the (last) proxy.
+ *
+ * @param secure true if the tunnel should be
+ * considered secure, false otherwise
+ * @param params the parameters for tunnelling the connection
+ *
+ * @throws IOException in case of a problem
+ */
+ public void tunnelTarget(final boolean secure, final HttpParams params)
+ throws IOException {
+
+ Args.notNull(params, "HTTP parameters");
+ Asserts.notNull(this.tracker, "Route tracker");
+ Asserts.check(this.tracker.isConnected(), "Connection not open");
+ Asserts.check(!this.tracker.isTunnelled(), "Connection is already tunnelled");
+
+ this.connection.update(null, tracker.getTargetHost(),
+ secure, params);
+ this.tracker.tunnelTarget(secure);
+ }
+
+ /**
+ * Tracks tunnelling of the connection to a chained proxy.
+ * The tunnel has to be established outside by sending a CONNECT
+ * request to the previous proxy.
+ *
+ * @param next the proxy to which the tunnel was established.
+ * See {@link ch.boye.httpclientandroidlib.conn.ManagedClientConnection#tunnelProxy
+ * ManagedClientConnection.tunnelProxy}
+ * for details.
+ * @param secure true if the tunnel should be
+ * considered secure, false otherwise
+ * @param params the parameters for tunnelling the connection
+ *
+ * @throws IOException in case of a problem
+ */
+ public void tunnelProxy(final HttpHost next, final boolean secure, final HttpParams params)
+ throws IOException {
+
+ Args.notNull(next, "Next proxy");
+ Args.notNull(params, "Parameters");
+
+ Asserts.notNull(this.tracker, "Route tracker");
+ Asserts.check(this.tracker.isConnected(), "Connection not open");
+
+ this.connection.update(null, next, secure, params);
+ this.tracker.tunnelProxy(next, secure);
+ }
+
+ /**
+ * Layers a protocol on top of an established tunnel.
+ *
+ * @param context the context for layering
+ * @param params the parameters for layering
+ *
+ * @throws IOException in case of a problem
+ */
+ public void layerProtocol(final HttpContext context, final HttpParams params)
+ throws IOException {
+
+ //@@@ is context allowed to be null? depends on operator?
+ Args.notNull(params, "HTTP parameters");
+ Asserts.notNull(this.tracker, "Route tracker");
+ Asserts.check(this.tracker.isConnected(), "Connection not open");
+ Asserts.check(this.tracker.isTunnelled(), "Protocol layering without a tunnel not supported");
+ Asserts.check(!this.tracker.isLayered(), "Multiple protocol layering not supported");
+ // - collect the arguments
+ // - call the operator
+ // - update the tracking data
+ // In this order, we can be sure that only a successful
+ // layering on top of the connection will be tracked.
+
+ final HttpHost target = tracker.getTargetHost();
+
+ connOperator.updateSecureConnection(this.connection, target,
+ context, params);
+
+ this.tracker.layerProtocol(this.connection.isSecure());
+
+ }
+
+ /**
+ * Shuts down the entry.
+ *
+ * If {@link #open(HttpRoute, HttpContext, HttpParams)} is in progress,
+ * this will cause that open to possibly throw an {@link IOException}.
+ */
+ protected void shutdownEntry() {
+ tracker = null;
+ state = null;
+ }
+
+}
+
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/AbstractPooledConnAdapter.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/AbstractPooledConnAdapter.java
new file mode 100644
index 000000000..47f0feda5
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/AbstractPooledConnAdapter.java
@@ -0,0 +1,191 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
+import ch.boye.httpclientandroidlib.conn.OperatedClientConnection;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+/**
+ * Abstract adapter from pool {@link AbstractPoolEntry entries} to
+ * {@link ch.boye.httpclientandroidlib.conn.ManagedClientConnection managed}
+ * client connections.
+ * The connection in the pool entry is used to initialize the base class.
+ * In addition, methods to establish a route are delegated to the
+ * pool entry. {@link #shutdown shutdown} and {@link #close close}
+ * will clear the tracked route in the pool entry and call the
+ * respective method of the wrapped connection.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.2) do not use
+ */
+@Deprecated
+public abstract class AbstractPooledConnAdapter extends AbstractClientConnAdapter {
+
+ /** The wrapped pool entry. */
+ protected volatile AbstractPoolEntry poolEntry;
+
+ /**
+ * Creates a new connection adapter.
+ *
+ * @param manager the connection manager
+ * @param entry the pool entry for the connection being wrapped
+ */
+ protected AbstractPooledConnAdapter(final ClientConnectionManager manager,
+ final AbstractPoolEntry entry) {
+ super(manager, entry.connection);
+ this.poolEntry = entry;
+ }
+
+ public String getId() {
+ return null;
+ }
+
+ /**
+ * Obtains the pool entry.
+ *
+ * @return the pool entry, or null if detached
+ *
+ * @deprecated (4.0.1)
+ */
+ @Deprecated
+ protected AbstractPoolEntry getPoolEntry() {
+ return this.poolEntry;
+ }
+
+ /**
+ * Asserts that there is a valid pool entry.
+ *
+ * @throws ConnectionShutdownException if there is no pool entry
+ * or connection has been aborted
+ *
+ * @see #assertValid(OperatedClientConnection)
+ */
+ protected void assertValid(final AbstractPoolEntry entry) {
+ if (isReleased() || entry == null) {
+ throw new ConnectionShutdownException();
+ }
+ }
+
+ /**
+ * @deprecated (4.1) use {@link #assertValid(AbstractPoolEntry)}
+ */
+ @Deprecated
+ protected final void assertAttached() {
+ if (poolEntry == null) {
+ throw new ConnectionShutdownException();
+ }
+ }
+
+ /**
+ * Detaches this adapter from the wrapped connection.
+ * This adapter becomes useless.
+ */
+ @Override
+ protected synchronized void detach() {
+ poolEntry = null;
+ super.detach();
+ }
+
+ public HttpRoute getRoute() {
+ final AbstractPoolEntry entry = getPoolEntry();
+ assertValid(entry);
+ return (entry.tracker == null) ? null : entry.tracker.toRoute();
+ }
+
+ public void open(final HttpRoute route,
+ final HttpContext context, final HttpParams params)
+ throws IOException {
+ final AbstractPoolEntry entry = getPoolEntry();
+ assertValid(entry);
+ entry.open(route, context, params);
+ }
+
+ public void tunnelTarget(final boolean secure, final HttpParams params)
+ throws IOException {
+ final AbstractPoolEntry entry = getPoolEntry();
+ assertValid(entry);
+ entry.tunnelTarget(secure, params);
+ }
+
+ public void tunnelProxy(final HttpHost next, final boolean secure, final HttpParams params)
+ throws IOException {
+ final AbstractPoolEntry entry = getPoolEntry();
+ assertValid(entry);
+ entry.tunnelProxy(next, secure, params);
+ }
+
+ public void layerProtocol(final HttpContext context, final HttpParams params)
+ throws IOException {
+ final AbstractPoolEntry entry = getPoolEntry();
+ assertValid(entry);
+ entry.layerProtocol(context, params);
+ }
+
+ public void close() throws IOException {
+ final AbstractPoolEntry entry = getPoolEntry();
+ if (entry != null) {
+ entry.shutdownEntry();
+ }
+
+ final OperatedClientConnection conn = getWrappedConnection();
+ if (conn != null) {
+ conn.close();
+ }
+ }
+
+ public void shutdown() throws IOException {
+ final AbstractPoolEntry entry = getPoolEntry();
+ if (entry != null) {
+ entry.shutdownEntry();
+ }
+
+ final OperatedClientConnection conn = getWrappedConnection();
+ if (conn != null) {
+ conn.shutdown();
+ }
+ }
+
+ public Object getState() {
+ final AbstractPoolEntry entry = getPoolEntry();
+ assertValid(entry);
+ return entry.getState();
+ }
+
+ public void setState(final Object state) {
+ final AbstractPoolEntry entry = getPoolEntry();
+ assertValid(entry);
+ entry.setState(state);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/BasicClientConnectionManager.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/BasicClientConnectionManager.java
new file mode 100644
index 000000000..176e28150
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/BasicClientConnectionManager.java
@@ -0,0 +1,276 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.HttpClientConnection;
+import ch.boye.httpclientandroidlib.annotation.GuardedBy;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionOperator;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionRequest;
+import ch.boye.httpclientandroidlib.conn.ManagedClientConnection;
+import ch.boye.httpclientandroidlib.conn.OperatedClientConnection;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.conn.scheme.SchemeRegistry;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.Asserts;
+
+/**
+ * A connection manager for a single connection. This connection manager maintains only one active
+ * connection. Even though this class is fully thread-safe it ought to be used by one execution
+ * thread only, as only one thread a time can lease the connection at a time.
+ *
+ * This connection manager will make an effort to reuse the connection for subsequent requests
+ * with the same {@link HttpRoute route}. It will, however, close the existing connection and
+ * open it for the given route, if the route of the persistent connection does not match that
+ * of the connection request. If the connection has been already been allocated
+ * {@link IllegalStateException} is thrown.
+ *
+ * This connection manager implementation should be used inside an EJB container instead of
+ * {@link PoolingClientConnectionManager}.
+ *
+ * @since 4.2
+ *
+ * @deprecated (4.3) use {@link BasicHttpClientConnectionManager}.
+ */
+@ThreadSafe
+@Deprecated
+public class BasicClientConnectionManager implements ClientConnectionManager {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ private static final AtomicLong COUNTER = new AtomicLong();
+
+ /** The message to be logged on multiple allocation. */
+ public final static String MISUSE_MESSAGE =
+ "Invalid use of BasicClientConnManager: connection still allocated.\n" +
+ "Make sure to release the connection before allocating another one.";
+
+ /** The schemes supported by this connection manager. */
+ private final SchemeRegistry schemeRegistry;
+
+ /** The operator for opening and updating connections. */
+ private final ClientConnectionOperator connOperator;
+
+ /** The one and only entry in this pool. */
+ @GuardedBy("this")
+ private HttpPoolEntry poolEntry;
+
+ /** The currently issued managed connection, if any. */
+ @GuardedBy("this")
+ private ManagedClientConnectionImpl conn;
+
+ /** Indicates whether this connection manager is shut down. */
+ @GuardedBy("this")
+ private volatile boolean shutdown;
+
+ /**
+ * Creates a new simple connection manager.
+ *
+ * @param schreg the scheme registry
+ */
+ public BasicClientConnectionManager(final SchemeRegistry schreg) {
+ Args.notNull(schreg, "Scheme registry");
+ this.schemeRegistry = schreg;
+ this.connOperator = createConnectionOperator(schreg);
+ }
+
+ public BasicClientConnectionManager() {
+ this(SchemeRegistryFactory.createDefault());
+ }
+
+ @Override
+ protected void finalize() throws Throwable {
+ try {
+ shutdown();
+ } finally { // Make sure we call overridden method even if shutdown barfs
+ super.finalize();
+ }
+ }
+
+ public SchemeRegistry getSchemeRegistry() {
+ return this.schemeRegistry;
+ }
+
+ protected ClientConnectionOperator createConnectionOperator(final SchemeRegistry schreg) {
+ return new DefaultClientConnectionOperator(schreg);
+ }
+
+ public final ClientConnectionRequest requestConnection(
+ final HttpRoute route,
+ final Object state) {
+
+ return new ClientConnectionRequest() {
+
+ public void abortRequest() {
+ // Nothing to abort, since requests are immediate.
+ }
+
+ public ManagedClientConnection getConnection(
+ final long timeout, final TimeUnit tunit) {
+ return BasicClientConnectionManager.this.getConnection(
+ route, state);
+ }
+
+ };
+ }
+
+ private void assertNotShutdown() {
+ Asserts.check(!this.shutdown, "Connection manager has been shut down");
+ }
+
+ ManagedClientConnection getConnection(final HttpRoute route, final Object state) {
+ Args.notNull(route, "Route");
+ synchronized (this) {
+ assertNotShutdown();
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Get connection for route " + route);
+ }
+ Asserts.check(this.conn == null, MISUSE_MESSAGE);
+ if (this.poolEntry != null && !this.poolEntry.getPlannedRoute().equals(route)) {
+ this.poolEntry.close();
+ this.poolEntry = null;
+ }
+ if (this.poolEntry == null) {
+ final String id = Long.toString(COUNTER.getAndIncrement());
+ final OperatedClientConnection conn = this.connOperator.createConnection();
+ this.poolEntry = new HttpPoolEntry(this.log, id, route, conn, 0, TimeUnit.MILLISECONDS);
+ }
+ final long now = System.currentTimeMillis();
+ if (this.poolEntry.isExpired(now)) {
+ this.poolEntry.close();
+ this.poolEntry.getTracker().reset();
+ }
+ this.conn = new ManagedClientConnectionImpl(this, this.connOperator, this.poolEntry);
+ return this.conn;
+ }
+ }
+
+ private void shutdownConnection(final HttpClientConnection conn) {
+ try {
+ conn.shutdown();
+ } catch (final IOException iox) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("I/O exception shutting down connection", iox);
+ }
+ }
+ }
+
+ public void releaseConnection(final ManagedClientConnection conn, final long keepalive, final TimeUnit tunit) {
+ Args.check(conn instanceof ManagedClientConnectionImpl, "Connection class mismatch, " +
+ "connection not obtained from this manager");
+ final ManagedClientConnectionImpl managedConn = (ManagedClientConnectionImpl) conn;
+ synchronized (managedConn) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Releasing connection " + conn);
+ }
+ if (managedConn.getPoolEntry() == null) {
+ return; // already released
+ }
+ final ClientConnectionManager manager = managedConn.getManager();
+ Asserts.check(manager == this, "Connection not obtained from this manager");
+ synchronized (this) {
+ if (this.shutdown) {
+ shutdownConnection(managedConn);
+ return;
+ }
+ try {
+ if (managedConn.isOpen() && !managedConn.isMarkedReusable()) {
+ shutdownConnection(managedConn);
+ }
+ if (managedConn.isMarkedReusable()) {
+ this.poolEntry.updateExpiry(keepalive, tunit != null ? tunit : TimeUnit.MILLISECONDS);
+ if (this.log.isDebugEnabled()) {
+ final String s;
+ if (keepalive > 0) {
+ s = "for " + keepalive + " " + tunit;
+ } else {
+ s = "indefinitely";
+ }
+ this.log.debug("Connection can be kept alive " + s);
+ }
+ }
+ } finally {
+ managedConn.detach();
+ this.conn = null;
+ if (this.poolEntry.isClosed()) {
+ this.poolEntry = null;
+ }
+ }
+ }
+ }
+ }
+
+ public void closeExpiredConnections() {
+ synchronized (this) {
+ assertNotShutdown();
+ final long now = System.currentTimeMillis();
+ if (this.poolEntry != null && this.poolEntry.isExpired(now)) {
+ this.poolEntry.close();
+ this.poolEntry.getTracker().reset();
+ }
+ }
+ }
+
+ public void closeIdleConnections(final long idletime, final TimeUnit tunit) {
+ Args.notNull(tunit, "Time unit");
+ synchronized (this) {
+ assertNotShutdown();
+ long time = tunit.toMillis(idletime);
+ if (time < 0) {
+ time = 0;
+ }
+ final long deadline = System.currentTimeMillis() - time;
+ if (this.poolEntry != null && this.poolEntry.getUpdated() <= deadline) {
+ this.poolEntry.close();
+ this.poolEntry.getTracker().reset();
+ }
+ }
+ }
+
+ public void shutdown() {
+ synchronized (this) {
+ this.shutdown = true;
+ try {
+ if (this.poolEntry != null) {
+ this.poolEntry.close();
+ }
+ } finally {
+ this.poolEntry = null;
+ this.conn = null;
+ }
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/BasicHttpClientConnectionManager.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/BasicHttpClientConnectionManager.java
new file mode 100644
index 000000000..1049a4151
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/BasicHttpClientConnectionManager.java
@@ -0,0 +1,370 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.Date;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.HttpClientConnection;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.annotation.GuardedBy;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.config.ConnectionConfig;
+import ch.boye.httpclientandroidlib.config.Lookup;
+import ch.boye.httpclientandroidlib.config.Registry;
+import ch.boye.httpclientandroidlib.config.RegistryBuilder;
+import ch.boye.httpclientandroidlib.config.SocketConfig;
+import ch.boye.httpclientandroidlib.conn.ConnectionRequest;
+import ch.boye.httpclientandroidlib.conn.DnsResolver;
+import ch.boye.httpclientandroidlib.conn.HttpClientConnectionManager;
+import ch.boye.httpclientandroidlib.conn.HttpConnectionFactory;
+import ch.boye.httpclientandroidlib.conn.SchemePortResolver;
+import ch.boye.httpclientandroidlib.conn.ManagedHttpClientConnection;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.conn.socket.ConnectionSocketFactory;
+import ch.boye.httpclientandroidlib.conn.socket.PlainConnectionSocketFactory;
+import ch.boye.httpclientandroidlib.conn.ssl.SSLConnectionSocketFactory;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.Asserts;
+import ch.boye.httpclientandroidlib.util.LangUtils;
+
+/**
+ * A connection manager for a single connection. This connection manager maintains only one active
+ * connection. Even though this class is fully thread-safe it ought to be used by one execution
+ * thread only, as only one thread a time can lease the connection at a time.
+ *
+ * This connection manager will make an effort to reuse the connection for subsequent requests
+ * with the same {@link HttpRoute route}. It will, however, close the existing connection and
+ * open it for the given route, if the route of the persistent connection does not match that
+ * of the connection request. If the connection has been already been allocated
+ * {@link IllegalStateException} is thrown.
+ *
+ * This connection manager implementation should be used inside an EJB container instead of
+ * {@link PoolingHttpClientConnectionManager}.
+ *
+ * @since 4.3
+ */
+@ThreadSafe
+public class BasicHttpClientConnectionManager implements HttpClientConnectionManager, Closeable {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ private final HttpClientConnectionOperator connectionOperator;
+ private final HttpConnectionFactory connFactory;
+
+ @GuardedBy("this")
+ private ManagedHttpClientConnection conn;
+
+ @GuardedBy("this")
+ private HttpRoute route;
+
+ @GuardedBy("this")
+ private Object state;
+
+ @GuardedBy("this")
+ private long updated;
+
+ @GuardedBy("this")
+ private long expiry;
+
+ @GuardedBy("this")
+ private boolean leased;
+
+ @GuardedBy("this")
+ private SocketConfig socketConfig;
+
+ @GuardedBy("this")
+ private ConnectionConfig connConfig;
+
+ private final AtomicBoolean isShutdown;
+
+ private static Registry getDefaultRegistry() {
+ return RegistryBuilder.create()
+ .register("http", PlainConnectionSocketFactory.getSocketFactory())
+ .register("https", SSLConnectionSocketFactory.getSocketFactory())
+ .build();
+ }
+
+ public BasicHttpClientConnectionManager(
+ final Lookup socketFactoryRegistry,
+ final HttpConnectionFactory connFactory,
+ final SchemePortResolver schemePortResolver,
+ final DnsResolver dnsResolver) {
+ super();
+ this.connectionOperator = new HttpClientConnectionOperator(
+ socketFactoryRegistry, schemePortResolver, dnsResolver);
+ this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE;
+ this.expiry = Long.MAX_VALUE;
+ this.socketConfig = SocketConfig.DEFAULT;
+ this.connConfig = ConnectionConfig.DEFAULT;
+ this.isShutdown = new AtomicBoolean(false);
+ }
+
+ public BasicHttpClientConnectionManager(
+ final Lookup socketFactoryRegistry,
+ final HttpConnectionFactory connFactory) {
+ this(socketFactoryRegistry, connFactory, null, null);
+ }
+
+ public BasicHttpClientConnectionManager(
+ final Lookup socketFactoryRegistry) {
+ this(socketFactoryRegistry, null, null, null);
+ }
+
+ public BasicHttpClientConnectionManager() {
+ this(getDefaultRegistry(), null, null, null);
+ }
+
+ @Override
+ protected void finalize() throws Throwable {
+ try {
+ shutdown();
+ } finally { // Make sure we call overridden method even if shutdown barfs
+ super.finalize();
+ }
+ }
+
+ public void close() {
+ shutdown();
+ }
+
+ HttpRoute getRoute() {
+ return route;
+ }
+
+ Object getState() {
+ return state;
+ }
+
+ public synchronized SocketConfig getSocketConfig() {
+ return socketConfig;
+ }
+
+ public synchronized void setSocketConfig(final SocketConfig socketConfig) {
+ this.socketConfig = socketConfig != null ? socketConfig : SocketConfig.DEFAULT;
+ }
+
+ public synchronized ConnectionConfig getConnectionConfig() {
+ return connConfig;
+ }
+
+ public synchronized void setConnectionConfig(final ConnectionConfig connConfig) {
+ this.connConfig = connConfig != null ? connConfig : ConnectionConfig.DEFAULT;
+ }
+
+ public final ConnectionRequest requestConnection(
+ final HttpRoute route,
+ final Object state) {
+ Args.notNull(route, "Route");
+ return new ConnectionRequest() {
+
+ public boolean cancel() {
+ // Nothing to abort, since requests are immediate.
+ return false;
+ }
+
+ public HttpClientConnection get(final long timeout, final TimeUnit tunit) {
+ return BasicHttpClientConnectionManager.this.getConnection(
+ route, state);
+ }
+
+ };
+ }
+
+ private void closeConnection() {
+ if (this.conn != null) {
+ this.log.debug("Closing connection");
+ try {
+ this.conn.close();
+ } catch (final IOException iox) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("I/O exception closing connection", iox);
+ }
+ }
+ this.conn = null;
+ }
+ }
+
+ private void shutdownConnection() {
+ if (this.conn != null) {
+ this.log.debug("Shutting down connection");
+ try {
+ this.conn.shutdown();
+ } catch (final IOException iox) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("I/O exception shutting down connection", iox);
+ }
+ }
+ this.conn = null;
+ }
+ }
+
+ private void checkExpiry() {
+ if (this.conn != null && System.currentTimeMillis() >= this.expiry) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Connection expired @ " + new Date(this.expiry));
+ }
+ closeConnection();
+ }
+ }
+
+ synchronized HttpClientConnection getConnection(final HttpRoute route, final Object state) {
+ Asserts.check(!this.isShutdown.get(), "Connection manager has been shut down");
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Get connection for route " + route);
+ }
+ Asserts.check(!this.leased, "Connection is still allocated");
+ if (!LangUtils.equals(this.route, route) || !LangUtils.equals(this.state, state)) {
+ closeConnection();
+ }
+ this.route = route;
+ this.state = state;
+ checkExpiry();
+ if (this.conn == null) {
+ this.conn = this.connFactory.create(route, this.connConfig);
+ }
+ this.leased = true;
+ return this.conn;
+ }
+
+ public synchronized void releaseConnection(
+ final HttpClientConnection conn,
+ final Object state,
+ final long keepalive, final TimeUnit tunit) {
+ Args.notNull(conn, "Connection");
+ Asserts.check(conn == this.conn, "Connection not obtained from this manager");
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Releasing connection " + conn);
+ }
+ if (this.isShutdown.get()) {
+ return;
+ }
+ try {
+ this.updated = System.currentTimeMillis();
+ if (!this.conn.isOpen()) {
+ this.conn = null;
+ this.route = null;
+ this.conn = null;
+ this.expiry = Long.MAX_VALUE;
+ } else {
+ this.state = state;
+ if (this.log.isDebugEnabled()) {
+ final String s;
+ if (keepalive > 0) {
+ s = "for " + keepalive + " " + tunit;
+ } else {
+ s = "indefinitely";
+ }
+ this.log.debug("Connection can be kept alive " + s);
+ }
+ if (keepalive > 0) {
+ this.expiry = this.updated + tunit.toMillis(keepalive);
+ } else {
+ this.expiry = Long.MAX_VALUE;
+ }
+ }
+ } finally {
+ this.leased = false;
+ }
+ }
+
+ public void connect(
+ final HttpClientConnection conn,
+ final HttpRoute route,
+ final int connectTimeout,
+ final HttpContext context) throws IOException {
+ Args.notNull(conn, "Connection");
+ Args.notNull(route, "HTTP route");
+ Asserts.check(conn == this.conn, "Connection not obtained from this manager");
+ final HttpHost host;
+ if (route.getProxyHost() != null) {
+ host = route.getProxyHost();
+ } else {
+ host = route.getTargetHost();
+ }
+ final InetSocketAddress localAddress = route.getLocalSocketAddress();
+ this.connectionOperator.connect(this.conn, host, localAddress,
+ connectTimeout, this.socketConfig, context);
+ }
+
+ public void upgrade(
+ final HttpClientConnection conn,
+ final HttpRoute route,
+ final HttpContext context) throws IOException {
+ Args.notNull(conn, "Connection");
+ Args.notNull(route, "HTTP route");
+ Asserts.check(conn == this.conn, "Connection not obtained from this manager");
+ this.connectionOperator.upgrade(this.conn, route.getTargetHost(), context);
+ }
+
+ public void routeComplete(
+ final HttpClientConnection conn,
+ final HttpRoute route,
+ final HttpContext context) throws IOException {
+ }
+
+ public synchronized void closeExpiredConnections() {
+ if (this.isShutdown.get()) {
+ return;
+ }
+ if (!this.leased) {
+ checkExpiry();
+ }
+ }
+
+ public synchronized void closeIdleConnections(final long idletime, final TimeUnit tunit) {
+ Args.notNull(tunit, "Time unit");
+ if (this.isShutdown.get()) {
+ return;
+ }
+ if (!this.leased) {
+ long time = tunit.toMillis(idletime);
+ if (time < 0) {
+ time = 0;
+ }
+ final long deadline = System.currentTimeMillis() - time;
+ if (this.updated <= deadline) {
+ closeConnection();
+ }
+ }
+ }
+
+ public synchronized void shutdown() {
+ if (this.isShutdown.compareAndSet(false, true)) {
+ shutdownConnection();
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/CPool.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/CPool.java
new file mode 100644
index 000000000..040960c71
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/CPool.java
@@ -0,0 +1,67 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.conn.ManagedHttpClientConnection;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.pool.AbstractConnPool;
+import ch.boye.httpclientandroidlib.pool.ConnFactory;
+
+/**
+ * @since 4.3
+ */
+@ThreadSafe
+class CPool extends AbstractConnPool {
+
+ private static final AtomicLong COUNTER = new AtomicLong();
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(CPool.class);
+ private final long timeToLive;
+ private final TimeUnit tunit;
+
+ public CPool(
+ final ConnFactory connFactory,
+ final int defaultMaxPerRoute, final int maxTotal,
+ final long timeToLive, final TimeUnit tunit) {
+ super(connFactory, defaultMaxPerRoute, maxTotal);
+ this.timeToLive = timeToLive;
+ this.tunit = tunit;
+ }
+
+ @Override
+ protected CPoolEntry createEntry(final HttpRoute route, final ManagedHttpClientConnection conn) {
+ final String id = Long.toString(COUNTER.getAndIncrement());
+ return new CPoolEntry(this.log, id, route, conn, this.timeToLive, this.tunit);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/CPoolEntry.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/CPoolEntry.java
new file mode 100644
index 000000000..f5ecfdc5e
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/CPoolEntry.java
@@ -0,0 +1,101 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+import java.util.Date;
+import java.util.concurrent.TimeUnit;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+import ch.boye.httpclientandroidlib.HttpClientConnection;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.conn.ManagedHttpClientConnection;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.pool.PoolEntry;
+
+/**
+ * @since 4.3
+ */
+@ThreadSafe
+class CPoolEntry extends PoolEntry {
+
+ public HttpClientAndroidLog log;
+ private volatile boolean routeComplete;
+
+ public CPoolEntry(
+ final HttpClientAndroidLog log,
+ final String id,
+ final HttpRoute route,
+ final ManagedHttpClientConnection conn,
+ final long timeToLive, final TimeUnit tunit) {
+ super(id, route, conn, timeToLive, tunit);
+ this.log = log;
+ }
+
+ public void markRouteComplete() {
+ this.routeComplete = true;
+ }
+
+ public boolean isRouteComplete() {
+ return this.routeComplete;
+ }
+
+ public void closeConnection() throws IOException {
+ final HttpClientConnection conn = getConnection();
+ conn.close();
+ }
+
+ public void shutdownConnection() throws IOException {
+ final HttpClientConnection conn = getConnection();
+ conn.shutdown();
+ }
+
+ @Override
+ public boolean isExpired(final long now) {
+ final boolean expired = super.isExpired(now);
+ if (expired && this.log.isDebugEnabled()) {
+ this.log.debug("Connection " + this + " expired @ " + new Date(getExpiry()));
+ }
+ return expired;
+ }
+
+ @Override
+ public boolean isClosed() {
+ final HttpClientConnection conn = getConnection();
+ return !conn.isOpen();
+ }
+
+ @Override
+ public void close() {
+ try {
+ closeConnection();
+ } catch (final IOException ex) {
+ this.log.debug("I/O error closing connection", ex);
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/CPoolProxy.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/CPoolProxy.java
new file mode 100644
index 000000000..9ac67a10d
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/CPoolProxy.java
@@ -0,0 +1,245 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.Socket;
+
+import javax.net.ssl.SSLSession;
+
+import ch.boye.httpclientandroidlib.HttpClientConnection;
+import ch.boye.httpclientandroidlib.HttpConnectionMetrics;
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.conn.ManagedHttpClientConnection;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+/**
+ * @since 4.3
+ */
+@NotThreadSafe
+class CPoolProxy implements ManagedHttpClientConnection, HttpContext {
+
+ private volatile CPoolEntry poolEntry;
+
+ CPoolProxy(final CPoolEntry entry) {
+ super();
+ this.poolEntry = entry;
+ }
+
+ CPoolEntry getPoolEntry() {
+ return this.poolEntry;
+ }
+
+ CPoolEntry detach() {
+ final CPoolEntry local = this.poolEntry;
+ this.poolEntry = null;
+ return local;
+ }
+
+ ManagedHttpClientConnection getConnection() {
+ final CPoolEntry local = this.poolEntry;
+ if (local == null) {
+ return null;
+ }
+ return local.getConnection();
+ }
+
+ ManagedHttpClientConnection getValidConnection() {
+ final ManagedHttpClientConnection conn = getConnection();
+ if (conn == null) {
+ throw new ConnectionShutdownException();
+ }
+ return conn;
+ }
+
+ public void close() throws IOException {
+ final CPoolEntry local = this.poolEntry;
+ if (local != null) {
+ local.closeConnection();
+ }
+ }
+
+ public void shutdown() throws IOException {
+ final CPoolEntry local = this.poolEntry;
+ if (local != null) {
+ local.shutdownConnection();
+ }
+ }
+
+ public boolean isOpen() {
+ final CPoolEntry local = this.poolEntry;
+ if (local != null) {
+ return !local.isClosed();
+ } else {
+ return false;
+ }
+ }
+
+ public boolean isStale() {
+ final HttpClientConnection conn = getConnection();
+ if (conn != null) {
+ return conn.isStale();
+ } else {
+ return true;
+ }
+ }
+
+ public void setSocketTimeout(final int timeout) {
+ getValidConnection().setSocketTimeout(timeout);
+ }
+
+ public int getSocketTimeout() {
+ return getValidConnection().getSocketTimeout();
+ }
+
+ public String getId() {
+ return getValidConnection().getId();
+ }
+
+ public void bind(final Socket socket) throws IOException {
+ getValidConnection().bind(socket);
+ }
+
+ public Socket getSocket() {
+ return getValidConnection().getSocket();
+ }
+
+ public SSLSession getSSLSession() {
+ return getValidConnection().getSSLSession();
+ }
+
+ public boolean isResponseAvailable(final int timeout) throws IOException {
+ return getValidConnection().isResponseAvailable(timeout);
+ }
+
+ public void sendRequestHeader(final HttpRequest request) throws HttpException, IOException {
+ getValidConnection().sendRequestHeader(request);
+ }
+
+ public void sendRequestEntity(final HttpEntityEnclosingRequest request) throws HttpException, IOException {
+ getValidConnection().sendRequestEntity(request);
+ }
+
+ public HttpResponse receiveResponseHeader() throws HttpException, IOException {
+ return getValidConnection().receiveResponseHeader();
+ }
+
+ public void receiveResponseEntity(final HttpResponse response) throws HttpException, IOException {
+ getValidConnection().receiveResponseEntity(response);
+ }
+
+ public void flush() throws IOException {
+ getValidConnection().flush();
+ }
+
+ public HttpConnectionMetrics getMetrics() {
+ return getValidConnection().getMetrics();
+ }
+
+ public InetAddress getLocalAddress() {
+ return getValidConnection().getLocalAddress();
+ }
+
+ public int getLocalPort() {
+ return getValidConnection().getLocalPort();
+ }
+
+ public InetAddress getRemoteAddress() {
+ return getValidConnection().getRemoteAddress();
+ }
+
+ public int getRemotePort() {
+ return getValidConnection().getRemotePort();
+ }
+
+ public Object getAttribute(final String id) {
+ final ManagedHttpClientConnection conn = getValidConnection();
+ if (conn instanceof HttpContext) {
+ return ((HttpContext) conn).getAttribute(id);
+ } else {
+ return null;
+ }
+ }
+
+ public void setAttribute(final String id, final Object obj) {
+ final ManagedHttpClientConnection conn = getValidConnection();
+ if (conn instanceof HttpContext) {
+ ((HttpContext) conn).setAttribute(id, obj);
+ }
+ }
+
+ public Object removeAttribute(final String id) {
+ final ManagedHttpClientConnection conn = getValidConnection();
+ if (conn instanceof HttpContext) {
+ return ((HttpContext) conn).removeAttribute(id);
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder("CPoolProxy{");
+ final ManagedHttpClientConnection conn = getConnection();
+ if (conn != null) {
+ sb.append(conn);
+ } else {
+ sb.append("detached");
+ }
+ sb.append('}');
+ return sb.toString();
+ }
+
+ public static HttpClientConnection newProxy(final CPoolEntry poolEntry) {
+ return new CPoolProxy(poolEntry);
+ }
+
+ private static CPoolProxy getProxy(final HttpClientConnection conn) {
+ if (!CPoolProxy.class.isInstance(conn)) {
+ throw new IllegalStateException("Unexpected connection proxy class: " + conn.getClass());
+ }
+ return CPoolProxy.class.cast(conn);
+ }
+
+ public static CPoolEntry getPoolEntry(final HttpClientConnection proxy) {
+ final CPoolEntry entry = getProxy(proxy).getPoolEntry();
+ if (entry == null) {
+ throw new ConnectionShutdownException();
+ }
+ return entry;
+ }
+
+ public static CPoolEntry detach(final HttpClientConnection conn) {
+ return getProxy(conn).detach();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/ConnectionShutdownException.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/ConnectionShutdownException.java
new file mode 100644
index 000000000..03820a38f
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/ConnectionShutdownException.java
@@ -0,0 +1,50 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+
+/**
+ * Signals that the connection has been shut down or released back to the
+ * the connection pool
+ *
+ * @since 4.1
+ */
+@Immutable
+public class ConnectionShutdownException extends IllegalStateException {
+
+ private static final long serialVersionUID = 5868657401162844497L;
+
+ /**
+ * Creates a new ConnectionShutdownException with a null detail message.
+ */
+ public ConnectionShutdownException() {
+ super();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultClientConnection.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultClientConnection.java
new file mode 100644
index 000000000..f9003b144
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultClientConnection.java
@@ -0,0 +1,292 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.Socket;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocket;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpResponseFactory;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.conn.OperatedClientConnection;
+import ch.boye.httpclientandroidlib.conn.ManagedHttpClientConnection;
+import ch.boye.httpclientandroidlib.impl.SocketHttpClientConnection;
+import ch.boye.httpclientandroidlib.io.HttpMessageParser;
+import ch.boye.httpclientandroidlib.io.SessionInputBuffer;
+import ch.boye.httpclientandroidlib.io.SessionOutputBuffer;
+import ch.boye.httpclientandroidlib.params.BasicHttpParams;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.params.HttpProtocolParams;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Default implementation of an operated client connection.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link ManagedHttpClientConnectionFactory}.
+ */
+@NotThreadSafe // connSecure, targetHost
+@Deprecated
+public class DefaultClientConnection extends SocketHttpClientConnection
+ implements OperatedClientConnection, ManagedHttpClientConnection, HttpContext {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+ public HttpClientAndroidLog headerLog = new HttpClientAndroidLog("ch.boye.httpclientandroidlib.headers");
+ public HttpClientAndroidLog wireLog = new HttpClientAndroidLog("ch.boye.httpclientandroidlib.wire");
+
+ /** The unconnected socket */
+ private volatile Socket socket;
+
+ /** The target host of this connection. */
+ private HttpHost targetHost;
+
+ /** Whether this connection is secure. */
+ private boolean connSecure;
+
+ /** True if this connection was shutdown. */
+ private volatile boolean shutdown;
+
+ /** connection specific attributes */
+ private final Map attributes;
+
+ public DefaultClientConnection() {
+ super();
+ this.attributes = new HashMap();
+ }
+
+ public String getId() {
+ return null;
+ }
+
+ public final HttpHost getTargetHost() {
+ return this.targetHost;
+ }
+
+ public final boolean isSecure() {
+ return this.connSecure;
+ }
+
+ @Override
+ public final Socket getSocket() {
+ return this.socket;
+ }
+
+ public SSLSession getSSLSession() {
+ if (this.socket instanceof SSLSocket) {
+ return ((SSLSocket) this.socket).getSession();
+ } else {
+ return null;
+ }
+ }
+
+ public void opening(final Socket sock, final HttpHost target) throws IOException {
+ assertNotOpen();
+ this.socket = sock;
+ this.targetHost = target;
+
+ // Check for shutdown after assigning socket, so that
+ if (this.shutdown) {
+ sock.close(); // allow this to throw...
+ // ...but if it doesn't, explicitly throw one ourselves.
+ throw new InterruptedIOException("Connection already shutdown");
+ }
+ }
+
+ public void openCompleted(final boolean secure, final HttpParams params) throws IOException {
+ Args.notNull(params, "Parameters");
+ assertNotOpen();
+ this.connSecure = secure;
+ bind(this.socket, params);
+ }
+
+ /**
+ * Force-closes this connection.
+ * If the connection is still in the process of being open (the method
+ * {@link #opening opening} was already called but
+ * {@link #openCompleted openCompleted} was not), the associated
+ * socket that is being connected to a remote address will be closed.
+ * That will interrupt a thread that is blocked on connecting
+ * the socket.
+ * If the connection is not yet open, this will prevent the connection
+ * from being opened.
+ *
+ * @throws IOException in case of a problem
+ */
+ @Override
+ public void shutdown() throws IOException {
+ shutdown = true;
+ try {
+ super.shutdown();
+ if (log.isDebugEnabled()) {
+ log.debug("Connection " + this + " shut down");
+ }
+ final Socket sock = this.socket; // copy volatile attribute
+ if (sock != null) {
+ sock.close();
+ }
+ } catch (final IOException ex) {
+ log.debug("I/O error shutting down connection", ex);
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ try {
+ super.close();
+ if (log.isDebugEnabled()) {
+ log.debug("Connection " + this + " closed");
+ }
+ } catch (final IOException ex) {
+ log.debug("I/O error closing connection", ex);
+ }
+ }
+
+ @Override
+ protected SessionInputBuffer createSessionInputBuffer(
+ final Socket socket,
+ final int buffersize,
+ final HttpParams params) throws IOException {
+ SessionInputBuffer inbuffer = super.createSessionInputBuffer(
+ socket,
+ buffersize > 0 ? buffersize : 8192,
+ params);
+ if (wireLog.isDebugEnabled()) {
+ inbuffer = new LoggingSessionInputBuffer(
+ inbuffer,
+ new Wire(wireLog),
+ HttpProtocolParams.getHttpElementCharset(params));
+ }
+ return inbuffer;
+ }
+
+ @Override
+ protected SessionOutputBuffer createSessionOutputBuffer(
+ final Socket socket,
+ final int buffersize,
+ final HttpParams params) throws IOException {
+ SessionOutputBuffer outbuffer = super.createSessionOutputBuffer(
+ socket,
+ buffersize > 0 ? buffersize : 8192,
+ params);
+ if (wireLog.isDebugEnabled()) {
+ outbuffer = new LoggingSessionOutputBuffer(
+ outbuffer,
+ new Wire(wireLog),
+ HttpProtocolParams.getHttpElementCharset(params));
+ }
+ return outbuffer;
+ }
+
+ @Override
+ protected HttpMessageParser createResponseParser(
+ final SessionInputBuffer buffer,
+ final HttpResponseFactory responseFactory,
+ final HttpParams params) {
+ // override in derived class to specify a line parser
+ return new DefaultHttpResponseParser
+ (buffer, null, responseFactory, params);
+ }
+
+ public void bind(final Socket socket) throws IOException {
+ bind(socket, new BasicHttpParams());
+ }
+
+ public void update(final Socket sock, final HttpHost target,
+ final boolean secure, final HttpParams params)
+ throws IOException {
+
+ assertOpen();
+ Args.notNull(target, "Target host");
+ Args.notNull(params, "Parameters");
+
+ if (sock != null) {
+ this.socket = sock;
+ bind(sock, params);
+ }
+ targetHost = target;
+ connSecure = secure;
+ }
+
+ @Override
+ public HttpResponse receiveResponseHeader() throws HttpException, IOException {
+ final HttpResponse response = super.receiveResponseHeader();
+ if (log.isDebugEnabled()) {
+ log.debug("Receiving response: " + response.getStatusLine());
+ }
+ if (headerLog.isDebugEnabled()) {
+ headerLog.debug("<< " + response.getStatusLine().toString());
+ final Header[] headers = response.getAllHeaders();
+ for (final Header header : headers) {
+ headerLog.debug("<< " + header.toString());
+ }
+ }
+ return response;
+ }
+
+ @Override
+ public void sendRequestHeader(final HttpRequest request) throws HttpException, IOException {
+ if (log.isDebugEnabled()) {
+ log.debug("Sending request: " + request.getRequestLine());
+ }
+ super.sendRequestHeader(request);
+ if (headerLog.isDebugEnabled()) {
+ headerLog.debug(">> " + request.getRequestLine().toString());
+ final Header[] headers = request.getAllHeaders();
+ for (final Header header : headers) {
+ headerLog.debug(">> " + header.toString());
+ }
+ }
+ }
+
+ public Object getAttribute(final String id) {
+ return this.attributes.get(id);
+ }
+
+ public Object removeAttribute(final String id) {
+ return this.attributes.remove(id);
+ }
+
+ public void setAttribute(final String id, final Object obj) {
+ this.attributes.put(id, obj);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultClientConnectionOperator.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultClientConnectionOperator.java
new file mode 100644
index 000000000..3cdf706ec
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultClientConnectionOperator.java
@@ -0,0 +1,263 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+import java.net.ConnectException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.net.UnknownHostException;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.client.protocol.ClientContext;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionOperator;
+import ch.boye.httpclientandroidlib.conn.ConnectTimeoutException;
+import ch.boye.httpclientandroidlib.conn.DnsResolver;
+import ch.boye.httpclientandroidlib.conn.HttpInetSocketAddress;
+import ch.boye.httpclientandroidlib.conn.OperatedClientConnection;
+import ch.boye.httpclientandroidlib.conn.scheme.Scheme;
+import ch.boye.httpclientandroidlib.conn.scheme.SchemeLayeredSocketFactory;
+import ch.boye.httpclientandroidlib.conn.scheme.SchemeRegistry;
+import ch.boye.httpclientandroidlib.conn.scheme.SchemeSocketFactory;
+import ch.boye.httpclientandroidlib.params.HttpConnectionParams;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.Asserts;
+
+/**
+ * Default implementation of a {@link ClientConnectionOperator}. It uses a {@link SchemeRegistry}
+ * to look up {@link SchemeSocketFactory} objects.
+ *
+ * This connection operator is multihome network aware and will attempt to retry failed connects
+ * against all known IP addresses sequentially until the connect is successful or all known
+ * addresses fail to respond. Please note the same
+ * {@link ch.boye.httpclientandroidlib.params.CoreConnectionPNames#CONNECTION_TIMEOUT} value will be used
+ * for each connection attempt, so in the worst case the total elapsed time before timeout
+ * can be CONNECTION_TIMEOUT * n where n is the number of IP addresses
+ * of the given host. One can disable multihome support by overriding
+ * the {@link #resolveHostname(String)} method and returning only one IP address for the given
+ * host name.
+ *
+ * The following parameters can be used to customize the behavior of this
+ * class:
+ *
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link PoolingHttpClientConnectionManager}.
+ */
+@Deprecated
+@ThreadSafe
+public class DefaultClientConnectionOperator implements ClientConnectionOperator {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ /** The scheme registry for looking up socket factories. */
+ protected final SchemeRegistry schemeRegistry; // @ThreadSafe
+
+ /** the custom-configured DNS lookup mechanism. */
+ protected final DnsResolver dnsResolver;
+
+ /**
+ * Creates a new client connection operator for the given scheme registry.
+ *
+ * @param schemes the scheme registry
+ *
+ * @since 4.2
+ */
+ public DefaultClientConnectionOperator(final SchemeRegistry schemes) {
+ Args.notNull(schemes, "Scheme registry");
+ this.schemeRegistry = schemes;
+ this.dnsResolver = new SystemDefaultDnsResolver();
+ }
+
+ /**
+ * Creates a new client connection operator for the given scheme registry
+ * and the given custom DNS lookup mechanism.
+ *
+ * @param schemes
+ * the scheme registry
+ * @param dnsResolver
+ * the custom DNS lookup mechanism
+ */
+ public DefaultClientConnectionOperator(final SchemeRegistry schemes,final DnsResolver dnsResolver) {
+ Args.notNull(schemes, "Scheme registry");
+
+ Args.notNull(dnsResolver, "DNS resolver");
+
+ this.schemeRegistry = schemes;
+ this.dnsResolver = dnsResolver;
+ }
+
+ public OperatedClientConnection createConnection() {
+ return new DefaultClientConnection();
+ }
+
+ private SchemeRegistry getSchemeRegistry(final HttpContext context) {
+ SchemeRegistry reg = (SchemeRegistry) context.getAttribute(
+ ClientContext.SCHEME_REGISTRY);
+ if (reg == null) {
+ reg = this.schemeRegistry;
+ }
+ return reg;
+ }
+
+ public void openConnection(
+ final OperatedClientConnection conn,
+ final HttpHost target,
+ final InetAddress local,
+ final HttpContext context,
+ final HttpParams params) throws IOException {
+ Args.notNull(conn, "Connection");
+ Args.notNull(target, "Target host");
+ Args.notNull(params, "HTTP parameters");
+ Asserts.check(!conn.isOpen(), "Connection must not be open");
+
+ final SchemeRegistry registry = getSchemeRegistry(context);
+ final Scheme schm = registry.getScheme(target.getSchemeName());
+ final SchemeSocketFactory sf = schm.getSchemeSocketFactory();
+
+ final InetAddress[] addresses = resolveHostname(target.getHostName());
+ final int port = schm.resolvePort(target.getPort());
+ for (int i = 0; i < addresses.length; i++) {
+ final InetAddress address = addresses[i];
+ final boolean last = i == addresses.length - 1;
+
+ Socket sock = sf.createSocket(params);
+ conn.opening(sock, target);
+
+ final InetSocketAddress remoteAddress = new HttpInetSocketAddress(target, address, port);
+ InetSocketAddress localAddress = null;
+ if (local != null) {
+ localAddress = new InetSocketAddress(local, 0);
+ }
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Connecting to " + remoteAddress);
+ }
+ try {
+ final Socket connsock = sf.connectSocket(sock, remoteAddress, localAddress, params);
+ if (sock != connsock) {
+ sock = connsock;
+ conn.opening(sock, target);
+ }
+ prepareSocket(sock, context, params);
+ conn.openCompleted(sf.isSecure(sock), params);
+ return;
+ } catch (final ConnectException ex) {
+ if (last) {
+ throw ex;
+ }
+ } catch (final ConnectTimeoutException ex) {
+ if (last) {
+ throw ex;
+ }
+ }
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Connect to " + remoteAddress + " timed out. " +
+ "Connection will be retried using another IP address");
+ }
+ }
+ }
+
+ public void updateSecureConnection(
+ final OperatedClientConnection conn,
+ final HttpHost target,
+ final HttpContext context,
+ final HttpParams params) throws IOException {
+ Args.notNull(conn, "Connection");
+ Args.notNull(target, "Target host");
+ Args.notNull(params, "Parameters");
+ Asserts.check(conn.isOpen(), "Connection must be open");
+
+ final SchemeRegistry registry = getSchemeRegistry(context);
+ final Scheme schm = registry.getScheme(target.getSchemeName());
+ Asserts.check(schm.getSchemeSocketFactory() instanceof SchemeLayeredSocketFactory,
+ "Socket factory must implement SchemeLayeredSocketFactory");
+ final SchemeLayeredSocketFactory lsf = (SchemeLayeredSocketFactory) schm.getSchemeSocketFactory();
+ final Socket sock = lsf.createLayeredSocket(
+ conn.getSocket(), target.getHostName(), schm.resolvePort(target.getPort()), params);
+ prepareSocket(sock, context, params);
+ conn.update(sock, target, lsf.isSecure(sock), params);
+ }
+
+ /**
+ * Performs standard initializations on a newly created socket.
+ *
+ * @param sock the socket to prepare
+ * @param context the context for the connection
+ * @param params the parameters from which to prepare the socket
+ *
+ * @throws IOException in case of an IO problem
+ */
+ protected void prepareSocket(
+ final Socket sock,
+ final HttpContext context,
+ final HttpParams params) throws IOException {
+ sock.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
+ sock.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
+
+ final int linger = HttpConnectionParams.getLinger(params);
+ if (linger >= 0) {
+ sock.setSoLinger(linger > 0, linger);
+ }
+ }
+
+ /**
+ * Resolves the given host name to an array of corresponding IP addresses, based on the
+ * configured name service on the provided DNS resolver. If one wasn't provided, the system
+ * configuration is used.
+ *
+ * @param host host name to resolve
+ * @return array of IP addresses
+ * @exception UnknownHostException if no IP address for the host could be determined.
+ *
+ * @see DnsResolver
+ * @see SystemDefaultDnsResolver
+ *
+ * @since 4.1
+ */
+ protected InetAddress[] resolveHostname(final String host) throws UnknownHostException {
+ return dnsResolver.resolve(host);
+ }
+
+}
+
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultHttpResponseParser.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultHttpResponseParser.java
new file mode 100644
index 000000000..9f249e5f7
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultHttpResponseParser.java
@@ -0,0 +1,168 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpResponseFactory;
+import ch.boye.httpclientandroidlib.NoHttpResponseException;
+import ch.boye.httpclientandroidlib.ProtocolException;
+import ch.boye.httpclientandroidlib.StatusLine;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.config.MessageConstraints;
+import ch.boye.httpclientandroidlib.impl.DefaultHttpResponseFactory;
+import ch.boye.httpclientandroidlib.impl.io.AbstractMessageParser;
+import ch.boye.httpclientandroidlib.io.SessionInputBuffer;
+import ch.boye.httpclientandroidlib.message.LineParser;
+import ch.boye.httpclientandroidlib.message.ParserCursor;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
+
+/**
+ * Lenient HTTP response parser implementation that can skip malformed data until
+ * a valid HTTP response message head is encountered.
+ *
+ * @since 4.2
+ */
+@SuppressWarnings("deprecation")
+@NotThreadSafe
+public class DefaultHttpResponseParser extends AbstractMessageParser {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ private final HttpResponseFactory responseFactory;
+ private final CharArrayBuffer lineBuf;
+
+ /**
+ * @deprecated (4.3) use {@link DefaultHttpResponseParser#DefaultHttpResponseParser(
+ * SessionInputBuffer, LineParser, HttpResponseFactory, MessageConstraints)}
+ */
+ @Deprecated
+ public DefaultHttpResponseParser(
+ final SessionInputBuffer buffer,
+ final LineParser parser,
+ final HttpResponseFactory responseFactory,
+ final HttpParams params) {
+ super(buffer, parser, params);
+ Args.notNull(responseFactory, "Response factory");
+ this.responseFactory = responseFactory;
+ this.lineBuf = new CharArrayBuffer(128);
+ }
+
+ /**
+ * Creates new instance of DefaultHttpResponseParser.
+ *
+ * @param buffer the session input buffer.
+ * @param lineParser the line parser. If null
+ * {@link ch.boye.httpclientandroidlib.message.BasicLineParser#INSTANCE} will be used.
+ * @param responseFactory HTTP response factory. If null
+ * {@link DefaultHttpResponseFactory#INSTANCE} will be used.
+ * @param constraints the message constraints. If null
+ * {@link MessageConstraints#DEFAULT} will be used.
+ *
+ * @since 4.3
+ */
+ public DefaultHttpResponseParser(
+ final SessionInputBuffer buffer,
+ final LineParser lineParser,
+ final HttpResponseFactory responseFactory,
+ final MessageConstraints constraints) {
+ super(buffer, lineParser, constraints);
+ this.responseFactory = responseFactory != null ? responseFactory :
+ DefaultHttpResponseFactory.INSTANCE;
+ this.lineBuf = new CharArrayBuffer(128);
+ }
+
+ /**
+ * Creates new instance of DefaultHttpResponseParser.
+ *
+ * @param buffer the session input buffer.
+ * @param constraints the message constraints. If null
+ * {@link MessageConstraints#DEFAULT} will be used.
+ *
+ * @since 4.3
+ */
+ public DefaultHttpResponseParser(
+ final SessionInputBuffer buffer, final MessageConstraints constraints) {
+ this(buffer, null, null, constraints);
+ }
+
+ /**
+ * Creates new instance of DefaultHttpResponseParser.
+ *
+ * @param buffer the session input buffer.
+ *
+ * @since 4.3
+ */
+ public DefaultHttpResponseParser(final SessionInputBuffer buffer) {
+ this(buffer, null, null, MessageConstraints.DEFAULT);
+ }
+
+ @Override
+ protected HttpResponse parseHead(
+ final SessionInputBuffer sessionBuffer) throws IOException, HttpException {
+ //read out the HTTP status string
+ int count = 0;
+ ParserCursor cursor = null;
+ do {
+ // clear the buffer
+ this.lineBuf.clear();
+ final int i = sessionBuffer.readLine(this.lineBuf);
+ if (i == -1 && count == 0) {
+ // The server just dropped connection on us
+ throw new NoHttpResponseException("The target server failed to respond");
+ }
+ cursor = new ParserCursor(0, this.lineBuf.length());
+ if (lineParser.hasProtocolVersion(this.lineBuf, cursor)) {
+ // Got one
+ break;
+ } else if (i == -1 || reject(this.lineBuf, count)) {
+ // Giving up
+ throw new ProtocolException("The server failed to respond with a " +
+ "valid HTTP response");
+ }
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Garbage in response: " + this.lineBuf.toString());
+ }
+ count++;
+ } while(true);
+ //create the status line from the status string
+ final StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, cursor);
+ return this.responseFactory.newHttpResponse(statusline, null);
+ }
+
+ protected boolean reject(final CharArrayBuffer line, final int count) {
+ return false;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultHttpResponseParserFactory.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultHttpResponseParserFactory.java
new file mode 100644
index 000000000..a229b2ca6
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultHttpResponseParserFactory.java
@@ -0,0 +1,77 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.HttpResponseFactory;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.config.MessageConstraints;
+import ch.boye.httpclientandroidlib.impl.DefaultHttpResponseFactory;
+import ch.boye.httpclientandroidlib.io.HttpMessageParser;
+import ch.boye.httpclientandroidlib.io.HttpMessageParserFactory;
+import ch.boye.httpclientandroidlib.io.SessionInputBuffer;
+import ch.boye.httpclientandroidlib.message.BasicLineParser;
+import ch.boye.httpclientandroidlib.message.LineParser;
+
+/**
+ * Default factory for response message parsers.
+ *
+ * @since 4.3
+ */
+@Immutable
+public class DefaultHttpResponseParserFactory implements HttpMessageParserFactory {
+
+ public static final DefaultHttpResponseParserFactory INSTANCE = new DefaultHttpResponseParserFactory();
+
+ private final LineParser lineParser;
+ private final HttpResponseFactory responseFactory;
+
+ public DefaultHttpResponseParserFactory(
+ final LineParser lineParser,
+ final HttpResponseFactory responseFactory) {
+ super();
+ this.lineParser = lineParser != null ? lineParser : BasicLineParser.INSTANCE;
+ this.responseFactory = responseFactory != null ? responseFactory
+ : DefaultHttpResponseFactory.INSTANCE;
+ }
+
+ public DefaultHttpResponseParserFactory(
+ final HttpResponseFactory responseFactory) {
+ this(null, responseFactory);
+ }
+
+ public DefaultHttpResponseParserFactory() {
+ this(null, null);
+ }
+
+ public HttpMessageParser create(final SessionInputBuffer buffer,
+ final MessageConstraints constraints) {
+ return new DefaultHttpResponseParser(buffer, lineParser, responseFactory, constraints);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultHttpRoutePlanner.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultHttpRoutePlanner.java
new file mode 100644
index 000000000..4b3525329
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultHttpRoutePlanner.java
@@ -0,0 +1,123 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+
+import java.net.InetAddress;
+
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.conn.params.ConnRouteParams;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoutePlanner;
+import ch.boye.httpclientandroidlib.conn.scheme.Scheme;
+import ch.boye.httpclientandroidlib.conn.scheme.SchemeRegistry;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.Asserts;
+
+/**
+ * Default implementation of an {@link HttpRoutePlanner}. This implementation
+ * is based on {@link ch.boye.httpclientandroidlib.conn.params.ConnRoutePNames parameters}.
+ * It will not make use of any Java system properties, nor of system or
+ * browser proxy settings.
+ *
+ * The following parameters can be used to customize the behavior of this
+ * class:
+ *
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) use {@link DefaultRoutePlanner}
+ */
+@ThreadSafe
+@Deprecated
+public class DefaultHttpRoutePlanner implements HttpRoutePlanner {
+
+ /** The scheme registry. */
+ protected final SchemeRegistry schemeRegistry; // class is @ThreadSafe
+
+ /**
+ * Creates a new default route planner.
+ *
+ * @param schreg the scheme registry
+ */
+ public DefaultHttpRoutePlanner(final SchemeRegistry schreg) {
+ Args.notNull(schreg, "Scheme registry");
+ schemeRegistry = schreg;
+ }
+
+ public HttpRoute determineRoute(final HttpHost target,
+ final HttpRequest request,
+ final HttpContext context)
+ throws HttpException {
+
+ Args.notNull(request, "HTTP request");
+
+ // If we have a forced route, we can do without a target.
+ HttpRoute route =
+ ConnRouteParams.getForcedRoute(request.getParams());
+ if (route != null) {
+ return route;
+ }
+
+ // If we get here, there is no forced route.
+ // So we need a target to compute a route.
+
+ Asserts.notNull(target, "Target host");
+
+ final InetAddress local =
+ ConnRouteParams.getLocalAddress(request.getParams());
+ final HttpHost proxy =
+ ConnRouteParams.getDefaultProxy(request.getParams());
+
+ final Scheme schm;
+ try {
+ schm = this.schemeRegistry.getScheme(target.getSchemeName());
+ } catch (final IllegalStateException ex) {
+ throw new HttpException(ex.getMessage());
+ }
+ // as it is typically used for TLS/SSL, we assume that
+ // a layered scheme implies a secure connection
+ final boolean secure = schm.isLayered();
+
+ if (proxy == null) {
+ route = new HttpRoute(target, local, secure);
+ } else {
+ route = new HttpRoute(target, local, proxy, secure);
+ }
+ return route;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultManagedHttpClientConnection.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultManagedHttpClientConnection.java
new file mode 100644
index 000000000..c46b93405
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultManagedHttpClientConnection.java
@@ -0,0 +1,135 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.Socket;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CharsetEncoder;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocket;
+
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.config.MessageConstraints;
+import ch.boye.httpclientandroidlib.conn.ManagedHttpClientConnection;
+import ch.boye.httpclientandroidlib.entity.ContentLengthStrategy;
+import ch.boye.httpclientandroidlib.impl.DefaultBHttpClientConnection;
+import ch.boye.httpclientandroidlib.io.HttpMessageParserFactory;
+import ch.boye.httpclientandroidlib.io.HttpMessageWriterFactory;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+
+/**
+ * Default {@link ManagedHttpClientConnection} implementation.
+ * @since 4.3
+ */
+@NotThreadSafe
+public class DefaultManagedHttpClientConnection extends DefaultBHttpClientConnection
+ implements ManagedHttpClientConnection, HttpContext {
+
+ private final String id;
+ private final Map attributes;
+
+ private volatile boolean shutdown;
+
+ public DefaultManagedHttpClientConnection(
+ final String id,
+ final int buffersize,
+ final int fragmentSizeHint,
+ final CharsetDecoder chardecoder,
+ final CharsetEncoder charencoder,
+ final MessageConstraints constraints,
+ final ContentLengthStrategy incomingContentStrategy,
+ final ContentLengthStrategy outgoingContentStrategy,
+ final HttpMessageWriterFactory requestWriterFactory,
+ final HttpMessageParserFactory responseParserFactory) {
+ super(buffersize, fragmentSizeHint, chardecoder, charencoder,
+ constraints, incomingContentStrategy, outgoingContentStrategy,
+ requestWriterFactory, responseParserFactory);
+ this.id = id;
+ this.attributes = new ConcurrentHashMap();
+ }
+
+ public DefaultManagedHttpClientConnection(
+ final String id,
+ final int buffersize) {
+ this(id, buffersize, buffersize, null, null, null, null, null, null, null);
+ }
+
+ public String getId() {
+ return this.id;
+ }
+
+ @Override
+ public void shutdown() throws IOException {
+ this.shutdown = true;
+ super.shutdown();
+ }
+
+ public Object getAttribute(final String id) {
+ return this.attributes.get(id);
+ }
+
+ public Object removeAttribute(final String id) {
+ return this.attributes.remove(id);
+ }
+
+ public void setAttribute(final String id, final Object obj) {
+ this.attributes.put(id, obj);
+ }
+
+ @Override
+ public void bind(final Socket socket) throws IOException {
+ if (this.shutdown) {
+ socket.close(); // allow this to throw...
+ // ...but if it doesn't, explicitly throw one ourselves.
+ throw new InterruptedIOException("Connection already shutdown");
+ }
+ super.bind(socket);
+ }
+
+ @Override
+ public Socket getSocket() {
+ return super.getSocket();
+ }
+
+ public SSLSession getSSLSession() {
+ final Socket socket = super.getSocket();
+ if (socket instanceof SSLSocket) {
+ return ((SSLSocket) socket).getSession();
+ } else {
+ return null;
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultProxyRoutePlanner.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultProxyRoutePlanner.java
new file mode 100644
index 000000000..fd569556c
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultProxyRoutePlanner.java
@@ -0,0 +1,66 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.conn.SchemePortResolver;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Implementation of an {@link ch.boye.httpclientandroidlib.conn.routing.HttpRoutePlanner}
+ * that routes requests through a default proxy.
+ *
+ * @since 4.3
+ */
+@Immutable
+public class DefaultProxyRoutePlanner extends DefaultRoutePlanner {
+
+ private final HttpHost proxy;
+
+ public DefaultProxyRoutePlanner(final HttpHost proxy, final SchemePortResolver schemePortResolver) {
+ super(schemePortResolver);
+ this.proxy = Args.notNull(proxy, "Proxy host");
+ }
+
+ public DefaultProxyRoutePlanner(final HttpHost proxy) {
+ this(proxy, null);
+ }
+
+ @Override
+ protected HttpHost determineProxy(
+ final HttpHost target,
+ final HttpRequest request,
+ final HttpContext context) throws HttpException {
+ return proxy;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultResponseParser.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultResponseParser.java
new file mode 100644
index 000000000..e82452ff5
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultResponseParser.java
@@ -0,0 +1,125 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpMessage;
+import ch.boye.httpclientandroidlib.HttpResponseFactory;
+import ch.boye.httpclientandroidlib.NoHttpResponseException;
+import ch.boye.httpclientandroidlib.ProtocolException;
+import ch.boye.httpclientandroidlib.StatusLine;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.impl.io.AbstractMessageParser;
+import ch.boye.httpclientandroidlib.io.SessionInputBuffer;
+import ch.boye.httpclientandroidlib.message.LineParser;
+import ch.boye.httpclientandroidlib.message.ParserCursor;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
+
+/**
+ * Default HTTP response parser implementation.
+ *
+ * The following parameters can be used to customize the behavior of this
+ * class:
+ *
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.2) use {@link DefaultHttpResponseParser}
+ */
+@Deprecated
+@ThreadSafe // no public methods
+public class DefaultResponseParser extends AbstractMessageParser {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ private final HttpResponseFactory responseFactory;
+ private final CharArrayBuffer lineBuf;
+ private final int maxGarbageLines;
+
+ public DefaultResponseParser(
+ final SessionInputBuffer buffer,
+ final LineParser parser,
+ final HttpResponseFactory responseFactory,
+ final HttpParams params) {
+ super(buffer, parser, params);
+ Args.notNull(responseFactory, "Response factory");
+ this.responseFactory = responseFactory;
+ this.lineBuf = new CharArrayBuffer(128);
+ this.maxGarbageLines = getMaxGarbageLines(params);
+ }
+
+ protected int getMaxGarbageLines(final HttpParams params) {
+ return params.getIntParameter(
+ ch.boye.httpclientandroidlib.conn.params.ConnConnectionPNames.MAX_STATUS_LINE_GARBAGE,
+ Integer.MAX_VALUE);
+ }
+
+ @Override
+ protected HttpMessage parseHead(
+ final SessionInputBuffer sessionBuffer) throws IOException, HttpException {
+ //read out the HTTP status string
+ int count = 0;
+ ParserCursor cursor = null;
+ do {
+ // clear the buffer
+ this.lineBuf.clear();
+ final int i = sessionBuffer.readLine(this.lineBuf);
+ if (i == -1 && count == 0) {
+ // The server just dropped connection on us
+ throw new NoHttpResponseException("The target server failed to respond");
+ }
+ cursor = new ParserCursor(0, this.lineBuf.length());
+ if (lineParser.hasProtocolVersion(this.lineBuf, cursor)) {
+ // Got one
+ break;
+ } else if (i == -1 || count >= this.maxGarbageLines) {
+ // Giving up
+ throw new ProtocolException("The server failed to respond with a " +
+ "valid HTTP response");
+ }
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Garbage in response: " + this.lineBuf.toString());
+ }
+ count++;
+ } while(true);
+ //create the status line from the status string
+ final StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, cursor);
+ return this.responseFactory.newHttpResponse(statusline, null);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultRoutePlanner.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultRoutePlanner.java
new file mode 100644
index 000000000..2c08a7118
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultRoutePlanner.java
@@ -0,0 +1,107 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.net.InetAddress;
+
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.ProtocolException;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.config.RequestConfig;
+import ch.boye.httpclientandroidlib.client.protocol.HttpClientContext;
+import ch.boye.httpclientandroidlib.conn.SchemePortResolver;
+import ch.boye.httpclientandroidlib.conn.UnsupportedSchemeException;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoutePlanner;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Default implementation of an {@link HttpRoutePlanner}. It will not make use of
+ * any Java system properties, nor of system or browser proxy settings.
+ *
+ * @since 4.3
+ */
+@Immutable
+public class DefaultRoutePlanner implements HttpRoutePlanner {
+
+ private final SchemePortResolver schemePortResolver;
+
+ public DefaultRoutePlanner(final SchemePortResolver schemePortResolver) {
+ super();
+ this.schemePortResolver = schemePortResolver != null ? schemePortResolver :
+ DefaultSchemePortResolver.INSTANCE;
+ }
+
+ public HttpRoute determineRoute(
+ final HttpHost host,
+ final HttpRequest request,
+ final HttpContext context) throws HttpException {
+ Args.notNull(request, "Request");
+ if (host == null) {
+ throw new ProtocolException("Target host is not specified");
+ }
+ final HttpClientContext clientContext = HttpClientContext.adapt(context);
+ final RequestConfig config = clientContext.getRequestConfig();
+ final InetAddress local = config.getLocalAddress();
+ HttpHost proxy = config.getProxy();
+ if (proxy == null) {
+ proxy = determineProxy(host, request, context);
+ }
+
+ final HttpHost target;
+ if (host.getPort() <= 0) {
+ try {
+ target = new HttpHost(
+ host.getHostName(),
+ this.schemePortResolver.resolve(host),
+ host.getSchemeName());
+ } catch (final UnsupportedSchemeException ex) {
+ throw new HttpException(ex.getMessage());
+ }
+ } else {
+ target = host;
+ }
+ final boolean secure = target.getSchemeName().equalsIgnoreCase("https");
+ if (proxy == null) {
+ return new HttpRoute(target, local, secure);
+ } else {
+ return new HttpRoute(target, local, proxy, secure);
+ }
+ }
+
+ protected HttpHost determineProxy(
+ final HttpHost target,
+ final HttpRequest request,
+ final HttpContext context) throws HttpException {
+ return null;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultSchemePortResolver.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultSchemePortResolver.java
new file mode 100644
index 000000000..4b384f681
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/DefaultSchemePortResolver.java
@@ -0,0 +1,61 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.conn.SchemePortResolver;
+import ch.boye.httpclientandroidlib.conn.UnsupportedSchemeException;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * Default {@link SchemePortResolver}.
+ *
+ * @since 4.3
+ */
+@Immutable
+public class DefaultSchemePortResolver implements SchemePortResolver {
+
+ public static final DefaultSchemePortResolver INSTANCE = new DefaultSchemePortResolver();
+
+ public int resolve(final HttpHost host) throws UnsupportedSchemeException {
+ Args.notNull(host, "HTTP host");
+ final int port = host.getPort();
+ if (port > 0) {
+ return port;
+ }
+ final String name = host.getSchemeName();
+ if (name.equalsIgnoreCase("http")) {
+ return 80;
+ } else if (name.equalsIgnoreCase("https")) {
+ return 443;
+ } else {
+ throw new UnsupportedSchemeException(name + " protocol is not supported");
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/HttpClientConnectionOperator.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/HttpClientConnectionOperator.java
new file mode 100644
index 000000000..a13368237
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/HttpClientConnectionOperator.java
@@ -0,0 +1,173 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+import java.net.ConnectException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.net.SocketTimeoutException;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.client.protocol.HttpClientContext;
+import ch.boye.httpclientandroidlib.config.Lookup;
+import ch.boye.httpclientandroidlib.config.SocketConfig;
+import ch.boye.httpclientandroidlib.conn.ConnectTimeoutException;
+import ch.boye.httpclientandroidlib.conn.DnsResolver;
+import ch.boye.httpclientandroidlib.conn.HttpHostConnectException;
+import ch.boye.httpclientandroidlib.conn.ManagedHttpClientConnection;
+import ch.boye.httpclientandroidlib.conn.SchemePortResolver;
+import ch.boye.httpclientandroidlib.conn.UnsupportedSchemeException;
+import ch.boye.httpclientandroidlib.conn.socket.ConnectionSocketFactory;
+import ch.boye.httpclientandroidlib.conn.socket.LayeredConnectionSocketFactory;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+
+@Immutable
+class HttpClientConnectionOperator {
+
+ static final String SOCKET_FACTORY_REGISTRY = "http.socket-factory-registry";
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ private final Lookup socketFactoryRegistry;
+ private final SchemePortResolver schemePortResolver;
+ private final DnsResolver dnsResolver;
+
+ HttpClientConnectionOperator(
+ final Lookup socketFactoryRegistry,
+ final SchemePortResolver schemePortResolver,
+ final DnsResolver dnsResolver) {
+ super();
+ Args.notNull(socketFactoryRegistry, "Socket factory registry");
+ this.socketFactoryRegistry = socketFactoryRegistry;
+ this.schemePortResolver = schemePortResolver != null ? schemePortResolver :
+ DefaultSchemePortResolver.INSTANCE;
+ this.dnsResolver = dnsResolver != null ? dnsResolver :
+ SystemDefaultDnsResolver.INSTANCE;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Lookup getSocketFactoryRegistry(final HttpContext context) {
+ Lookup reg = (Lookup) context.getAttribute(
+ SOCKET_FACTORY_REGISTRY);
+ if (reg == null) {
+ reg = this.socketFactoryRegistry;
+ }
+ return reg;
+ }
+
+ public void connect(
+ final ManagedHttpClientConnection conn,
+ final HttpHost host,
+ final InetSocketAddress localAddress,
+ final int connectTimeout,
+ final SocketConfig socketConfig,
+ final HttpContext context) throws IOException {
+ final Lookup registry = getSocketFactoryRegistry(context);
+ final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName());
+ if (sf == null) {
+ throw new UnsupportedSchemeException(host.getSchemeName() +
+ " protocol is not supported");
+ }
+ final InetAddress[] addresses = this.dnsResolver.resolve(host.getHostName());
+ final int port = this.schemePortResolver.resolve(host);
+ for (int i = 0; i < addresses.length; i++) {
+ final InetAddress address = addresses[i];
+ final boolean last = i == addresses.length - 1;
+
+ Socket sock = sf.createSocket(context);
+ sock.setSoTimeout(socketConfig.getSoTimeout());
+ sock.setReuseAddress(socketConfig.isSoReuseAddress());
+ sock.setTcpNoDelay(socketConfig.isTcpNoDelay());
+ sock.setKeepAlive(socketConfig.isSoKeepAlive());
+ final int linger = socketConfig.getSoLinger();
+ if (linger >= 0) {
+ sock.setSoLinger(linger > 0, linger);
+ }
+ conn.bind(sock);
+
+ final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Connecting to " + remoteAddress);
+ }
+ try {
+ sock = sf.connectSocket(
+ connectTimeout, sock, host, remoteAddress, localAddress, context);
+ conn.bind(sock);
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Connection established " + conn);
+ }
+ return;
+ } catch (final SocketTimeoutException ex) {
+ if (last) {
+ throw new ConnectTimeoutException(ex, host, addresses);
+ }
+ } catch (final ConnectException ex) {
+ if (last) {
+ final String msg = ex.getMessage();
+ if ("Connection timed out".equals(msg)) {
+ throw new ConnectTimeoutException(ex, host, addresses);
+ } else {
+ throw new HttpHostConnectException(ex, host, addresses);
+ }
+ }
+ }
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Connect to " + remoteAddress + " timed out. " +
+ "Connection will be retried using another IP address");
+ }
+ }
+ }
+
+ public void upgrade(
+ final ManagedHttpClientConnection conn,
+ final HttpHost host,
+ final HttpContext context) throws IOException {
+ final HttpClientContext clientContext = HttpClientContext.adapt(context);
+ final Lookup registry = getSocketFactoryRegistry(clientContext);
+ final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName());
+ if (sf == null) {
+ throw new UnsupportedSchemeException(host.getSchemeName() +
+ " protocol is not supported");
+ }
+ if (!(sf instanceof LayeredConnectionSocketFactory)) {
+ throw new UnsupportedSchemeException(host.getSchemeName() +
+ " protocol does not support connection upgrade");
+ }
+ final LayeredConnectionSocketFactory lsf = (LayeredConnectionSocketFactory) sf;
+ Socket sock = conn.getSocket();
+ final int port = this.schemePortResolver.resolve(host);
+ sock = lsf.createLayeredSocket(sock, host.getHostName(), port, context);
+ conn.bind(sock);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/HttpConnPool.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/HttpConnPool.java
new file mode 100644
index 000000000..e10bd6cf6
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/HttpConnPool.java
@@ -0,0 +1,84 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionOperator;
+import ch.boye.httpclientandroidlib.conn.OperatedClientConnection;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.pool.AbstractConnPool;
+import ch.boye.httpclientandroidlib.pool.ConnFactory;
+
+/**
+ * @since 4.2
+ *
+ * @deprecated (4.3) no longer used.
+ */
+@Deprecated
+class HttpConnPool extends AbstractConnPool {
+
+ private static final AtomicLong COUNTER = new AtomicLong();
+
+ public HttpClientAndroidLog log;
+ private final long timeToLive;
+ private final TimeUnit tunit;
+
+ public HttpConnPool(final HttpClientAndroidLog log,
+ final ClientConnectionOperator connOperator,
+ final int defaultMaxPerRoute, final int maxTotal,
+ final long timeToLive, final TimeUnit tunit) {
+ super(new InternalConnFactory(connOperator), defaultMaxPerRoute, maxTotal);
+ this.log = log;
+ this.timeToLive = timeToLive;
+ this.tunit = tunit;
+ }
+
+ @Override
+ protected HttpPoolEntry createEntry(final HttpRoute route, final OperatedClientConnection conn) {
+ final String id = Long.toString(COUNTER.getAndIncrement());
+ return new HttpPoolEntry(this.log, id, route, conn, this.timeToLive, this.tunit);
+ }
+
+ static class InternalConnFactory implements ConnFactory {
+
+ private final ClientConnectionOperator connOperator;
+
+ InternalConnFactory(final ClientConnectionOperator connOperator) {
+ this.connOperator = connOperator;
+ }
+
+ public OperatedClientConnection create(final HttpRoute route) throws IOException {
+ return connOperator.createConnection();
+ }
+
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/HttpPoolEntry.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/HttpPoolEntry.java
new file mode 100644
index 000000000..d04023126
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/HttpPoolEntry.java
@@ -0,0 +1,98 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+import java.util.Date;
+import java.util.concurrent.TimeUnit;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+import ch.boye.httpclientandroidlib.conn.OperatedClientConnection;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.conn.routing.RouteTracker;
+import ch.boye.httpclientandroidlib.pool.PoolEntry;
+
+/**
+ * @since 4.2
+ *
+ * @deprecated (4.3) no longer used.
+ */
+@Deprecated
+class HttpPoolEntry extends PoolEntry {
+
+ public HttpClientAndroidLog log;
+ private final RouteTracker tracker;
+
+ public HttpPoolEntry(
+ final HttpClientAndroidLog log,
+ final String id,
+ final HttpRoute route,
+ final OperatedClientConnection conn,
+ final long timeToLive, final TimeUnit tunit) {
+ super(id, route, conn, timeToLive, tunit);
+ this.log = log;
+ this.tracker = new RouteTracker(route);
+ }
+
+ @Override
+ public boolean isExpired(final long now) {
+ final boolean expired = super.isExpired(now);
+ if (expired && this.log.isDebugEnabled()) {
+ this.log.debug("Connection " + this + " expired @ " + new Date(getExpiry()));
+ }
+ return expired;
+ }
+
+ RouteTracker getTracker() {
+ return this.tracker;
+ }
+
+ HttpRoute getPlannedRoute() {
+ return getRoute();
+ }
+
+ HttpRoute getEffectiveRoute() {
+ return this.tracker.toRoute();
+ }
+
+ @Override
+ public boolean isClosed() {
+ final OperatedClientConnection conn = getConnection();
+ return !conn.isOpen();
+ }
+
+ @Override
+ public void close() {
+ final OperatedClientConnection conn = getConnection();
+ try {
+ conn.close();
+ } catch (final IOException ex) {
+ this.log.debug("I/O error closing connection", ex);
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/IdleConnectionHandler.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/IdleConnectionHandler.java
new file mode 100644
index 000000000..cbcd5d04f
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/IdleConnectionHandler.java
@@ -0,0 +1,181 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.TimeUnit;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.HttpConnection;
+
+// Currently only used by AbstractConnPool
+/**
+ * A helper class for connection managers to track idle connections.
+ *
+ *
This class is not synchronized.
+ *
+ * @see ch.boye.httpclientandroidlib.conn.ClientConnectionManager#closeIdleConnections
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.1) no longer used
+ */
+@Deprecated
+public class IdleConnectionHandler {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ /** Holds connections and the time they were added. */
+ private final Map connectionToTimes;
+
+
+ public IdleConnectionHandler() {
+ super();
+ connectionToTimes = new HashMap();
+ }
+
+ /**
+ * Registers the given connection with this handler. The connection will be held until
+ * {@link #remove} or {@link #closeIdleConnections} is called.
+ *
+ * @param connection the connection to add
+ *
+ * @see #remove
+ */
+ public void add(final HttpConnection connection, final long validDuration, final TimeUnit unit) {
+
+ final long timeAdded = System.currentTimeMillis();
+
+ if (log.isDebugEnabled()) {
+ log.debug("Adding connection at: " + timeAdded);
+ }
+
+ connectionToTimes.put(connection, new TimeValues(timeAdded, validDuration, unit));
+ }
+
+ /**
+ * Removes the given connection from the list of connections to be closed when idle.
+ * This will return true if the connection is still valid, and false
+ * if the connection should be considered expired and not used.
+ *
+ * @param connection
+ * @return True if the connection is still valid.
+ */
+ public boolean remove(final HttpConnection connection) {
+ final TimeValues times = connectionToTimes.remove(connection);
+ if(times == null) {
+ log.warn("Removing a connection that never existed!");
+ return true;
+ } else {
+ return System.currentTimeMillis() <= times.timeExpires;
+ }
+ }
+
+ /**
+ * Removes all connections referenced by this handler.
+ */
+ public void removeAll() {
+ this.connectionToTimes.clear();
+ }
+
+ /**
+ * Closes connections that have been idle for at least the given amount of time.
+ *
+ * @param idleTime the minimum idle time, in milliseconds, for connections to be closed
+ */
+ public void closeIdleConnections(final long idleTime) {
+
+ // the latest time for which connections will be closed
+ final long idleTimeout = System.currentTimeMillis() - idleTime;
+
+ if (log.isDebugEnabled()) {
+ log.debug("Checking for connections, idle timeout: " + idleTimeout);
+ }
+
+ for (final Entry entry : connectionToTimes.entrySet()) {
+ final HttpConnection conn = entry.getKey();
+ final TimeValues times = entry.getValue();
+ final long connectionTime = times.timeAdded;
+ if (connectionTime <= idleTimeout) {
+ if (log.isDebugEnabled()) {
+ log.debug("Closing idle connection, connection time: " + connectionTime);
+ }
+ try {
+ conn.close();
+ } catch (final IOException ex) {
+ log.debug("I/O error closing connection", ex);
+ }
+ }
+ }
+ }
+
+
+ public void closeExpiredConnections() {
+ final long now = System.currentTimeMillis();
+ if (log.isDebugEnabled()) {
+ log.debug("Checking for expired connections, now: " + now);
+ }
+
+ for (final Entry entry : connectionToTimes.entrySet()) {
+ final HttpConnection conn = entry.getKey();
+ final TimeValues times = entry.getValue();
+ if(times.timeExpires <= now) {
+ if (log.isDebugEnabled()) {
+ log.debug("Closing connection, expired @: " + times.timeExpires);
+ }
+ try {
+ conn.close();
+ } catch (final IOException ex) {
+ log.debug("I/O error closing connection", ex);
+ }
+ }
+ }
+ }
+
+ private static class TimeValues {
+ private final long timeAdded;
+ private final long timeExpires;
+
+ /**
+ * @param now The current time in milliseconds
+ * @param validDuration The duration this connection is valid for
+ * @param validUnit The unit of time the duration is specified in.
+ */
+ TimeValues(final long now, final long validDuration, final TimeUnit validUnit) {
+ this.timeAdded = now;
+ if(validDuration > 0) {
+ this.timeExpires = now + validUnit.toMillis(validDuration);
+ } else {
+ this.timeExpires = Long.MAX_VALUE;
+ }
+ }
+ }
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/InMemoryDnsResolver.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/InMemoryDnsResolver.java
new file mode 100644
index 000000000..34f02b11b
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/InMemoryDnsResolver.java
@@ -0,0 +1,94 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.conn.DnsResolver;
+import ch.boye.httpclientandroidlib.util.Args;
+
+/**
+ * In-memory {@link DnsResolver} implementation.
+ *
+ * @since 4.2
+ */
+public class InMemoryDnsResolver implements DnsResolver {
+
+ /** Logger associated to this class. */
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(InMemoryDnsResolver.class);
+
+ /**
+ * In-memory collection that will hold the associations between a host name
+ * and an array of InetAddress instances.
+ */
+ private final Map dnsMap;
+
+ /**
+ * Builds a DNS resolver that will resolve the host names against a
+ * collection held in-memory.
+ */
+ public InMemoryDnsResolver() {
+ dnsMap = new ConcurrentHashMap();
+ }
+
+ /**
+ * Associates the given array of IP addresses to the given host in this DNS overrider.
+ * The IP addresses are assumed to be already resolved.
+ *
+ * @param host
+ * The host name to be associated with the given IP.
+ * @param ips
+ * array of IP addresses to be resolved by this DNS overrider to the given
+ * host name.
+ */
+ public void add(final String host, final InetAddress... ips) {
+ Args.notNull(host, "Host name");
+ Args.notNull(ips, "Array of IP addresses");
+ dnsMap.put(host, ips);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public InetAddress[] resolve(final String host) throws UnknownHostException {
+ final InetAddress[] resolvedAddresses = dnsMap.get(host);
+ if (log.isInfoEnabled()) {
+ log.info("Resolving " + host + " to " + Arrays.deepToString(resolvedAddresses));
+ }
+ if(resolvedAddresses == null){
+ throw new UnknownHostException(host + " cannot be resolved");
+ }
+ return resolvedAddresses;
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/LoggingInputStream.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/LoggingInputStream.java
new file mode 100644
index 000000000..0c117395c
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/LoggingInputStream.java
@@ -0,0 +1,145 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Internal class.
+ *
+ * @since 4.3
+ */
+@NotThreadSafe
+class LoggingInputStream extends InputStream {
+
+ private final InputStream in;
+ private final Wire wire;
+
+ public LoggingInputStream(final InputStream in, final Wire wire) {
+ super();
+ this.in = in;
+ this.wire = wire;
+ }
+
+ @Override
+ public int read() throws IOException {
+ try {
+ final int b = in.read();
+ if (b == -1) {
+ wire.input("end of stream");
+ } else {
+ wire.input(b);
+ }
+ return b;
+ } catch (IOException ex) {
+ wire.input("[read] I/O error: " + ex.getMessage());
+ throw ex;
+ }
+ }
+
+ @Override
+ public int read(final byte[] b) throws IOException {
+ try {
+ final int bytesRead = in.read(b);
+ if (bytesRead == -1) {
+ wire.input("end of stream");
+ } else if (bytesRead > 0) {
+ wire.input(b, 0, bytesRead);
+ }
+ return bytesRead;
+ } catch (IOException ex) {
+ wire.input("[read] I/O error: " + ex.getMessage());
+ throw ex;
+ }
+ }
+
+ @Override
+ public int read(final byte[] b, final int off, final int len) throws IOException {
+ try {
+ final int bytesRead = in.read(b, off, len);
+ if (bytesRead == -1) {
+ wire.input("end of stream");
+ } else if (bytesRead > 0) {
+ wire.input(b, off, bytesRead);
+ }
+ return bytesRead;
+ } catch (IOException ex) {
+ wire.input("[read] I/O error: " + ex.getMessage());
+ throw ex;
+ }
+ }
+
+ @Override
+ public long skip(final long n) throws IOException {
+ try {
+ return super.skip(n);
+ } catch (IOException ex) {
+ wire.input("[skip] I/O error: " + ex.getMessage());
+ throw ex;
+ }
+ }
+
+ @Override
+ public int available() throws IOException {
+ try {
+ return in.available();
+ } catch (IOException ex) {
+ wire.input("[available] I/O error : " + ex.getMessage());
+ throw ex;
+ }
+ }
+
+ @Override
+ public void mark(final int readlimit) {
+ super.mark(readlimit);
+ }
+
+ @Override
+ public void reset() throws IOException {
+ super.reset();
+ }
+
+ @Override
+ public boolean markSupported() {
+ return false;
+ }
+
+ @Override
+ public void close() throws IOException {
+ try {
+ in.close();
+ } catch (IOException ex) {
+ wire.input("[close] I/O error: " + ex.getMessage());
+ throw ex;
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/LoggingManagedHttpClientConnection.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/LoggingManagedHttpClientConnection.java
new file mode 100644
index 000000000..5b06179c0
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/LoggingManagedHttpClientConnection.java
@@ -0,0 +1,132 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+import ch.boye.httpclientandroidlib.Header;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.config.MessageConstraints;
+import ch.boye.httpclientandroidlib.entity.ContentLengthStrategy;
+import ch.boye.httpclientandroidlib.io.HttpMessageParserFactory;
+import ch.boye.httpclientandroidlib.io.HttpMessageWriterFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.Socket;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CharsetEncoder;
+
+@NotThreadSafe
+class LoggingManagedHttpClientConnection extends DefaultManagedHttpClientConnection {
+
+ public HttpClientAndroidLog log;
+ private final HttpClientAndroidLog headerlog;
+ private final Wire wire;
+
+ public LoggingManagedHttpClientConnection(
+ final String id,
+ final HttpClientAndroidLog log,
+ final HttpClientAndroidLog headerlog,
+ final HttpClientAndroidLog wirelog,
+ final int buffersize,
+ final int fragmentSizeHint,
+ final CharsetDecoder chardecoder,
+ final CharsetEncoder charencoder,
+ final MessageConstraints constraints,
+ final ContentLengthStrategy incomingContentStrategy,
+ final ContentLengthStrategy outgoingContentStrategy,
+ final HttpMessageWriterFactory requestWriterFactory,
+ final HttpMessageParserFactory responseParserFactory) {
+ super(id, buffersize, fragmentSizeHint, chardecoder, charencoder,
+ constraints, incomingContentStrategy, outgoingContentStrategy,
+ requestWriterFactory, responseParserFactory);
+ this.log = log;
+ this.headerlog = headerlog;
+ this.wire = new Wire(wirelog, id);
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug(getId() + ": Close connection");
+ }
+ super.close();
+ }
+
+ @Override
+ public void shutdown() throws IOException {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug(getId() + ": Shutdown connection");
+ }
+ super.shutdown();
+ }
+
+ @Override
+ protected InputStream getSocketInputStream(final Socket socket) throws IOException {
+ InputStream in = super.getSocketInputStream(socket);
+ if (this.wire.enabled()) {
+ in = new LoggingInputStream(in, this.wire);
+ }
+ return in;
+ }
+
+ @Override
+ protected OutputStream getSocketOutputStream(final Socket socket) throws IOException {
+ OutputStream out = super.getSocketOutputStream(socket);
+ if (this.wire.enabled()) {
+ out = new LoggingOutputStream(out, this.wire);
+ }
+ return out;
+ }
+
+ @Override
+ protected void onResponseReceived(final HttpResponse response) {
+ if (response != null && this.headerlog.isDebugEnabled()) {
+ this.headerlog.debug(getId() + " << " + response.getStatusLine().toString());
+ final Header[] headers = response.getAllHeaders();
+ for (final Header header : headers) {
+ this.headerlog.debug(getId() + " << " + header.toString());
+ }
+ }
+ }
+
+ @Override
+ protected void onRequestSubmitted(final HttpRequest request) {
+ if (request != null && this.headerlog.isDebugEnabled()) {
+ this.headerlog.debug(getId() + " >> " + request.getRequestLine().toString());
+ final Header[] headers = request.getAllHeaders();
+ for (final Header header : headers) {
+ this.headerlog.debug(getId() + " >> " + header.toString());
+ }
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/LoggingOutputStream.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/LoggingOutputStream.java
new file mode 100644
index 000000000..86c47b502
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/LoggingOutputStream.java
@@ -0,0 +1,104 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * Internal class.
+ *
+ * @since 4.3
+ */
+@NotThreadSafe
+class LoggingOutputStream extends OutputStream {
+
+ private final OutputStream out;
+ private final Wire wire;
+
+ public LoggingOutputStream(final OutputStream out, final Wire wire) {
+ super();
+ this.out = out;
+ this.wire = wire;
+ }
+
+ @Override
+ public void write(final int b) throws IOException {
+ try {
+ wire.output(b);
+ } catch (IOException ex) {
+ wire.output("[write] I/O error: " + ex.getMessage());
+ throw ex;
+ }
+ }
+
+ @Override
+ public void write(final byte[] b) throws IOException {
+ try {
+ wire.output(b);
+ out.write(b);
+ } catch (IOException ex) {
+ wire.output("[write] I/O error: " + ex.getMessage());
+ throw ex;
+ }
+ }
+
+ @Override
+ public void write(final byte[] b, final int off, final int len) throws IOException {
+ try {
+ wire.output(b, off, len);
+ out.write(b, off, len);
+ } catch (IOException ex) {
+ wire.output("[write] I/O error: " + ex.getMessage());
+ throw ex;
+ }
+ }
+
+ @Override
+ public void flush() throws IOException {
+ try {
+ out.flush();
+ } catch (IOException ex) {
+ wire.output("[flush] I/O error: " + ex.getMessage());
+ throw ex;
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ try {
+ out.close();
+ } catch (IOException ex) {
+ wire.output("[close] I/O error: " + ex.getMessage());
+ throw ex;
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/LoggingSessionInputBuffer.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/LoggingSessionInputBuffer.java
new file mode 100644
index 000000000..95617206e
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/LoggingSessionInputBuffer.java
@@ -0,0 +1,138 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.Consts;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.io.EofSensor;
+import ch.boye.httpclientandroidlib.io.HttpTransportMetrics;
+import ch.boye.httpclientandroidlib.io.SessionInputBuffer;
+import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
+
+/**
+ * Logs all data read to the wire LOG.
+ *
+ * @since 4.0
+ *
+ * @deprecated (4.3) no longer used.
+ */
+@Immutable
+@Deprecated
+public class LoggingSessionInputBuffer implements SessionInputBuffer, EofSensor {
+
+ /** Original session input buffer. */
+ private final SessionInputBuffer in;
+
+ private final EofSensor eofSensor;
+
+ /** The wire log to use for writing. */
+ private final Wire wire;
+
+ private final String charset;
+
+ /**
+ * Create an instance that wraps the specified session input buffer.
+ * @param in The session input buffer.
+ * @param wire The wire log to use.
+ * @param charset protocol charset, ASCII if null
+ */
+ public LoggingSessionInputBuffer(
+ final SessionInputBuffer in, final Wire wire, final String charset) {
+ super();
+ this.in = in;
+ this.eofSensor = in instanceof EofSensor ? (EofSensor) in : null;
+ this.wire = wire;
+ this.charset = charset != null ? charset : Consts.ASCII.name();
+ }
+
+ public LoggingSessionInputBuffer(final SessionInputBuffer in, final Wire wire) {
+ this(in, wire, null);
+ }
+
+ public boolean isDataAvailable(final int timeout) throws IOException {
+ return this.in.isDataAvailable(timeout);
+ }
+
+ public int read(final byte[] b, final int off, final int len) throws IOException {
+ final int l = this.in.read(b, off, len);
+ if (this.wire.enabled() && l > 0) {
+ this.wire.input(b, off, l);
+ }
+ return l;
+ }
+
+ public int read() throws IOException {
+ final int l = this.in.read();
+ if (this.wire.enabled() && l != -1) {
+ this.wire.input(l);
+ }
+ return l;
+ }
+
+ public int read(final byte[] b) throws IOException {
+ final int l = this.in.read(b);
+ if (this.wire.enabled() && l > 0) {
+ this.wire.input(b, 0, l);
+ }
+ return l;
+ }
+
+ public String readLine() throws IOException {
+ final String s = this.in.readLine();
+ if (this.wire.enabled() && s != null) {
+ final String tmp = s + "\r\n";
+ this.wire.input(tmp.getBytes(this.charset));
+ }
+ return s;
+ }
+
+ public int readLine(final CharArrayBuffer buffer) throws IOException {
+ final int l = this.in.readLine(buffer);
+ if (this.wire.enabled() && l >= 0) {
+ final int pos = buffer.length() - l;
+ final String s = new String(buffer.buffer(), pos, l);
+ final String tmp = s + "\r\n";
+ this.wire.input(tmp.getBytes(this.charset));
+ }
+ return l;
+ }
+
+ public HttpTransportMetrics getMetrics() {
+ return this.in.getMetrics();
+ }
+
+ public boolean isEof() {
+ if (this.eofSensor != null) {
+ return this.eofSensor.isEof();
+ } else {
+ return false;
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/LoggingSessionOutputBuffer.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/LoggingSessionOutputBuffer.java
new file mode 100644
index 000000000..bf1100b4e
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/LoggingSessionOutputBuffer.java
@@ -0,0 +1,118 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+
+import ch.boye.httpclientandroidlib.Consts;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.io.HttpTransportMetrics;
+import ch.boye.httpclientandroidlib.io.SessionOutputBuffer;
+import ch.boye.httpclientandroidlib.util.CharArrayBuffer;
+
+/**
+ * Logs all data written to the wire LOG.
+ * @since 4.0
+ * @deprecated (4.3) no longer used.
+ */
+@Immutable
+@Deprecated
+public class LoggingSessionOutputBuffer implements SessionOutputBuffer {
+
+ /** Original data transmitter. */
+ private final SessionOutputBuffer out;
+
+ /** The wire log to use. */
+ private final Wire wire;
+
+ private final String charset;
+
+ /**
+ * Create an instance that wraps the specified session output buffer.
+ * @param out The session output buffer.
+ * @param wire The Wire log to use.
+ * @param charset protocol charset, ASCII if null
+ */
+ public LoggingSessionOutputBuffer(
+ final SessionOutputBuffer out, final Wire wire, final String charset) {
+ super();
+ this.out = out;
+ this.wire = wire;
+ this.charset = charset != null ? charset : Consts.ASCII.name();
+ }
+
+ public LoggingSessionOutputBuffer(final SessionOutputBuffer out, final Wire wire) {
+ this(out, wire, null);
+ }
+
+ public void write(final byte[] b, final int off, final int len) throws IOException {
+ this.out.write(b, off, len);
+ if (this.wire.enabled()) {
+ this.wire.output(b, off, len);
+ }
+ }
+
+ public void write(final int b) throws IOException {
+ this.out.write(b);
+ if (this.wire.enabled()) {
+ this.wire.output(b);
+ }
+ }
+
+ public void write(final byte[] b) throws IOException {
+ this.out.write(b);
+ if (this.wire.enabled()) {
+ this.wire.output(b);
+ }
+ }
+
+ public void flush() throws IOException {
+ this.out.flush();
+ }
+
+ public void writeLine(final CharArrayBuffer buffer) throws IOException {
+ this.out.writeLine(buffer);
+ if (this.wire.enabled()) {
+ final String s = new String(buffer.buffer(), 0, buffer.length());
+ final String tmp = s + "\r\n";
+ this.wire.output(tmp.getBytes(this.charset));
+ }
+ }
+
+ public void writeLine(final String s) throws IOException {
+ this.out.writeLine(s);
+ if (this.wire.enabled()) {
+ final String tmp = s + "\r\n";
+ this.wire.output(tmp.getBytes(this.charset));
+ }
+ }
+
+ public HttpTransportMetrics getMetrics() {
+ return this.out.getMetrics();
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/ManagedClientConnectionImpl.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/ManagedClientConnectionImpl.java
new file mode 100644
index 000000000..d1db2d8eb
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/ManagedClientConnectionImpl.java
@@ -0,0 +1,461 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.util.concurrent.TimeUnit;
+
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocket;
+
+import ch.boye.httpclientandroidlib.HttpConnectionMetrics;
+import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionOperator;
+import ch.boye.httpclientandroidlib.conn.ManagedClientConnection;
+import ch.boye.httpclientandroidlib.conn.OperatedClientConnection;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.conn.routing.RouteTracker;
+import ch.boye.httpclientandroidlib.params.HttpParams;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.Asserts;
+
+/**
+ * @since 4.2
+ *
+ * @deprecated (4.3) use {@link ManagedHttpClientConnectionFactory}.
+ */
+@Deprecated
+@NotThreadSafe
+class ManagedClientConnectionImpl implements ManagedClientConnection {
+
+ private final ClientConnectionManager manager;
+ private final ClientConnectionOperator operator;
+ private volatile HttpPoolEntry poolEntry;
+ private volatile boolean reusable;
+ private volatile long duration;
+
+ ManagedClientConnectionImpl(
+ final ClientConnectionManager manager,
+ final ClientConnectionOperator operator,
+ final HttpPoolEntry entry) {
+ super();
+ Args.notNull(manager, "Connection manager");
+ Args.notNull(operator, "Connection operator");
+ Args.notNull(entry, "HTTP pool entry");
+ this.manager = manager;
+ this.operator = operator;
+ this.poolEntry = entry;
+ this.reusable = false;
+ this.duration = Long.MAX_VALUE;
+ }
+
+ public String getId() {
+ return null;
+ }
+
+ HttpPoolEntry getPoolEntry() {
+ return this.poolEntry;
+ }
+
+ HttpPoolEntry detach() {
+ final HttpPoolEntry local = this.poolEntry;
+ this.poolEntry = null;
+ return local;
+ }
+
+ public ClientConnectionManager getManager() {
+ return this.manager;
+ }
+
+ private OperatedClientConnection getConnection() {
+ final HttpPoolEntry local = this.poolEntry;
+ if (local == null) {
+ return null;
+ }
+ return local.getConnection();
+ }
+
+ private OperatedClientConnection ensureConnection() {
+ final HttpPoolEntry local = this.poolEntry;
+ if (local == null) {
+ throw new ConnectionShutdownException();
+ }
+ return local.getConnection();
+ }
+
+ private HttpPoolEntry ensurePoolEntry() {
+ final HttpPoolEntry local = this.poolEntry;
+ if (local == null) {
+ throw new ConnectionShutdownException();
+ }
+ return local;
+ }
+
+ public void close() throws IOException {
+ final HttpPoolEntry local = this.poolEntry;
+ if (local != null) {
+ final OperatedClientConnection conn = local.getConnection();
+ local.getTracker().reset();
+ conn.close();
+ }
+ }
+
+ public void shutdown() throws IOException {
+ final HttpPoolEntry local = this.poolEntry;
+ if (local != null) {
+ final OperatedClientConnection conn = local.getConnection();
+ local.getTracker().reset();
+ conn.shutdown();
+ }
+ }
+
+ public boolean isOpen() {
+ final OperatedClientConnection conn = getConnection();
+ if (conn != null) {
+ return conn.isOpen();
+ } else {
+ return false;
+ }
+ }
+
+ public boolean isStale() {
+ final OperatedClientConnection conn = getConnection();
+ if (conn != null) {
+ return conn.isStale();
+ } else {
+ return true;
+ }
+ }
+
+ public void setSocketTimeout(final int timeout) {
+ final OperatedClientConnection conn = ensureConnection();
+ conn.setSocketTimeout(timeout);
+ }
+
+ public int getSocketTimeout() {
+ final OperatedClientConnection conn = ensureConnection();
+ return conn.getSocketTimeout();
+ }
+
+ public HttpConnectionMetrics getMetrics() {
+ final OperatedClientConnection conn = ensureConnection();
+ return conn.getMetrics();
+ }
+
+ public void flush() throws IOException {
+ final OperatedClientConnection conn = ensureConnection();
+ conn.flush();
+ }
+
+ public boolean isResponseAvailable(final int timeout) throws IOException {
+ final OperatedClientConnection conn = ensureConnection();
+ return conn.isResponseAvailable(timeout);
+ }
+
+ public void receiveResponseEntity(
+ final HttpResponse response) throws HttpException, IOException {
+ final OperatedClientConnection conn = ensureConnection();
+ conn.receiveResponseEntity(response);
+ }
+
+ public HttpResponse receiveResponseHeader() throws HttpException, IOException {
+ final OperatedClientConnection conn = ensureConnection();
+ return conn.receiveResponseHeader();
+ }
+
+ public void sendRequestEntity(
+ final HttpEntityEnclosingRequest request) throws HttpException, IOException {
+ final OperatedClientConnection conn = ensureConnection();
+ conn.sendRequestEntity(request);
+ }
+
+ public void sendRequestHeader(
+ final HttpRequest request) throws HttpException, IOException {
+ final OperatedClientConnection conn = ensureConnection();
+ conn.sendRequestHeader(request);
+ }
+
+ public InetAddress getLocalAddress() {
+ final OperatedClientConnection conn = ensureConnection();
+ return conn.getLocalAddress();
+ }
+
+ public int getLocalPort() {
+ final OperatedClientConnection conn = ensureConnection();
+ return conn.getLocalPort();
+ }
+
+ public InetAddress getRemoteAddress() {
+ final OperatedClientConnection conn = ensureConnection();
+ return conn.getRemoteAddress();
+ }
+
+ public int getRemotePort() {
+ final OperatedClientConnection conn = ensureConnection();
+ return conn.getRemotePort();
+ }
+
+ public boolean isSecure() {
+ final OperatedClientConnection conn = ensureConnection();
+ return conn.isSecure();
+ }
+
+ public void bind(final Socket socket) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ public Socket getSocket() {
+ final OperatedClientConnection conn = ensureConnection();
+ return conn.getSocket();
+ }
+
+ public SSLSession getSSLSession() {
+ final OperatedClientConnection conn = ensureConnection();
+ SSLSession result = null;
+ final Socket sock = conn.getSocket();
+ if (sock instanceof SSLSocket) {
+ result = ((SSLSocket)sock).getSession();
+ }
+ return result;
+ }
+
+ public Object getAttribute(final String id) {
+ final OperatedClientConnection conn = ensureConnection();
+ if (conn instanceof HttpContext) {
+ return ((HttpContext) conn).getAttribute(id);
+ } else {
+ return null;
+ }
+ }
+
+ public Object removeAttribute(final String id) {
+ final OperatedClientConnection conn = ensureConnection();
+ if (conn instanceof HttpContext) {
+ return ((HttpContext) conn).removeAttribute(id);
+ } else {
+ return null;
+ }
+ }
+
+ public void setAttribute(final String id, final Object obj) {
+ final OperatedClientConnection conn = ensureConnection();
+ if (conn instanceof HttpContext) {
+ ((HttpContext) conn).setAttribute(id, obj);
+ }
+ }
+
+ public HttpRoute getRoute() {
+ final HttpPoolEntry local = ensurePoolEntry();
+ return local.getEffectiveRoute();
+ }
+
+ public void open(
+ final HttpRoute route,
+ final HttpContext context,
+ final HttpParams params) throws IOException {
+ Args.notNull(route, "Route");
+ Args.notNull(params, "HTTP parameters");
+ final OperatedClientConnection conn;
+ synchronized (this) {
+ if (this.poolEntry == null) {
+ throw new ConnectionShutdownException();
+ }
+ final RouteTracker tracker = this.poolEntry.getTracker();
+ Asserts.notNull(tracker, "Route tracker");
+ Asserts.check(!tracker.isConnected(), "Connection already open");
+ conn = this.poolEntry.getConnection();
+ }
+
+ final HttpHost proxy = route.getProxyHost();
+ this.operator.openConnection(
+ conn,
+ (proxy != null) ? proxy : route.getTargetHost(),
+ route.getLocalAddress(),
+ context, params);
+
+ synchronized (this) {
+ if (this.poolEntry == null) {
+ throw new InterruptedIOException();
+ }
+ final RouteTracker tracker = this.poolEntry.getTracker();
+ if (proxy == null) {
+ tracker.connectTarget(conn.isSecure());
+ } else {
+ tracker.connectProxy(proxy, conn.isSecure());
+ }
+ }
+ }
+
+ public void tunnelTarget(
+ final boolean secure, final HttpParams params) throws IOException {
+ Args.notNull(params, "HTTP parameters");
+ final HttpHost target;
+ final OperatedClientConnection conn;
+ synchronized (this) {
+ if (this.poolEntry == null) {
+ throw new ConnectionShutdownException();
+ }
+ final RouteTracker tracker = this.poolEntry.getTracker();
+ Asserts.notNull(tracker, "Route tracker");
+ Asserts.check(tracker.isConnected(), "Connection not open");
+ Asserts.check(!tracker.isTunnelled(), "Connection is already tunnelled");
+ target = tracker.getTargetHost();
+ conn = this.poolEntry.getConnection();
+ }
+
+ conn.update(null, target, secure, params);
+
+ synchronized (this) {
+ if (this.poolEntry == null) {
+ throw new InterruptedIOException();
+ }
+ final RouteTracker tracker = this.poolEntry.getTracker();
+ tracker.tunnelTarget(secure);
+ }
+ }
+
+ public void tunnelProxy(
+ final HttpHost next, final boolean secure, final HttpParams params) throws IOException {
+ Args.notNull(next, "Next proxy");
+ Args.notNull(params, "HTTP parameters");
+ final OperatedClientConnection conn;
+ synchronized (this) {
+ if (this.poolEntry == null) {
+ throw new ConnectionShutdownException();
+ }
+ final RouteTracker tracker = this.poolEntry.getTracker();
+ Asserts.notNull(tracker, "Route tracker");
+ Asserts.check(tracker.isConnected(), "Connection not open");
+ conn = this.poolEntry.getConnection();
+ }
+
+ conn.update(null, next, secure, params);
+
+ synchronized (this) {
+ if (this.poolEntry == null) {
+ throw new InterruptedIOException();
+ }
+ final RouteTracker tracker = this.poolEntry.getTracker();
+ tracker.tunnelProxy(next, secure);
+ }
+ }
+
+ public void layerProtocol(
+ final HttpContext context, final HttpParams params) throws IOException {
+ Args.notNull(params, "HTTP parameters");
+ final HttpHost target;
+ final OperatedClientConnection conn;
+ synchronized (this) {
+ if (this.poolEntry == null) {
+ throw new ConnectionShutdownException();
+ }
+ final RouteTracker tracker = this.poolEntry.getTracker();
+ Asserts.notNull(tracker, "Route tracker");
+ Asserts.check(tracker.isConnected(), "Connection not open");
+ Asserts.check(tracker.isTunnelled(), "Protocol layering without a tunnel not supported");
+ Asserts.check(!tracker.isLayered(), "Multiple protocol layering not supported");
+ target = tracker.getTargetHost();
+ conn = this.poolEntry.getConnection();
+ }
+ this.operator.updateSecureConnection(conn, target, context, params);
+
+ synchronized (this) {
+ if (this.poolEntry == null) {
+ throw new InterruptedIOException();
+ }
+ final RouteTracker tracker = this.poolEntry.getTracker();
+ tracker.layerProtocol(conn.isSecure());
+ }
+ }
+
+ public Object getState() {
+ final HttpPoolEntry local = ensurePoolEntry();
+ return local.getState();
+ }
+
+ public void setState(final Object state) {
+ final HttpPoolEntry local = ensurePoolEntry();
+ local.setState(state);
+ }
+
+ public void markReusable() {
+ this.reusable = true;
+ }
+
+ public void unmarkReusable() {
+ this.reusable = false;
+ }
+
+ public boolean isMarkedReusable() {
+ return this.reusable;
+ }
+
+ public void setIdleDuration(final long duration, final TimeUnit unit) {
+ if(duration > 0) {
+ this.duration = unit.toMillis(duration);
+ } else {
+ this.duration = -1;
+ }
+ }
+
+ public void releaseConnection() {
+ synchronized (this) {
+ if (this.poolEntry == null) {
+ return;
+ }
+ this.manager.releaseConnection(this, this.duration, TimeUnit.MILLISECONDS);
+ this.poolEntry = null;
+ }
+ }
+
+ public void abortConnection() {
+ synchronized (this) {
+ if (this.poolEntry == null) {
+ return;
+ }
+ this.reusable = false;
+ final OperatedClientConnection conn = this.poolEntry.getConnection();
+ try {
+ conn.shutdown();
+ } catch (final IOException ignore) {
+ }
+ this.manager.releaseConnection(this, this.duration, TimeUnit.MILLISECONDS);
+ this.poolEntry = null;
+ }
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/ManagedHttpClientConnectionFactory.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/ManagedHttpClientConnectionFactory.java
new file mode 100644
index 000000000..51b3844f9
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/ManagedHttpClientConnectionFactory.java
@@ -0,0 +1,121 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CharsetEncoder;
+import java.nio.charset.CodingErrorAction;
+import java.util.concurrent.atomic.AtomicLong;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.HttpResponse;
+import ch.boye.httpclientandroidlib.annotation.Immutable;
+import ch.boye.httpclientandroidlib.config.ConnectionConfig;
+import ch.boye.httpclientandroidlib.conn.HttpConnectionFactory;
+import ch.boye.httpclientandroidlib.conn.ManagedHttpClientConnection;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.impl.io.DefaultHttpRequestWriterFactory;
+import ch.boye.httpclientandroidlib.io.HttpMessageParserFactory;
+import ch.boye.httpclientandroidlib.io.HttpMessageWriterFactory;
+
+/**
+ * Factory for {@link ManagedHttpClientConnection} instances.
+ * @since 4.3
+ */
+@Immutable
+public class ManagedHttpClientConnectionFactory
+ implements HttpConnectionFactory {
+
+ private static final AtomicLong COUNTER = new AtomicLong();
+
+ public static final ManagedHttpClientConnectionFactory INSTANCE = new ManagedHttpClientConnectionFactory();
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(DefaultManagedHttpClientConnection.class);
+ public HttpClientAndroidLog headerlog = new HttpClientAndroidLog("ch.boye.httpclientandroidlib.headers");
+ public HttpClientAndroidLog wirelog = new HttpClientAndroidLog("ch.boye.httpclientandroidlib.wire");
+
+ private final HttpMessageWriterFactory requestWriterFactory;
+ private final HttpMessageParserFactory responseParserFactory;
+
+ public ManagedHttpClientConnectionFactory(
+ final HttpMessageWriterFactory requestWriterFactory,
+ final HttpMessageParserFactory responseParserFactory) {
+ super();
+ this.requestWriterFactory = requestWriterFactory != null ? requestWriterFactory :
+ DefaultHttpRequestWriterFactory.INSTANCE;
+ this.responseParserFactory = responseParserFactory != null ? responseParserFactory :
+ DefaultHttpResponseParserFactory.INSTANCE;
+ }
+
+ public ManagedHttpClientConnectionFactory(
+ final HttpMessageParserFactory responseParserFactory) {
+ this(null, responseParserFactory);
+ }
+
+ public ManagedHttpClientConnectionFactory() {
+ this(null, null);
+ }
+
+ public ManagedHttpClientConnection create(final HttpRoute route, final ConnectionConfig config) {
+ final ConnectionConfig cconfig = config != null ? config : ConnectionConfig.DEFAULT;
+ CharsetDecoder chardecoder = null;
+ CharsetEncoder charencoder = null;
+ final Charset charset = cconfig.getCharset();
+ final CodingErrorAction malformedInputAction = cconfig.getMalformedInputAction() != null ?
+ cconfig.getMalformedInputAction() : CodingErrorAction.REPORT;
+ final CodingErrorAction unmappableInputAction = cconfig.getUnmappableInputAction() != null ?
+ cconfig.getUnmappableInputAction() : CodingErrorAction.REPORT;
+ if (charset != null) {
+ chardecoder = charset.newDecoder();
+ chardecoder.onMalformedInput(malformedInputAction);
+ chardecoder.onUnmappableCharacter(unmappableInputAction);
+ charencoder = charset.newEncoder();
+ charencoder.onMalformedInput(malformedInputAction);
+ charencoder.onUnmappableCharacter(unmappableInputAction);
+ }
+ final String id = "http-outgoing-" + Long.toString(COUNTER.getAndIncrement());
+ return new LoggingManagedHttpClientConnection(
+ id,
+ log,
+ headerlog,
+ wirelog,
+ cconfig.getBufferSize(),
+ cconfig.getFragmentSizeHint(),
+ chardecoder,
+ charencoder,
+ cconfig.getMessageConstraints(),
+ null,
+ null,
+ requestWriterFactory,
+ responseParserFactory);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/PoolingClientConnectionManager.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/PoolingClientConnectionManager.java
new file mode 100644
index 000000000..f9685b81e
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/PoolingClientConnectionManager.java
@@ -0,0 +1,328 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.IOException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionOperator;
+import ch.boye.httpclientandroidlib.conn.ClientConnectionRequest;
+import ch.boye.httpclientandroidlib.conn.ConnectionPoolTimeoutException;
+import ch.boye.httpclientandroidlib.conn.DnsResolver;
+import ch.boye.httpclientandroidlib.conn.ManagedClientConnection;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.conn.scheme.SchemeRegistry;
+import ch.boye.httpclientandroidlib.pool.ConnPoolControl;
+import ch.boye.httpclientandroidlib.pool.PoolStats;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.Asserts;
+
+/**
+ * Manages a pool of {@link ch.boye.httpclientandroidlib.conn.OperatedClientConnection}
+ * and is able to service connection requests from multiple execution threads.
+ * Connections are pooled on a per route basis. A request for a route which
+ * already the manager has persistent connections for available in the pool
+ * will be services by leasing a connection from the pool rather than
+ * creating a brand new connection.
+ *
+ * PoolingConnectionManager maintains a maximum limit of connection on
+ * a per route basis and in total. Per default this implementation will
+ * create no more than than 2 concurrent connections per given route
+ * and no more 20 connections in total. For many real-world applications
+ * these limits may prove too constraining, especially if they use HTTP
+ * as a transport protocol for their services. Connection limits, however,
+ * can be adjusted using HTTP parameters.
+ *
+ * @since 4.2
+ *
+ * @deprecated (4.3) use {@link PoolingHttpClientConnectionManager}.
+ */
+@Deprecated
+@ThreadSafe
+public class PoolingClientConnectionManager implements ClientConnectionManager, ConnPoolControl {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ private final SchemeRegistry schemeRegistry;
+
+ private final HttpConnPool pool;
+
+ private final ClientConnectionOperator operator;
+
+ /** the custom-configured DNS lookup mechanism. */
+ private final DnsResolver dnsResolver;
+
+ public PoolingClientConnectionManager(final SchemeRegistry schreg) {
+ this(schreg, -1, TimeUnit.MILLISECONDS);
+ }
+
+ public PoolingClientConnectionManager(final SchemeRegistry schreg,final DnsResolver dnsResolver) {
+ this(schreg, -1, TimeUnit.MILLISECONDS,dnsResolver);
+ }
+
+ public PoolingClientConnectionManager() {
+ this(SchemeRegistryFactory.createDefault());
+ }
+
+ public PoolingClientConnectionManager(
+ final SchemeRegistry schemeRegistry,
+ final long timeToLive, final TimeUnit tunit) {
+ this(schemeRegistry, timeToLive, tunit, new SystemDefaultDnsResolver());
+ }
+
+ public PoolingClientConnectionManager(final SchemeRegistry schemeRegistry,
+ final long timeToLive, final TimeUnit tunit,
+ final DnsResolver dnsResolver) {
+ super();
+ Args.notNull(schemeRegistry, "Scheme registry");
+ Args.notNull(dnsResolver, "DNS resolver");
+ this.schemeRegistry = schemeRegistry;
+ this.dnsResolver = dnsResolver;
+ this.operator = createConnectionOperator(schemeRegistry);
+ this.pool = new HttpConnPool(this.log, this.operator, 2, 20, timeToLive, tunit);
+ }
+
+ @Override
+ protected void finalize() throws Throwable {
+ try {
+ shutdown();
+ } finally {
+ super.finalize();
+ }
+ }
+
+ /**
+ * Hook for creating the connection operator.
+ * It is called by the constructor.
+ * Derived classes can override this method to change the
+ * instantiation of the operator.
+ * The default implementation here instantiates
+ * {@link DefaultClientConnectionOperator DefaultClientConnectionOperator}.
+ *
+ * @param schreg the scheme registry.
+ *
+ * @return the connection operator to use
+ */
+ protected ClientConnectionOperator createConnectionOperator(final SchemeRegistry schreg) {
+ return new DefaultClientConnectionOperator(schreg, this.dnsResolver);
+ }
+
+ public SchemeRegistry getSchemeRegistry() {
+ return this.schemeRegistry;
+ }
+
+ private String format(final HttpRoute route, final Object state) {
+ final StringBuilder buf = new StringBuilder();
+ buf.append("[route: ").append(route).append("]");
+ if (state != null) {
+ buf.append("[state: ").append(state).append("]");
+ }
+ return buf.toString();
+ }
+
+ private String formatStats(final HttpRoute route) {
+ final StringBuilder buf = new StringBuilder();
+ final PoolStats totals = this.pool.getTotalStats();
+ final PoolStats stats = this.pool.getStats(route);
+ buf.append("[total kept alive: ").append(totals.getAvailable()).append("; ");
+ buf.append("route allocated: ").append(stats.getLeased() + stats.getAvailable());
+ buf.append(" of ").append(stats.getMax()).append("; ");
+ buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable());
+ buf.append(" of ").append(totals.getMax()).append("]");
+ return buf.toString();
+ }
+
+ private String format(final HttpPoolEntry entry) {
+ final StringBuilder buf = new StringBuilder();
+ buf.append("[id: ").append(entry.getId()).append("]");
+ buf.append("[route: ").append(entry.getRoute()).append("]");
+ final Object state = entry.getState();
+ if (state != null) {
+ buf.append("[state: ").append(state).append("]");
+ }
+ return buf.toString();
+ }
+
+ public ClientConnectionRequest requestConnection(
+ final HttpRoute route,
+ final Object state) {
+ Args.notNull(route, "HTTP route");
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Connection request: " + format(route, state) + formatStats(route));
+ }
+ final Future future = this.pool.lease(route, state);
+
+ return new ClientConnectionRequest() {
+
+ public void abortRequest() {
+ future.cancel(true);
+ }
+
+ public ManagedClientConnection getConnection(
+ final long timeout,
+ final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException {
+ return leaseConnection(future, timeout, tunit);
+ }
+
+ };
+
+ }
+
+ ManagedClientConnection leaseConnection(
+ final Future future,
+ final long timeout,
+ final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException {
+ final HttpPoolEntry entry;
+ try {
+ entry = future.get(timeout, tunit);
+ if (entry == null || future.isCancelled()) {
+ throw new InterruptedException();
+ }
+ Asserts.check(entry.getConnection() != null, "Pool entry with no connection");
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Connection leased: " + format(entry) + formatStats(entry.getRoute()));
+ }
+ return new ManagedClientConnectionImpl(this, this.operator, entry);
+ } catch (final ExecutionException ex) {
+ Throwable cause = ex.getCause();
+ if (cause == null) {
+ cause = ex;
+ }
+ this.log.error("Unexpected exception leasing connection from pool", cause);
+ // Should never happen
+ throw new InterruptedException();
+ } catch (final TimeoutException ex) {
+ throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool");
+ }
+ }
+
+ public void releaseConnection(
+ final ManagedClientConnection conn, final long keepalive, final TimeUnit tunit) {
+
+ Args.check(conn instanceof ManagedClientConnectionImpl, "Connection class mismatch, " +
+ "connection not obtained from this manager");
+ final ManagedClientConnectionImpl managedConn = (ManagedClientConnectionImpl) conn;
+ Asserts.check(managedConn.getManager() == this, "Connection not obtained from this manager");
+ synchronized (managedConn) {
+ final HttpPoolEntry entry = managedConn.detach();
+ if (entry == null) {
+ return;
+ }
+ try {
+ if (managedConn.isOpen() && !managedConn.isMarkedReusable()) {
+ try {
+ managedConn.shutdown();
+ } catch (final IOException iox) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("I/O exception shutting down released connection", iox);
+ }
+ }
+ }
+ // Only reusable connections can be kept alive
+ if (managedConn.isMarkedReusable()) {
+ entry.updateExpiry(keepalive, tunit != null ? tunit : TimeUnit.MILLISECONDS);
+ if (this.log.isDebugEnabled()) {
+ final String s;
+ if (keepalive > 0) {
+ s = "for " + keepalive + " " + tunit;
+ } else {
+ s = "indefinitely";
+ }
+ this.log.debug("Connection " + format(entry) + " can be kept alive " + s);
+ }
+ }
+ } finally {
+ this.pool.release(entry, managedConn.isMarkedReusable());
+ }
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Connection released: " + format(entry) + formatStats(entry.getRoute()));
+ }
+ }
+ }
+
+ public void shutdown() {
+ this.log.debug("Connection manager is shutting down");
+ try {
+ this.pool.shutdown();
+ } catch (final IOException ex) {
+ this.log.debug("I/O exception shutting down connection manager", ex);
+ }
+ this.log.debug("Connection manager shut down");
+ }
+
+ public void closeIdleConnections(final long idleTimeout, final TimeUnit tunit) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Closing connections idle longer than " + idleTimeout + " " + tunit);
+ }
+ this.pool.closeIdle(idleTimeout, tunit);
+ }
+
+ public void closeExpiredConnections() {
+ this.log.debug("Closing expired connections");
+ this.pool.closeExpired();
+ }
+
+ public int getMaxTotal() {
+ return this.pool.getMaxTotal();
+ }
+
+ public void setMaxTotal(final int max) {
+ this.pool.setMaxTotal(max);
+ }
+
+ public int getDefaultMaxPerRoute() {
+ return this.pool.getDefaultMaxPerRoute();
+ }
+
+ public void setDefaultMaxPerRoute(final int max) {
+ this.pool.setDefaultMaxPerRoute(max);
+ }
+
+ public int getMaxPerRoute(final HttpRoute route) {
+ return this.pool.getMaxPerRoute(route);
+ }
+
+ public void setMaxPerRoute(final HttpRoute route, final int max) {
+ this.pool.setMaxPerRoute(route, max);
+ }
+
+ public PoolStats getTotalStats() {
+ return this.pool.getTotalStats();
+ }
+
+ public PoolStats getStats(final HttpRoute route) {
+ return this.pool.getStats(route);
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/PoolingHttpClientConnectionManager.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/PoolingHttpClientConnectionManager.java
new file mode 100644
index 000000000..a2606b4e6
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/PoolingHttpClientConnectionManager.java
@@ -0,0 +1,516 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package ch.boye.httpclientandroidlib.impl.conn;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import ch.boye.httpclientandroidlib.androidextra.HttpClientAndroidLog;
+/* LogFactory removed by HttpClient for Android script. */
+import ch.boye.httpclientandroidlib.HttpClientConnection;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.annotation.ThreadSafe;
+import ch.boye.httpclientandroidlib.config.ConnectionConfig;
+import ch.boye.httpclientandroidlib.config.Lookup;
+import ch.boye.httpclientandroidlib.config.Registry;
+import ch.boye.httpclientandroidlib.config.RegistryBuilder;
+import ch.boye.httpclientandroidlib.config.SocketConfig;
+import ch.boye.httpclientandroidlib.conn.ConnectionPoolTimeoutException;
+import ch.boye.httpclientandroidlib.conn.ConnectionRequest;
+import ch.boye.httpclientandroidlib.conn.DnsResolver;
+import ch.boye.httpclientandroidlib.conn.HttpClientConnectionManager;
+import ch.boye.httpclientandroidlib.conn.HttpConnectionFactory;
+import ch.boye.httpclientandroidlib.conn.SchemePortResolver;
+import ch.boye.httpclientandroidlib.conn.ManagedHttpClientConnection;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.conn.socket.ConnectionSocketFactory;
+import ch.boye.httpclientandroidlib.conn.socket.PlainConnectionSocketFactory;
+import ch.boye.httpclientandroidlib.conn.ssl.SSLConnectionSocketFactory;
+import ch.boye.httpclientandroidlib.pool.ConnFactory;
+import ch.boye.httpclientandroidlib.pool.ConnPoolControl;
+import ch.boye.httpclientandroidlib.pool.PoolStats;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.Asserts;
+
+/**
+ * ClientConnectionPoolManager maintains a pool of
+ * {@link HttpClientConnection}s and is able to service connection requests
+ * from multiple execution threads. Connections are pooled on a per route
+ * basis. A request for a route which already the manager has persistent
+ * connections for available in the pool will be services by leasing
+ * a connection from the pool rather than creating a brand new connection.
+ *
+ * ClientConnectionPoolManager maintains a maximum limit of connection
+ * on a per route basis and in total. Per default this implementation will
+ * create no more than than 2 concurrent connections per given route
+ * and no more 20 connections in total. For many real-world applications
+ * these limits may prove too constraining, especially if they use HTTP
+ * as a transport protocol for their services. Connection limits, however,
+ * can be adjusted using {@link ConnPoolControl} methods.
+ *
+ * @since 4.3
+ */
+@ThreadSafe
+public class PoolingHttpClientConnectionManager
+ implements HttpClientConnectionManager, ConnPoolControl, Closeable {
+
+ public HttpClientAndroidLog log = new HttpClientAndroidLog(getClass());
+
+ private final ConfigData configData;
+ private final CPool pool;
+ private final HttpClientConnectionOperator connectionOperator;
+ private final AtomicBoolean isShutDown;
+
+ private static Registry getDefaultRegistry() {
+ return RegistryBuilder.create()
+ .register("http", PlainConnectionSocketFactory.getSocketFactory())
+ .register("https", SSLConnectionSocketFactory.getSocketFactory())
+ .build();
+ }
+
+ public PoolingHttpClientConnectionManager() {
+ this(getDefaultRegistry());
+ }
+
+ public PoolingHttpClientConnectionManager(final long timeToLive, final TimeUnit tunit) {
+ this(getDefaultRegistry(), null, null ,null, timeToLive, tunit);
+ }
+
+ public PoolingHttpClientConnectionManager(
+ final Registry socketFactoryRegistry) {
+ this(socketFactoryRegistry, null, null);
+ }
+
+ public PoolingHttpClientConnectionManager(
+ final Registry socketFactoryRegistry,
+ final DnsResolver dnsResolver) {
+ this(socketFactoryRegistry, null, dnsResolver);
+ }
+
+ public PoolingHttpClientConnectionManager(
+ final Registry socketFactoryRegistry,
+ final HttpConnectionFactory connFactory) {
+ this(socketFactoryRegistry, connFactory, null);
+ }
+
+ public PoolingHttpClientConnectionManager(
+ final HttpConnectionFactory connFactory) {
+ this(getDefaultRegistry(), connFactory, null);
+ }
+
+ public PoolingHttpClientConnectionManager(
+ final Registry socketFactoryRegistry,
+ final HttpConnectionFactory connFactory,
+ final DnsResolver dnsResolver) {
+ this(socketFactoryRegistry, connFactory, null, dnsResolver, -1, TimeUnit.MILLISECONDS);
+ }
+
+ public PoolingHttpClientConnectionManager(
+ final Registry socketFactoryRegistry,
+ final HttpConnectionFactory connFactory,
+ final SchemePortResolver schemePortResolver,
+ final DnsResolver dnsResolver,
+ final long timeToLive, final TimeUnit tunit) {
+ super();
+ this.configData = new ConfigData();
+ this.pool = new CPool(
+ new InternalConnectionFactory(this.configData, connFactory), 2, 20, timeToLive, tunit);
+ this.connectionOperator = new HttpClientConnectionOperator(
+ socketFactoryRegistry, schemePortResolver, dnsResolver);
+ this.isShutDown = new AtomicBoolean(false);
+ }
+
+ PoolingHttpClientConnectionManager(
+ final CPool pool,
+ final Lookup socketFactoryRegistry,
+ final SchemePortResolver schemePortResolver,
+ final DnsResolver dnsResolver) {
+ super();
+ this.configData = new ConfigData();
+ this.pool = pool;
+ this.connectionOperator = new HttpClientConnectionOperator(
+ socketFactoryRegistry, schemePortResolver, dnsResolver);
+ this.isShutDown = new AtomicBoolean(false);
+ }
+
+ @Override
+ protected void finalize() throws Throwable {
+ try {
+ shutdown();
+ } finally {
+ super.finalize();
+ }
+ }
+
+ public void close() {
+ shutdown();
+ }
+
+ private String format(final HttpRoute route, final Object state) {
+ final StringBuilder buf = new StringBuilder();
+ buf.append("[route: ").append(route).append("]");
+ if (state != null) {
+ buf.append("[state: ").append(state).append("]");
+ }
+ return buf.toString();
+ }
+
+ private String formatStats(final HttpRoute route) {
+ final StringBuilder buf = new StringBuilder();
+ final PoolStats totals = this.pool.getTotalStats();
+ final PoolStats stats = this.pool.getStats(route);
+ buf.append("[total kept alive: ").append(totals.getAvailable()).append("; ");
+ buf.append("route allocated: ").append(stats.getLeased() + stats.getAvailable());
+ buf.append(" of ").append(stats.getMax()).append("; ");
+ buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable());
+ buf.append(" of ").append(totals.getMax()).append("]");
+ return buf.toString();
+ }
+
+ private String format(final CPoolEntry entry) {
+ final StringBuilder buf = new StringBuilder();
+ buf.append("[id: ").append(entry.getId()).append("]");
+ buf.append("[route: ").append(entry.getRoute()).append("]");
+ final Object state = entry.getState();
+ if (state != null) {
+ buf.append("[state: ").append(state).append("]");
+ }
+ return buf.toString();
+ }
+
+ public ConnectionRequest requestConnection(
+ final HttpRoute route,
+ final Object state) {
+ Args.notNull(route, "HTTP route");
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Connection request: " + format(route, state) + formatStats(route));
+ }
+ final Future future = this.pool.lease(route, state, null);
+ return new ConnectionRequest() {
+
+ public boolean cancel() {
+ return future.cancel(true);
+ }
+
+ public HttpClientConnection get(
+ final long timeout,
+ final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
+ return leaseConnection(future, timeout, tunit);
+ }
+
+ };
+
+ }
+
+ protected HttpClientConnection leaseConnection(
+ final Future future,
+ final long timeout,
+ final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
+ final CPoolEntry entry;
+ try {
+ entry = future.get(timeout, tunit);
+ if (entry == null || future.isCancelled()) {
+ throw new InterruptedException();
+ }
+ Asserts.check(entry.getConnection() != null, "Pool entry with no connection");
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Connection leased: " + format(entry) + formatStats(entry.getRoute()));
+ }
+ return CPoolProxy.newProxy(entry);
+ } catch (final TimeoutException ex) {
+ throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool");
+ }
+ }
+
+ public void releaseConnection(
+ final HttpClientConnection managedConn,
+ final Object state,
+ final long keepalive, final TimeUnit tunit) {
+ Args.notNull(managedConn, "Managed connection");
+ synchronized (managedConn) {
+ final CPoolEntry entry = CPoolProxy.detach(managedConn);
+ if (entry == null) {
+ return;
+ }
+ final ManagedHttpClientConnection conn = entry.getConnection();
+ try {
+ if (conn.isOpen()) {
+ entry.setState(state);
+ entry.updateExpiry(keepalive, tunit != null ? tunit : TimeUnit.MILLISECONDS);
+ if (this.log.isDebugEnabled()) {
+ final String s;
+ if (keepalive > 0) {
+ s = "for " + (double) keepalive / 1000 + " seconds";
+ } else {
+ s = "indefinitely";
+ }
+ this.log.debug("Connection " + format(entry) + " can be kept alive " + s);
+ }
+ }
+ } finally {
+ this.pool.release(entry, conn.isOpen() && entry.isRouteComplete());
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Connection released: " + format(entry) + formatStats(entry.getRoute()));
+ }
+ }
+ }
+ }
+
+ public void connect(
+ final HttpClientConnection managedConn,
+ final HttpRoute route,
+ final int connectTimeout,
+ final HttpContext context) throws IOException {
+ Args.notNull(managedConn, "Managed Connection");
+ Args.notNull(route, "HTTP route");
+ final ManagedHttpClientConnection conn;
+ synchronized (managedConn) {
+ final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn);
+ conn = entry.getConnection();
+ }
+ final HttpHost host;
+ if (route.getProxyHost() != null) {
+ host = route.getProxyHost();
+ } else {
+ host = route.getTargetHost();
+ }
+ final InetSocketAddress localAddress = route.getLocalSocketAddress();
+ SocketConfig socketConfig = this.configData.getSocketConfig(host);
+ if (socketConfig == null) {
+ socketConfig = this.configData.getDefaultSocketConfig();
+ }
+ if (socketConfig == null) {
+ socketConfig = SocketConfig.DEFAULT;
+ }
+ this.connectionOperator.connect(
+ conn, host, localAddress, connectTimeout, socketConfig, context);
+ }
+
+ public void upgrade(
+ final HttpClientConnection managedConn,
+ final HttpRoute route,
+ final HttpContext context) throws IOException {
+ Args.notNull(managedConn, "Managed Connection");
+ Args.notNull(route, "HTTP route");
+ final ManagedHttpClientConnection conn;
+ synchronized (managedConn) {
+ final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn);
+ conn = entry.getConnection();
+ }
+ this.connectionOperator.upgrade(conn, route.getTargetHost(), context);
+ }
+
+ public void routeComplete(
+ final HttpClientConnection managedConn,
+ final HttpRoute route,
+ final HttpContext context) throws IOException {
+ Args.notNull(managedConn, "Managed Connection");
+ Args.notNull(route, "HTTP route");
+ synchronized (managedConn) {
+ final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn);
+ entry.markRouteComplete();
+ }
+ }
+
+ public void shutdown() {
+ if (this.isShutDown.compareAndSet(false, true)) {
+ this.log.debug("Connection manager is shutting down");
+ try {
+ this.pool.shutdown();
+ } catch (final IOException ex) {
+ this.log.debug("I/O exception shutting down connection manager", ex);
+ }
+ this.log.debug("Connection manager shut down");
+ }
+ }
+
+ public void closeIdleConnections(final long idleTimeout, final TimeUnit tunit) {
+ if (this.log.isDebugEnabled()) {
+ this.log.debug("Closing connections idle longer than " + idleTimeout + " " + tunit);
+ }
+ this.pool.closeIdle(idleTimeout, tunit);
+ }
+
+ public void closeExpiredConnections() {
+ this.log.debug("Closing expired connections");
+ this.pool.closeExpired();
+ }
+
+ public int getMaxTotal() {
+ return this.pool.getMaxTotal();
+ }
+
+ public void setMaxTotal(final int max) {
+ this.pool.setMaxTotal(max);
+ }
+
+ public int getDefaultMaxPerRoute() {
+ return this.pool.getDefaultMaxPerRoute();
+ }
+
+ public void setDefaultMaxPerRoute(final int max) {
+ this.pool.setDefaultMaxPerRoute(max);
+ }
+
+ public int getMaxPerRoute(final HttpRoute route) {
+ return this.pool.getMaxPerRoute(route);
+ }
+
+ public void setMaxPerRoute(final HttpRoute route, final int max) {
+ this.pool.setMaxPerRoute(route, max);
+ }
+
+ public PoolStats getTotalStats() {
+ return this.pool.getTotalStats();
+ }
+
+ public PoolStats getStats(final HttpRoute route) {
+ return this.pool.getStats(route);
+ }
+
+ public SocketConfig getDefaultSocketConfig() {
+ return this.configData.getDefaultSocketConfig();
+ }
+
+ public void setDefaultSocketConfig(final SocketConfig defaultSocketConfig) {
+ this.configData.setDefaultSocketConfig(defaultSocketConfig);
+ }
+
+ public ConnectionConfig getDefaultConnectionConfig() {
+ return this.configData.getDefaultConnectionConfig();
+ }
+
+ public void setDefaultConnectionConfig(final ConnectionConfig defaultConnectionConfig) {
+ this.configData.setDefaultConnectionConfig(defaultConnectionConfig);
+ }
+
+ public SocketConfig getSocketConfig(final HttpHost host) {
+ return this.configData.getSocketConfig(host);
+ }
+
+ public void setSocketConfig(final HttpHost host, final SocketConfig socketConfig) {
+ this.configData.setSocketConfig(host, socketConfig);
+ }
+
+ public ConnectionConfig getConnectionConfig(final HttpHost host) {
+ return this.configData.getConnectionConfig(host);
+ }
+
+ public void setConnectionConfig(final HttpHost host, final ConnectionConfig connectionConfig) {
+ this.configData.setConnectionConfig(host, connectionConfig);
+ }
+
+ static class ConfigData {
+
+ private final Map socketConfigMap;
+ private final Map connectionConfigMap;
+ private volatile SocketConfig defaultSocketConfig;
+ private volatile ConnectionConfig defaultConnectionConfig;
+
+ ConfigData() {
+ super();
+ this.socketConfigMap = new ConcurrentHashMap();
+ this.connectionConfigMap = new ConcurrentHashMap();
+ }
+
+ public SocketConfig getDefaultSocketConfig() {
+ return this.defaultSocketConfig;
+ }
+
+ public void setDefaultSocketConfig(final SocketConfig defaultSocketConfig) {
+ this.defaultSocketConfig = defaultSocketConfig;
+ }
+
+ public ConnectionConfig getDefaultConnectionConfig() {
+ return this.defaultConnectionConfig;
+ }
+
+ public void setDefaultConnectionConfig(final ConnectionConfig defaultConnectionConfig) {
+ this.defaultConnectionConfig = defaultConnectionConfig;
+ }
+
+ public SocketConfig getSocketConfig(final HttpHost host) {
+ return this.socketConfigMap.get(host);
+ }
+
+ public void setSocketConfig(final HttpHost host, final SocketConfig socketConfig) {
+ this.socketConfigMap.put(host, socketConfig);
+ }
+
+ public ConnectionConfig getConnectionConfig(final HttpHost host) {
+ return this.connectionConfigMap.get(host);
+ }
+
+ public void setConnectionConfig(final HttpHost host, final ConnectionConfig connectionConfig) {
+ this.connectionConfigMap.put(host, connectionConfig);
+ }
+
+ }
+
+ static class InternalConnectionFactory implements ConnFactory {
+
+ private final ConfigData configData;
+ private final HttpConnectionFactory connFactory;
+
+ InternalConnectionFactory(
+ final ConfigData configData,
+ final HttpConnectionFactory connFactory) {
+ super();
+ this.configData = configData != null ? configData : new ConfigData();
+ this.connFactory = connFactory != null ? connFactory :
+ ManagedHttpClientConnectionFactory.INSTANCE;
+ }
+
+ public ManagedHttpClientConnection create(final HttpRoute route) throws IOException {
+ ConnectionConfig config = null;
+ if (route.getProxyHost() != null) {
+ config = this.configData.getConnectionConfig(route.getProxyHost());
+ }
+ if (config == null) {
+ config = this.configData.getConnectionConfig(route.getTargetHost());
+ }
+ if (config == null) {
+ config = this.configData.getDefaultConnectionConfig();
+ }
+ if (config == null) {
+ config = ConnectionConfig.DEFAULT;
+ }
+ return this.connFactory.create(route, config);
+ }
+
+ }
+
+}
diff --git a/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/ProxySelectorRoutePlanner.java b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/ProxySelectorRoutePlanner.java
new file mode 100644
index 000000000..8c68e5e18
--- /dev/null
+++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/impl/conn/ProxySelectorRoutePlanner.java
@@ -0,0 +1,279 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package ch.boye.httpclientandroidlib.impl.conn;
+
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.List;
+
+import ch.boye.httpclientandroidlib.HttpException;
+import ch.boye.httpclientandroidlib.HttpHost;
+import ch.boye.httpclientandroidlib.HttpRequest;
+import ch.boye.httpclientandroidlib.annotation.NotThreadSafe;
+import ch.boye.httpclientandroidlib.conn.params.ConnRouteParams;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoute;
+import ch.boye.httpclientandroidlib.conn.routing.HttpRoutePlanner;
+import ch.boye.httpclientandroidlib.conn.scheme.Scheme;
+import ch.boye.httpclientandroidlib.conn.scheme.SchemeRegistry;
+import ch.boye.httpclientandroidlib.protocol.HttpContext;
+import ch.boye.httpclientandroidlib.util.Args;
+import ch.boye.httpclientandroidlib.util.Asserts;
+
+
+/**
+ * Default implementation of an {@link HttpRoutePlanner}.
+ * This implementation is based on {@link java.net.ProxySelector}.
+ * By default, it will pick up the proxy settings of the JVM, either
+ * from system properties or from the browser running the application.
+ * Additionally, it interprets some
+ * {@link ch.boye.httpclientandroidlib.conn.params.ConnRoutePNames parameters},
+ * though not the {@link
+ * ch.boye.httpclientandroidlib.conn.params.ConnRoutePNames#DEFAULT_PROXY DEFAULT_PROXY}.
+ *
+ * The following parameters can be used to customize the behavior of this
+ * class:
+ *