You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hc.apache.org by ol...@apache.org on 2017/09/02 15:28:13 UTC
[13/17] httpcomponents-client git commit: Moved classes and renamed
packages (no functional changes)
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/6d17126c/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ContentCompressionExec.java
----------------------------------------------------------------------
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ContentCompressionExec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ContentCompressionExec.java
new file mode 100644
index 0000000..75df9fc
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ContentCompressionExec.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
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.hc.client5.http.impl.classic;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+
+import org.apache.hc.client5.http.classic.ExecChain;
+import org.apache.hc.client5.http.classic.ExecChainHandler;
+import org.apache.hc.client5.http.config.RequestConfig;
+import org.apache.hc.client5.http.entity.DecompressingEntity;
+import org.apache.hc.client5.http.entity.DeflateInputStreamFactory;
+import org.apache.hc.client5.http.entity.GZIPInputStreamFactory;
+import org.apache.hc.client5.http.entity.InputStreamFactory;
+import org.apache.hc.client5.http.protocol.HttpClientContext;
+import org.apache.hc.core5.annotation.Contract;
+import org.apache.hc.core5.annotation.ThreadingBehavior;
+import org.apache.hc.core5.http.ClassicHttpRequest;
+import org.apache.hc.core5.http.ClassicHttpResponse;
+import org.apache.hc.core5.http.HeaderElement;
+import org.apache.hc.core5.http.HttpEntity;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.HttpHeaders;
+import org.apache.hc.core5.http.config.Lookup;
+import org.apache.hc.core5.http.config.RegistryBuilder;
+import org.apache.hc.core5.http.message.BasicHeaderValueParser;
+import org.apache.hc.core5.http.message.ParserCursor;
+import org.apache.hc.core5.util.Args;
+
+/**
+ * Request executor in the request execution chain that is responsible
+ * for automatic response content decompression.
+ * <p>
+ * Further responsibilities such as communication with the opposite
+ * endpoint is delegated to the next executor in the request execution
+ * chain.
+ * </p>
+ *
+ * @since 5.0
+ */
+@Contract(threading = ThreadingBehavior.IMMUTABLE)
+public final class ContentCompressionExec implements ExecChainHandler {
+
+ private final List<String> acceptEncoding;
+ private final Lookup<InputStreamFactory> decoderRegistry;
+ private final boolean ignoreUnknown;
+
+ public ContentCompressionExec(
+ final List<String> acceptEncoding,
+ final Lookup<InputStreamFactory> decoderRegistry,
+ final boolean ignoreUnknown) {
+ this.acceptEncoding = acceptEncoding != null ? acceptEncoding : Arrays.asList("gzip", "x-gzip", "deflate");
+ this.decoderRegistry = decoderRegistry != null ? decoderRegistry :
+ RegistryBuilder.<InputStreamFactory>create()
+ .register("gzip", GZIPInputStreamFactory.getInstance())
+ .register("x-gzip", GZIPInputStreamFactory.getInstance())
+ .register("deflate", DeflateInputStreamFactory.getInstance())
+ .build();
+ this.ignoreUnknown = ignoreUnknown;
+ }
+
+ public ContentCompressionExec(final boolean ignoreUnknown) {
+ this(null, null, ignoreUnknown);
+ }
+
+ /**
+ * Handles {@code gzip} and {@code deflate} compressed entities by using the following
+ * decoders:
+ * <ul>
+ * <li>gzip - see {@link java.util.zip.GZIPInputStream}</li>
+ * <li>deflate - see {@link org.apache.hc.client5.http.entity.DeflateInputStream}</li>
+ * </ul>
+ */
+ public ContentCompressionExec() {
+ this(null, null, true);
+ }
+
+
+ @Override
+ public ClassicHttpResponse execute(
+ final ClassicHttpRequest request,
+ final ExecChain.Scope scope,
+ final ExecChain chain) throws IOException, HttpException {
+ Args.notNull(request, "HTTP request");
+ Args.notNull(scope, "Scope");
+
+ final HttpClientContext clientContext = scope.clientContext;
+ final RequestConfig requestConfig = clientContext.getRequestConfig();
+
+ /* Signal support for Accept-Encoding transfer encodings. */
+ if (!request.containsHeader(HttpHeaders.ACCEPT_ENCODING) && requestConfig.isContentCompressionEnabled()) {
+ request.addHeader(HttpHeaders.ACCEPT_ENCODING, acceptEncoding);
+ }
+
+ final ClassicHttpResponse response = chain.proceed(request, scope);
+
+ 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 (requestConfig.isContentCompressionEnabled() && entity != null && entity.getContentLength() != 0) {
+ final String contentEncoding = entity.getContentEncoding();
+ if (contentEncoding != null) {
+ final ParserCursor cursor = new ParserCursor(0, contentEncoding.length());
+ final HeaderElement[] codecs = BasicHeaderValueParser.INSTANCE.parseElements(contentEncoding, cursor);
+ for (final HeaderElement codec : codecs) {
+ final String codecname = codec.getName().toLowerCase(Locale.ROOT);
+ final InputStreamFactory decoderFactory = decoderRegistry.lookup(codecname);
+ if (decoderFactory != null) {
+ response.setEntity(new DecompressingEntity(response.getEntity(), decoderFactory));
+ response.removeHeaders(HttpHeaders.CONTENT_LENGTH);
+ response.removeHeaders(HttpHeaders.CONTENT_ENCODING);
+ response.removeHeaders(HttpHeaders.CONTENT_MD5);
+ } else {
+ if (!"identity".equals(codecname) && !ignoreUnknown) {
+ throw new HttpException("Unsupported Content-Encoding: " + codec.getName());
+ }
+ }
+ }
+ }
+ }
+ return response;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/6d17126c/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/DefaultBackoffStrategy.java
----------------------------------------------------------------------
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/DefaultBackoffStrategy.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/DefaultBackoffStrategy.java
new file mode 100644
index 0000000..7f2ab14
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/DefaultBackoffStrategy.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
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.client5.http.impl.classic;
+
+import java.net.ConnectException;
+import java.net.SocketTimeoutException;
+
+import org.apache.hc.client5.http.classic.ConnectionBackoffStrategy;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.HttpStatus;
+
+/**
+ * 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 {
+
+ @Override
+ public boolean shouldBackoff(final Throwable t) {
+ return (t instanceof SocketTimeoutException
+ || t instanceof ConnectException);
+ }
+
+ @Override
+ public boolean shouldBackoff(final HttpResponse resp) {
+ return (resp.getCode() == HttpStatus.SC_SERVICE_UNAVAILABLE);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/6d17126c/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ExecChainElement.java
----------------------------------------------------------------------
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ExecChainElement.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ExecChainElement.java
new file mode 100644
index 0000000..ff13e9f
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ExecChainElement.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
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.hc.client5.http.impl.classic;
+
+import java.io.IOException;
+
+import org.apache.hc.client5.http.classic.ExecChain;
+import org.apache.hc.client5.http.classic.ExecChainHandler;
+import org.apache.hc.core5.http.ClassicHttpRequest;
+import org.apache.hc.core5.http.ClassicHttpResponse;
+import org.apache.hc.core5.http.HttpException;
+
+class ExecChainElement {
+
+ private final ExecChainHandler handler;
+ private final ExecChainElement next;
+
+ ExecChainElement(final ExecChainHandler handler, final ExecChainElement next) {
+ this.handler = handler;
+ this.next = next;
+ }
+
+ public ClassicHttpResponse execute(
+ final ClassicHttpRequest request,
+ final ExecChain.Scope scope) throws IOException, HttpException {
+ return handler.execute(request, scope, new ExecChain() {
+
+ @Override
+ public ClassicHttpResponse proceed(
+ final ClassicHttpRequest request,
+ final Scope scope) throws IOException, HttpException {
+ return next.execute(request, scope);
+ }
+
+ });
+ }
+
+ @Override
+ public String toString() {
+ return "{" +
+ "handler=" + handler.getClass() +
+ ", next=" + (next != null ? next.handler.getClass() : "null") +
+ '}';
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/6d17126c/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ExecRuntimeImpl.java
----------------------------------------------------------------------
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ExecRuntimeImpl.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ExecRuntimeImpl.java
new file mode 100644
index 0000000..b9a0666
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ExecRuntimeImpl.java
@@ -0,0 +1,258 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.hc.client5.http.impl.classic;
+
+import java.io.IOException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.hc.client5.http.CancellableAware;
+import org.apache.hc.client5.http.HttpRoute;
+import org.apache.hc.client5.http.classic.ExecRuntime;
+import org.apache.hc.client5.http.config.RequestConfig;
+import org.apache.hc.client5.http.io.ConnectionEndpoint;
+import org.apache.hc.client5.http.io.HttpClientConnectionManager;
+import org.apache.hc.client5.http.io.LeaseRequest;
+import org.apache.hc.client5.http.protocol.HttpClientContext;
+import org.apache.hc.core5.concurrent.Cancellable;
+import org.apache.hc.core5.http.ClassicHttpRequest;
+import org.apache.hc.core5.http.ClassicHttpResponse;
+import org.apache.hc.core5.http.ConnectionRequestTimeoutException;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.impl.io.HttpRequestExecutor;
+import org.apache.hc.core5.io.ShutdownType;
+import org.apache.hc.core5.util.Args;
+import org.apache.hc.core5.util.TimeValue;
+import org.apache.logging.log4j.Logger;
+
+class ExecRuntimeImpl implements ExecRuntime, Cancellable {
+
+ private final Logger log;
+
+ private final HttpClientConnectionManager manager;
+ private final HttpRequestExecutor requestExecutor;
+ private final CancellableAware cancellableAware;
+ private final AtomicReference<ConnectionEndpoint> endpointRef;
+
+ private volatile boolean reusable;
+ private volatile Object state;
+ private volatile TimeValue validDuration;
+
+ ExecRuntimeImpl(
+ final Logger log,
+ final HttpClientConnectionManager manager,
+ final HttpRequestExecutor requestExecutor,
+ final CancellableAware cancellableAware) {
+ super();
+ this.log = log;
+ this.manager = manager;
+ this.requestExecutor = requestExecutor;
+ this.cancellableAware = cancellableAware;
+ this.endpointRef = new AtomicReference<>(null);
+ this.validDuration = TimeValue.NEG_ONE_MILLISECONDS;
+ }
+
+ @Override
+ public boolean isExecutionAborted() {
+ return cancellableAware != null && cancellableAware.isCancelled();
+ }
+
+ @Override
+ public boolean isConnectionAcquired() {
+ return endpointRef.get() != null;
+ }
+
+ @Override
+ public void acquireConnection(final HttpRoute route, final Object object, final HttpClientContext context) throws IOException {
+ Args.notNull(route, "Route");
+ if (endpointRef.get() == null) {
+ final LeaseRequest connRequest = manager.lease(route, object);
+ state = object;
+ if (cancellableAware != null) {
+ if (cancellableAware.isCancelled()) {
+ connRequest.cancel();
+ throw new RequestFailedException("Request aborted");
+ }
+ cancellableAware.setCancellable(connRequest);
+ }
+ try {
+ final RequestConfig requestConfig = context.getRequestConfig();
+ final TimeValue timeout = requestConfig.getConnectionRequestTimeout();
+ final ConnectionEndpoint connectionEndpoint = connRequest.get(timeout.getDuration(), timeout.getTimeUnit());
+ endpointRef.set(connectionEndpoint);
+ reusable = connectionEndpoint.isConnected();
+ if (cancellableAware != null) {
+ cancellableAware.setCancellable(this);
+ }
+ } catch(final TimeoutException ex) {
+ throw new ConnectionRequestTimeoutException(ex.getMessage());
+ } catch(final InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ throw new RequestFailedException("Request aborted", interrupted);
+ } catch(final ExecutionException ex) {
+ Throwable cause = ex.getCause();
+ if (cause == null) {
+ cause = ex;
+ }
+ throw new RequestFailedException("Request execution failed", cause);
+ }
+ } else {
+ throw new IllegalStateException("Endpoint already acquired");
+ }
+ }
+
+ ConnectionEndpoint ensureValid() {
+ final ConnectionEndpoint endpoint = endpointRef.get();
+ if (endpoint == null) {
+ throw new IllegalStateException("Endpoint not acquired / already released");
+ }
+ return endpoint;
+ }
+
+ @Override
+ public boolean isConnected() {
+ final ConnectionEndpoint endpoint = endpointRef.get();
+ return endpoint != null && endpoint.isConnected();
+ }
+
+ private void connectEndpoint(final ConnectionEndpoint endpoint, final HttpClientContext context) throws IOException {
+ if (cancellableAware != null) {
+ if (cancellableAware.isCancelled()) {
+ throw new RequestFailedException("Request aborted");
+ }
+ }
+ final RequestConfig requestConfig = context.getRequestConfig();
+ final TimeValue connectTimeout = requestConfig.getConnectTimeout();
+ manager.connect(endpoint, connectTimeout, context);
+ final TimeValue socketTimeout = requestConfig.getSocketTimeout();
+ if (socketTimeout.getDuration() >= 0) {
+ endpoint.setSocketTimeout(socketTimeout.toMillisIntBound());
+ }
+ }
+
+ @Override
+ public void connect(final HttpClientContext context) throws IOException {
+ final ConnectionEndpoint endpoint = ensureValid();
+ if (!endpoint.isConnected()) {
+ connectEndpoint(endpoint, context);
+ }
+ }
+
+ @Override
+ public void disconnect() throws IOException {
+ final ConnectionEndpoint endpoint = endpointRef.get();
+ if (endpoint != null) {
+ endpoint.close();
+ log.debug("Disconnected");
+ }
+ }
+
+ @Override
+ public void upgradeTls(final HttpClientContext context) throws IOException {
+ final ConnectionEndpoint endpoint = ensureValid();
+ manager.upgrade(endpoint, context);
+ }
+
+ @Override
+ public ClassicHttpResponse execute(final ClassicHttpRequest request, final HttpClientContext context) throws IOException, HttpException {
+ final ConnectionEndpoint endpoint = ensureValid();
+ if (!endpoint.isConnected()) {
+ connectEndpoint(endpoint, context);
+ }
+ return endpoint.execute(request, requestExecutor, context);
+ }
+
+ @Override
+ public boolean isConnectionReusable() {
+ return reusable;
+ }
+
+ @Override
+ public void markConnectionReusable() {
+ reusable = true;
+ }
+
+ @Override
+ public void markConnectionNonReusable() {
+ reusable = false;
+ }
+
+ @Override
+ public void setConnectionState(final Object state) {
+ this.state = state;
+ }
+
+ @Override
+ public void setConnectionValidFor(final TimeValue duration) {
+ validDuration = duration;
+ }
+
+ @Override
+ public void releaseConnection() {
+ final ConnectionEndpoint endpoint = endpointRef.getAndSet(null);
+ if (endpoint != null) {
+ if (reusable) {
+ manager.release(endpoint, state, validDuration);
+ } else {
+ try {
+ endpoint.close();
+ log.debug("Connection discarded");
+ } catch (final IOException ex) {
+ if (log.isDebugEnabled()) {
+ log.debug(ex.getMessage(), ex);
+ }
+ } finally {
+ manager.release(endpoint, null, TimeValue.ZERO_MILLISECONDS);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void discardConnection() {
+ final ConnectionEndpoint endpoint = endpointRef.getAndSet(null);
+ if (endpoint != null) {
+ try {
+ endpoint.shutdown(ShutdownType.IMMEDIATE);
+ log.debug("Connection discarded");
+ } finally {
+ manager.release(endpoint, null, TimeValue.ZERO_MILLISECONDS);
+ }
+ }
+ }
+
+ @Override
+ public boolean cancel() {
+ final boolean alreadyReleased = endpointRef.get() == null;
+ log.debug("Cancelling request execution");
+ discardConnection();
+ return !alreadyReleased;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/6d17126c/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/FutureRequestExecutionMetrics.java
----------------------------------------------------------------------
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/FutureRequestExecutionMetrics.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/FutureRequestExecutionMetrics.java
new file mode 100644
index 0000000..4c88dac
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/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
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.client5.http.impl.classic;
+
+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();
+ }
+
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/6d17126c/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/FutureRequestExecutionService.java
----------------------------------------------------------------------
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/FutureRequestExecutionService.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/FutureRequestExecutionService.java
new file mode 100644
index 0000000..82b5f7b
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/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
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.client5.http.impl.classic;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.hc.client5.http.classic.HttpClient;
+import org.apache.hc.core5.annotation.Contract;
+import org.apache.hc.core5.annotation.ThreadingBehavior;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.ClassicHttpRequest;
+import org.apache.hc.core5.http.io.HttpClientResponseHandler;
+import org.apache.hc.core5.http.protocol.HttpContext;
+
+/**
+ * HttpAsyncClientWithFuture wraps calls to execute with a {@link HttpRequestFutureTask}
+ * and schedules them using the provided executor service. Scheduled calls may be cancelled.
+ */
+@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL)
+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 <T>
+ *
+ * @param request
+ * request to execute
+ * @param HttpClientResponseHandler
+ * handler that will process the response.
+ * @return HttpAsyncClientFutureTask for the scheduled request.
+ */
+ public <T> HttpRequestFutureTask<T> execute(
+ final ClassicHttpRequest request,
+ final HttpContext context,
+ final HttpClientResponseHandler<T> HttpClientResponseHandler) {
+ return execute(request, context, HttpClientResponseHandler, null);
+ }
+
+ /**
+ * Schedule a request for execution.
+ *
+ * @param <T>
+ *
+ * @param request
+ * request to execute
+ * @param context
+ * optional context; use null if not needed.
+ * @param HttpClientResponseHandler
+ * 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.
+ */
+ public <T> HttpRequestFutureTask<T> execute(
+ final ClassicHttpRequest request,
+ final HttpContext context,
+ final HttpClientResponseHandler<T> HttpClientResponseHandler,
+ final FutureCallback<T> callback) {
+ if(closed.get()) {
+ throw new IllegalStateException("Close has been called on this httpclient instance.");
+ }
+ metrics.getScheduledConnections().incrementAndGet();
+ final HttpRequestTaskCallable<T> callable = new HttpRequestTaskCallable<>(
+ httpclient, request, context, HttpClientResponseHandler, callback, metrics);
+ final HttpRequestFutureTask<T> httpRequestFutureTask = new HttpRequestFutureTask<>(
+ request, callable);
+ executorService.execute(httpRequestFutureTask);
+
+ return httpRequestFutureTask;
+ }
+
+ /**
+ * @return metrics gathered for this instance.
+ * @see FutureRequestExecutionMetrics
+ */
+ public FutureRequestExecutionMetrics metrics() {
+ return metrics;
+ }
+
+ @Override
+ public void close() throws IOException {
+ closed.set(true);
+ executorService.shutdownNow();
+ if (httpclient instanceof Closeable) {
+ ((Closeable) httpclient).close();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/6d17126c/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpClientBuilder.java
----------------------------------------------------------------------
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpClientBuilder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpClientBuilder.java
new file mode 100644
index 0000000..c5beb8b
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpClientBuilder.java
@@ -0,0 +1,1019 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.hc.client5.http.impl.classic;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.ProxySelector;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.hc.client5.http.AuthenticationStrategy;
+import org.apache.hc.client5.http.ConnectionKeepAliveStrategy;
+import org.apache.hc.client5.http.HttpRequestRetryHandler;
+import org.apache.hc.client5.http.SchemePortResolver;
+import org.apache.hc.client5.http.ServiceUnavailableRetryStrategy;
+import org.apache.hc.client5.http.SystemDefaultDnsResolver;
+import org.apache.hc.client5.http.UserTokenHandler;
+import org.apache.hc.client5.http.auth.AuthSchemeProvider;
+import org.apache.hc.client5.http.auth.CredentialsProvider;
+import org.apache.hc.client5.http.classic.BackoffManager;
+import org.apache.hc.client5.http.classic.ConnectionBackoffStrategy;
+import org.apache.hc.client5.http.classic.ExecChainHandler;
+import org.apache.hc.client5.http.config.AuthSchemes;
+import org.apache.hc.client5.http.config.RequestConfig;
+import org.apache.hc.client5.http.cookie.BasicCookieStore;
+import org.apache.hc.client5.http.cookie.CookieSpecProvider;
+import org.apache.hc.client5.http.cookie.CookieStore;
+import org.apache.hc.client5.http.entity.InputStreamFactory;
+import org.apache.hc.client5.http.impl.ChainElements;
+import org.apache.hc.client5.http.impl.CookieSpecRegistries;
+import org.apache.hc.client5.http.impl.DefaultAuthenticationStrategy;
+import org.apache.hc.client5.http.impl.DefaultConnectionKeepAliveStrategy;
+import org.apache.hc.client5.http.impl.DefaultHttpRequestRetryHandler;
+import org.apache.hc.client5.http.impl.DefaultRedirectStrategy;
+import org.apache.hc.client5.http.impl.DefaultSchemePortResolver;
+import org.apache.hc.client5.http.impl.DefaultUserTokenHandler;
+import org.apache.hc.client5.http.impl.IdleConnectionEvictor;
+import org.apache.hc.client5.http.impl.NoopUserTokenHandler;
+import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
+import org.apache.hc.client5.http.impl.auth.BasicSchemeFactory;
+import org.apache.hc.client5.http.impl.auth.CredSspSchemeFactory;
+import org.apache.hc.client5.http.impl.auth.DigestSchemeFactory;
+import org.apache.hc.client5.http.impl.auth.KerberosSchemeFactory;
+import org.apache.hc.client5.http.impl.auth.NTLMSchemeFactory;
+import org.apache.hc.client5.http.impl.auth.SPNegoSchemeFactory;
+import org.apache.hc.client5.http.impl.auth.SystemDefaultCredentialsProvider;
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
+import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
+import org.apache.hc.client5.http.impl.routing.DefaultRoutePlanner;
+import org.apache.hc.client5.http.impl.routing.SystemDefaultRoutePlanner;
+import org.apache.hc.client5.http.io.HttpClientConnectionManager;
+import org.apache.hc.client5.http.protocol.RedirectStrategy;
+import org.apache.hc.client5.http.protocol.RequestAddCookies;
+import org.apache.hc.client5.http.protocol.RequestAuthCache;
+import org.apache.hc.client5.http.protocol.RequestClientConnControl;
+import org.apache.hc.client5.http.protocol.RequestDefaultHeaders;
+import org.apache.hc.client5.http.protocol.RequestExpectContinue;
+import org.apache.hc.client5.http.protocol.ResponseProcessCookies;
+import org.apache.hc.client5.http.routing.HttpRoutePlanner;
+import org.apache.hc.core5.annotation.Internal;
+import org.apache.hc.core5.http.ConnectionReuseStrategy;
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.HttpRequestInterceptor;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.HttpResponseInterceptor;
+import org.apache.hc.core5.http.config.Lookup;
+import org.apache.hc.core5.http.config.NamedElementChain;
+import org.apache.hc.core5.http.config.Registry;
+import org.apache.hc.core5.http.config.RegistryBuilder;
+import org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy;
+import org.apache.hc.core5.http.impl.io.HttpRequestExecutor;
+import org.apache.hc.core5.http.protocol.DefaultHttpProcessor;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.http.protocol.HttpProcessor;
+import org.apache.hc.core5.http.protocol.HttpProcessorBuilder;
+import org.apache.hc.core5.http.protocol.RequestContent;
+import org.apache.hc.core5.http.protocol.RequestTargetHost;
+import org.apache.hc.core5.http.protocol.RequestUserAgent;
+import org.apache.hc.core5.pool.ConnPoolControl;
+import org.apache.hc.core5.util.Args;
+import org.apache.hc.core5.util.TimeValue;
+import org.apache.hc.core5.util.VersionInfo;
+
+/**
+ * Builder for {@link CloseableHttpClient} instances.
+ * <p>
+ * When a particular component is not explicitly set 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()}.
+ * </p>
+ * <ul>
+ * <li>http.proxyHost</li>
+ * <li>http.proxyPort</li>
+ * <li>http.nonProxyHosts</li>
+ * <li>http.keepAlive</li>
+ * <li>http.agent</li>
+ * </ul>
+ * <p>
+ * Please note that some settings used by this class can be mutually
+ * exclusive and may not apply when building {@link CloseableHttpClient}
+ * instances.
+ * </p>
+ *
+ * @since 4.3
+ */
+public class HttpClientBuilder {
+
+ private static class RequestInterceptorEntry {
+
+ enum Postion { FIRST, LAST }
+
+ final Postion postion;
+ final HttpRequestInterceptor interceptor;
+
+ private RequestInterceptorEntry(final Postion postion, final HttpRequestInterceptor interceptor) {
+ this.postion = postion;
+ this.interceptor = interceptor;
+ }
+ }
+
+ private static class ResponseInterceptorEntry {
+
+ enum Postion { FIRST, LAST }
+
+ final Postion postion;
+ final HttpResponseInterceptor interceptor;
+
+ private ResponseInterceptorEntry(final Postion postion, final HttpResponseInterceptor interceptor) {
+ this.postion = postion;
+ this.interceptor = interceptor;
+ }
+ }
+
+ private static class ExecInterceptorEntry {
+
+ enum Postion { BEFORE, AFTER, REPLACE, FIRST, LAST }
+
+ final Postion postion;
+ final String name;
+ final ExecChainHandler interceptor;
+ final String existing;
+
+ private ExecInterceptorEntry(
+ final Postion postion,
+ final String name,
+ final ExecChainHandler interceptor,
+ final String existing) {
+ this.postion = postion;
+ this.name = name;
+ this.interceptor = interceptor;
+ this.existing = existing;
+ }
+
+ }
+
+ private HttpRequestExecutor requestExec;
+ private HttpClientConnectionManager connManager;
+ private boolean connManagerShared;
+ private SchemePortResolver schemePortResolver;
+ private ConnectionReuseStrategy reuseStrategy;
+ private ConnectionKeepAliveStrategy keepAliveStrategy;
+ private AuthenticationStrategy targetAuthStrategy;
+ private AuthenticationStrategy proxyAuthStrategy;
+ private UserTokenHandler userTokenHandler;
+
+ private LinkedList<RequestInterceptorEntry> requestInterceptors;
+ private LinkedList<ResponseInterceptorEntry> responseInterceptors;
+ private LinkedList<ExecInterceptorEntry> execInterceptors;
+
+ private HttpRequestRetryHandler retryHandler;
+ private HttpRoutePlanner routePlanner;
+ private RedirectStrategy redirectStrategy;
+ private ConnectionBackoffStrategy connectionBackoffStrategy;
+ private BackoffManager backoffManager;
+ private ServiceUnavailableRetryStrategy serviceUnavailStrategy;
+ private Lookup<AuthSchemeProvider> authSchemeRegistry;
+ private Lookup<CookieSpecProvider> cookieSpecRegistry;
+ private LinkedHashMap<String, InputStreamFactory> contentDecoderMap;
+ private CookieStore cookieStore;
+ private CredentialsProvider credentialsProvider;
+ private String userAgent;
+ private HttpHost proxy;
+ private Collection<? extends Header> defaultHeaders;
+ private RequestConfig defaultRequestConfig;
+ private boolean evictExpiredConnections;
+ private boolean evictIdleConnections;
+ private TimeValue maxIdleTime;
+
+ private boolean systemProperties;
+ private boolean redirectHandlingDisabled;
+ private boolean automaticRetriesDisabled;
+ private boolean contentCompressionDisabled;
+ private boolean cookieManagementDisabled;
+ private boolean authCachingDisabled;
+ private boolean connectionStateDisabled;
+
+ private List<Closeable> closeables;
+
+ 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 HttpClientConnectionManager} instance.
+ */
+ public final HttpClientBuilder setConnectionManager(
+ final HttpClientConnectionManager connManager) {
+ this.connManager = connManager;
+ return this;
+ }
+
+ /**
+ * Defines the connection manager is to be shared by multiple
+ * client instances.
+ * <p>
+ * If the connection manager is shared its life-cycle is expected
+ * to be managed by the caller and it will not be shut down
+ * if the client is closed.
+ * </p>
+ *
+ * @param shared defines whether or not the connection manager can be shared
+ * by multiple clients.
+ *
+ * @since 4.4
+ */
+ public final HttpClientBuilder setConnectionManagerShared(
+ final boolean shared) {
+ this.connManagerShared = shared;
+ 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 target
+ * host authentication.
+ */
+ public final HttpClientBuilder setTargetAuthenticationStrategy(
+ final AuthenticationStrategy targetAuthStrategy) {
+ this.targetAuthStrategy = targetAuthStrategy;
+ return this;
+ }
+
+ /**
+ * Assigns {@link AuthenticationStrategy} instance for proxy
+ * authentication.
+ */
+ public final HttpClientBuilder setProxyAuthenticationStrategy(
+ final AuthenticationStrategy proxyAuthStrategy) {
+ this.proxyAuthStrategy = proxyAuthStrategy;
+ return this;
+ }
+
+ /**
+ * Assigns {@link UserTokenHandler} instance.
+ * <p>
+ * Please note this value can be overridden by the {@link #disableConnectionState()}
+ * method.
+ * </p>
+ */
+ 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 {@code User-Agent} value.
+ */
+ public final HttpClientBuilder setUserAgent(final String userAgent) {
+ this.userAgent = userAgent;
+ return this;
+ }
+
+ /**
+ * Assigns default request header values.
+ */
+ 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.
+ */
+ public final HttpClientBuilder addRequestInterceptorFirst(final HttpResponseInterceptor interceptor) {
+ Args.notNull(interceptor, "Interceptor");
+ if (responseInterceptors == null) {
+ responseInterceptors = new LinkedList<>();
+ }
+ responseInterceptors.add(new ResponseInterceptorEntry(ResponseInterceptorEntry.Postion.FIRST, interceptor));
+ return this;
+ }
+
+ /**
+ * Adds this protocol interceptor to the tail of the protocol processing list.
+ */
+ public final HttpClientBuilder addResponseInterceptorLast(final HttpResponseInterceptor interceptor) {
+ Args.notNull(interceptor, "Interceptor");
+ if (responseInterceptors == null) {
+ responseInterceptors = new LinkedList<>();
+ }
+ responseInterceptors.add(new ResponseInterceptorEntry(ResponseInterceptorEntry.Postion.LAST, interceptor));
+ return this;
+ }
+
+ /**
+ * Adds this protocol interceptor to the head of the protocol processing list.
+ */
+ public final HttpClientBuilder addRequestInterceptorFirst(final HttpRequestInterceptor interceptor) {
+ Args.notNull(interceptor, "Interceptor");
+ if (requestInterceptors == null) {
+ requestInterceptors = new LinkedList<>();
+ }
+ requestInterceptors.add(new RequestInterceptorEntry(RequestInterceptorEntry.Postion.FIRST, interceptor));
+ return this;
+ }
+
+ /**
+ * Adds this protocol interceptor to the tail of the protocol processing list.
+ */
+ public final HttpClientBuilder addResponseInterceptorLast(final HttpRequestInterceptor interceptor) {
+ Args.notNull(interceptor, "Interceptor");
+ if (requestInterceptors == null) {
+ requestInterceptors = new LinkedList<>();
+ }
+ requestInterceptors.add(new RequestInterceptorEntry(RequestInterceptorEntry.Postion.LAST, interceptor));
+ return this;
+ }
+
+ /**
+ * Adds this execution interceptor before an existing interceptor.
+ */
+ public final HttpClientBuilder addExecInterceptorBefore(final String existing, final String name, final ExecChainHandler interceptor) {
+ Args.notBlank(existing, "Existing");
+ Args.notBlank(name, "Name");
+ Args.notNull(interceptor, "Interceptor");
+ if (execInterceptors == null) {
+ execInterceptors = new LinkedList<>();
+ }
+ execInterceptors.add(new ExecInterceptorEntry(ExecInterceptorEntry.Postion.BEFORE, name, interceptor, existing));
+ return this;
+ }
+
+ /**
+ * Adds this execution interceptor after interceptor with the given name.
+ */
+ public final HttpClientBuilder addExecInterceptorAfter(final String existing, final String name, final ExecChainHandler interceptor) {
+ Args.notBlank(existing, "Existing");
+ Args.notBlank(name, "Name");
+ Args.notNull(interceptor, "Interceptor");
+ if (execInterceptors == null) {
+ execInterceptors = new LinkedList<>();
+ }
+ execInterceptors.add(new ExecInterceptorEntry(ExecInterceptorEntry.Postion.AFTER, name, interceptor, existing));
+ return this;
+ }
+
+ /**
+ * Replace an existing interceptor with the given name with new interceptor.
+ */
+ public final HttpClientBuilder replaceExecInterceptor(final String existing, final ExecChainHandler interceptor) {
+ Args.notBlank(existing, "Existing");
+ Args.notNull(interceptor, "Interceptor");
+ if (execInterceptors == null) {
+ execInterceptors = new LinkedList<>();
+ }
+ execInterceptors.add(new ExecInterceptorEntry(ExecInterceptorEntry.Postion.REPLACE, existing, interceptor, existing));
+ return this;
+ }
+
+ /**
+ * Add an interceptor to the head of the processing list.
+ */
+ public final HttpClientBuilder addExecInterceptorFirst(final String name, final ExecChainHandler interceptor) {
+ Args.notNull(name, "Name");
+ Args.notNull(interceptor, "Interceptor");
+ execInterceptors.add(new ExecInterceptorEntry(ExecInterceptorEntry.Postion.FIRST, name, interceptor, null));
+ return this;
+ }
+
+ /**
+ * Add an interceptor to the tail of the processing list.
+ */
+ public final HttpClientBuilder addExecInterceptorLast(final String name, final ExecChainHandler interceptor) {
+ Args.notNull(name, "Name");
+ Args.notNull(interceptor, "Interceptor");
+ execInterceptors.add(new ExecInterceptorEntry(ExecInterceptorEntry.Postion.LAST, name, interceptor, null));
+ return this;
+ }
+
+ /**
+ * Disables state (cookie) management.
+ */
+ public final HttpClientBuilder disableCookieManagement() {
+ this.cookieManagementDisabled = true;
+ return this;
+ }
+
+ /**
+ * Disables automatic content decompression.
+ */
+ public final HttpClientBuilder disableContentCompression() {
+ contentCompressionDisabled = true;
+ return this;
+ }
+
+ /**
+ * Disables authentication scheme caching.
+ */
+ public final HttpClientBuilder disableAuthCaching() {
+ this.authCachingDisabled = true;
+ return this;
+ }
+
+ /**
+ * Assigns {@link HttpRequestRetryHandler} instance.
+ * <p>
+ * 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.
+ * <p>
+ * Please note this value can be overridden by the {@link #setRoutePlanner(
+ * org.apache.hc.client5.http.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.
+ * <p>
+ * Please note this value can be overridden by the {@link #disableRedirectHandling()}
+ * method.
+ * </p>
+` */
+ 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 org.apache.hc.client5.http.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<AuthSchemeProvider> authSchemeRegistry) {
+ this.authSchemeRegistry = authSchemeRegistry;
+ return this;
+ }
+
+ /**
+ * Assigns default {@link org.apache.hc.client5.http.cookie.CookieSpec} registry which will
+ * be used for request execution if not explicitly set in the client execution
+ * context.
+ *
+ * @see CookieSpecRegistries
+ *
+ */
+ public final HttpClientBuilder setDefaultCookieSpecRegistry(
+ final Lookup<CookieSpecProvider> cookieSpecRegistry) {
+ this.cookieSpecRegistry = cookieSpecRegistry;
+ return this;
+ }
+
+
+ /**
+ * Assigns a map of {@link org.apache.hc.client5.http.entity.InputStreamFactory}s
+ * to be used for automatic content decompression.
+ */
+ public final HttpClientBuilder setContentDecoderRegistry(
+ final LinkedHashMap<String, InputStreamFactory> contentDecoderMap) {
+ this.contentDecoderMap = contentDecoderMap;
+ 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() {
+ this.systemProperties = true;
+ return this;
+ }
+
+ /**
+ * Makes this instance of HttpClient proactively evict expired connections from the
+ * connection pool using a background thread.
+ * <p>
+ * One MUST explicitly close HttpClient with {@link CloseableHttpClient#close()} in order
+ * to stop and release the background thread.
+ * <p>
+ * Please note this method has no effect if the instance of HttpClient is configured to
+ * use a shared connection manager.
+ *
+ * @see #setConnectionManagerShared(boolean)
+ * @see ConnPoolControl#closeExpired()
+ *
+ * @since 4.4
+ */
+ public final HttpClientBuilder evictExpiredConnections() {
+ evictExpiredConnections = true;
+ return this;
+ }
+
+ /**
+ * Makes this instance of HttpClient proactively evict idle connections from the
+ * connection pool using a background thread.
+ * <p>
+ * One MUST explicitly close HttpClient with {@link CloseableHttpClient#close()} in order
+ * to stop and release the background thread.
+ * <p>
+ * Please note this method has no effect if the instance of HttpClient is configured to
+ * use a shared connection manager.
+ *
+ * @see #setConnectionManagerShared(boolean)
+ * @see ConnPoolControl#closeIdle(TimeValue)
+ *
+ * @param maxIdleTime maximum time persistent connections can stay idle while kept alive
+ * in the connection pool. Connections whose inactivity period exceeds this value will
+ * get closed and evicted from the pool.
+ *
+ * @since 4.4
+ */
+ public final HttpClientBuilder evictIdleConnections(final TimeValue maxIdleTime) {
+ this.evictIdleConnections = true;
+ this.maxIdleTime = maxIdleTime;
+ return this;
+ }
+
+ /**
+ * Request exec chain customization and extension.
+ * <p>
+ * For internal use.
+ */
+ @Internal
+ protected void customizeExecChain(final NamedElementChain<ExecChainHandler> execChainDefinition) {
+ }
+
+ /**
+ * Adds to the list of {@link Closeable} resources to be managed by the client.
+ * <p>
+ * For internal use.
+ */
+ @Internal
+ protected void addCloseable(final Closeable closeable) {
+ if (closeable == null) {
+ return;
+ }
+ if (closeables == null) {
+ closeables = new ArrayList<>();
+ }
+ closeables.add(closeable);
+ }
+
+ public CloseableHttpClient build() {
+ // Create main request executor
+ // We copy the instance fields to avoid changing them, and rename to avoid accidental use of the wrong version
+ HttpRequestExecutor requestExecCopy = this.requestExec;
+ if (requestExecCopy == null) {
+ requestExecCopy = new HttpRequestExecutor();
+ }
+ HttpClientConnectionManager connManagerCopy = this.connManager;
+ if (connManagerCopy == null) {
+ connManagerCopy = PoolingHttpClientConnectionManagerBuilder.create().build();
+ }
+ ConnectionReuseStrategy reuseStrategyCopy = this.reuseStrategy;
+ if (reuseStrategyCopy == null) {
+ if (systemProperties) {
+ final String s = System.getProperty("http.keepAlive", "true");
+ if ("true".equalsIgnoreCase(s)) {
+ reuseStrategyCopy = DefaultConnectionReuseStrategy.INSTANCE;
+ } else {
+ reuseStrategyCopy = new ConnectionReuseStrategy() {
+ @Override
+ public boolean keepAlive(
+ final HttpRequest request, final HttpResponse response, final HttpContext context) {
+ return false;
+ }
+ };
+ }
+ } else {
+ reuseStrategyCopy = DefaultConnectionReuseStrategy.INSTANCE;
+ }
+ }
+
+ ConnectionKeepAliveStrategy keepAliveStrategyCopy = this.keepAliveStrategy;
+ if (keepAliveStrategyCopy == null) {
+ keepAliveStrategyCopy = DefaultConnectionKeepAliveStrategy.INSTANCE;
+ }
+ AuthenticationStrategy targetAuthStrategyCopy = this.targetAuthStrategy;
+ if (targetAuthStrategyCopy == null) {
+ targetAuthStrategyCopy = DefaultAuthenticationStrategy.INSTANCE;
+ }
+ AuthenticationStrategy proxyAuthStrategyCopy = this.proxyAuthStrategy;
+ if (proxyAuthStrategyCopy == null) {
+ proxyAuthStrategyCopy = DefaultAuthenticationStrategy.INSTANCE;
+ }
+ UserTokenHandler userTokenHandlerCopy = this.userTokenHandler;
+ if (userTokenHandlerCopy == null) {
+ if (!connectionStateDisabled) {
+ userTokenHandlerCopy = DefaultUserTokenHandler.INSTANCE;
+ } else {
+ userTokenHandlerCopy = NoopUserTokenHandler.INSTANCE;
+ }
+ }
+
+ String userAgentCopy = this.userAgent;
+ if (userAgentCopy == null) {
+ if (systemProperties) {
+ userAgentCopy = System.getProperty("http.agent");
+ }
+ if (userAgentCopy == null) {
+ userAgentCopy = VersionInfo.getSoftwareInfo("Apache-HttpClient",
+ "org.apache.hc.client5", getClass());
+ }
+ }
+
+ final NamedElementChain<ExecChainHandler> execChainDefinition = new NamedElementChain<>();
+ execChainDefinition.addLast(
+ new MainClientExec(reuseStrategyCopy, keepAliveStrategyCopy, userTokenHandlerCopy),
+ ChainElements.MAIN_TRANSPORT.name());
+ execChainDefinition.addFirst(
+ new ConnectExec(
+ reuseStrategyCopy,
+ new DefaultHttpProcessor(new RequestTargetHost(), new RequestUserAgent(userAgentCopy)),
+ proxyAuthStrategyCopy),
+ ChainElements.CONNECT.name());
+
+ final HttpProcessorBuilder b = HttpProcessorBuilder.create();
+ if (requestInterceptors != null) {
+ for (final RequestInterceptorEntry entry: requestInterceptors) {
+ if (entry.postion == RequestInterceptorEntry.Postion.FIRST) {
+ b.addFirst(entry.interceptor);
+ }
+ }
+ }
+ if (responseInterceptors != null) {
+ for (final ResponseInterceptorEntry entry: responseInterceptors) {
+ if (entry.postion == ResponseInterceptorEntry.Postion.FIRST) {
+ b.addFirst(entry.interceptor);
+ }
+ }
+ }
+ b.addAll(
+ new RequestDefaultHeaders(defaultHeaders),
+ new RequestContent(),
+ new RequestTargetHost(),
+ new RequestClientConnControl(),
+ new RequestUserAgent(userAgentCopy),
+ new RequestExpectContinue());
+ if (!cookieManagementDisabled) {
+ b.add(new RequestAddCookies());
+ }
+ if (!authCachingDisabled) {
+ b.add(new RequestAuthCache());
+ }
+ if (!cookieManagementDisabled) {
+ b.add(new ResponseProcessCookies());
+ }
+ if (requestInterceptors != null) {
+ for (final RequestInterceptorEntry entry: requestInterceptors) {
+ if (entry.postion == RequestInterceptorEntry.Postion.LAST) {
+ b.addFirst(entry.interceptor);
+ }
+ }
+ }
+ if (responseInterceptors != null) {
+ for (final ResponseInterceptorEntry entry: responseInterceptors) {
+ if (entry.postion == ResponseInterceptorEntry.Postion.LAST) {
+ b.addFirst(entry.interceptor);
+ }
+ }
+ }
+ final HttpProcessor httpProcessor = b.build();
+ execChainDefinition.addFirst(
+ new ProtocolExec(httpProcessor, targetAuthStrategyCopy, proxyAuthStrategyCopy),
+ ChainElements.PROTOCOL.name());
+
+ // Add request retry executor, if not disabled
+ if (!automaticRetriesDisabled) {
+ HttpRequestRetryHandler retryHandlerCopy = this.retryHandler;
+ if (retryHandlerCopy == null) {
+ retryHandlerCopy = DefaultHttpRequestRetryHandler.INSTANCE;
+ }
+ execChainDefinition.addFirst(
+ new RetryExec(retryHandlerCopy),
+ ChainElements.RETRY_IO_ERROR.name());
+ }
+
+ HttpRoutePlanner routePlannerCopy = this.routePlanner;
+ if (routePlannerCopy == null) {
+ SchemePortResolver schemePortResolverCopy = this.schemePortResolver;
+ if (schemePortResolverCopy == null) {
+ schemePortResolverCopy = DefaultSchemePortResolver.INSTANCE;
+ }
+ if (proxy != null) {
+ routePlannerCopy = new DefaultProxyRoutePlanner(proxy, schemePortResolverCopy);
+ } else if (systemProperties) {
+ routePlannerCopy = new SystemDefaultRoutePlanner(
+ schemePortResolverCopy, ProxySelector.getDefault());
+ } else {
+ routePlannerCopy = new DefaultRoutePlanner(schemePortResolverCopy);
+ }
+ }
+
+ // Optionally, add service unavailable retry executor
+ final ServiceUnavailableRetryStrategy serviceUnavailStrategyCopy = this.serviceUnavailStrategy;
+ if (serviceUnavailStrategyCopy != null) {
+ execChainDefinition.addFirst(
+ new ServiceUnavailableRetryExec(serviceUnavailStrategyCopy),
+ ChainElements.RETRY_SERVICE_UNAVAILABLE.name());
+ }
+
+ // Add redirect executor, if not disabled
+ if (!redirectHandlingDisabled) {
+ RedirectStrategy redirectStrategyCopy = this.redirectStrategy;
+ if (redirectStrategyCopy == null) {
+ redirectStrategyCopy = DefaultRedirectStrategy.INSTANCE;
+ }
+ execChainDefinition.addFirst(
+ new RedirectExec(routePlannerCopy, redirectStrategyCopy),
+ ChainElements.REDIRECT.name());
+ }
+
+ if (!contentCompressionDisabled) {
+ if (contentDecoderMap != null) {
+ final List<String> encodings = new ArrayList<>(contentDecoderMap.keySet());
+ final RegistryBuilder<InputStreamFactory> b2 = RegistryBuilder.create();
+ for (final Map.Entry<String, InputStreamFactory> entry: contentDecoderMap.entrySet()) {
+ b2.register(entry.getKey(), entry.getValue());
+ }
+ final Registry<InputStreamFactory> decoderRegistry = b2.build();
+ execChainDefinition.addFirst(
+ new ContentCompressionExec(encodings, decoderRegistry, true),
+ ChainElements.REDIRECT.name());
+ } else {
+ execChainDefinition.addFirst(
+ new ContentCompressionExec(true),
+ ChainElements.REDIRECT.name());
+ }
+ }
+
+ // Optionally, add connection back-off executor
+ if (this.backoffManager != null && this.connectionBackoffStrategy != null) {
+ execChainDefinition.addFirst(new BackoffStrategyExec(this.connectionBackoffStrategy, this.backoffManager),
+ ChainElements.BACK_OFF.name());
+ }
+
+ if (execInterceptors != null) {
+ for (final ExecInterceptorEntry entry: execInterceptors) {
+ switch (entry.postion) {
+ case AFTER:
+ execChainDefinition.addAfter(entry.existing, entry.interceptor, entry.name);
+ break;
+ case BEFORE:
+ execChainDefinition.addBefore(entry.existing, entry.interceptor, entry.name);
+ break;
+ case REPLACE:
+ execChainDefinition.replace(entry.existing, entry.interceptor);
+ break;
+ case FIRST:
+ execChainDefinition.addFirst(entry.interceptor, entry.name);
+ break;
+ case LAST:
+ execChainDefinition.addLast(entry.interceptor, entry.name);
+ break;
+ }
+ }
+ }
+
+ customizeExecChain(execChainDefinition);
+
+ NamedElementChain<ExecChainHandler>.Node current = execChainDefinition.getLast();
+ ExecChainElement execChain = null;
+ while (current != null) {
+ execChain = new ExecChainElement(current.getValue(), execChain);
+ current = current.getPrevious();
+ }
+
+ Lookup<AuthSchemeProvider> authSchemeRegistryCopy = this.authSchemeRegistry;
+ if (authSchemeRegistryCopy == null) {
+ authSchemeRegistryCopy = RegistryBuilder.<AuthSchemeProvider>create()
+ .register(AuthSchemes.BASIC, new BasicSchemeFactory())
+ .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
+ .register(AuthSchemes.CREDSSP, new CredSspSchemeFactory())
+ .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
+ .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(SystemDefaultDnsResolver.INSTANCE, true, true))
+ .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory(SystemDefaultDnsResolver.INSTANCE, true, true))
+ .build();
+ }
+ Lookup<CookieSpecProvider> cookieSpecRegistryCopy = this.cookieSpecRegistry;
+ if (cookieSpecRegistryCopy == null) {
+ cookieSpecRegistryCopy = CookieSpecRegistries.createDefault();
+ }
+
+ 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();
+ }
+ }
+
+ List<Closeable> closeablesCopy = closeables != null ? new ArrayList<>(closeables) : null;
+ if (!this.connManagerShared) {
+ if (closeablesCopy == null) {
+ closeablesCopy = new ArrayList<>(1);
+ }
+ if (evictExpiredConnections || evictIdleConnections) {
+ if (connManagerCopy instanceof ConnPoolControl) {
+ final IdleConnectionEvictor connectionEvictor = new IdleConnectionEvictor((ConnPoolControl<?>) connManagerCopy,
+ maxIdleTime, maxIdleTime);
+ closeablesCopy.add(new Closeable() {
+
+ @Override
+ public void close() throws IOException {
+ connectionEvictor.shutdown();
+ try {
+ connectionEvictor.awaitTermination(1L, TimeUnit.SECONDS);
+ } catch (final InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ });
+ connectionEvictor.start();
+ }
+ }
+ closeablesCopy.add(connManagerCopy);
+ }
+
+ return new InternalHttpClient(
+ connManagerCopy,
+ requestExecCopy,
+ execChain,
+ routePlannerCopy,
+ cookieSpecRegistryCopy,
+ authSchemeRegistryCopy,
+ defaultCookieStore,
+ defaultCredentialsProvider,
+ defaultRequestConfig != null ? defaultRequestConfig : RequestConfig.DEFAULT,
+ closeablesCopy);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/6d17126c/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpClients.java
----------------------------------------------------------------------
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpClients.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpClients.java
new file mode 100644
index 0000000..5bd30f6
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpClients.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
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.hc.client5.http.impl.classic;
+
+import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
+import org.apache.hc.client5.http.io.HttpClientConnectionManager;
+
+/**
+ * Factory methods for {@link CloseableHttpClient} instances.
+ * @since 4.3
+ */
+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 MinimalHttpClient createMinimal() {
+ return new MinimalHttpClient(new PoolingHttpClientConnectionManager());
+ }
+
+ /**
+ * Creates {@link CloseableHttpClient} instance that implements
+ * the most basic HTTP protocol support.
+ */
+ public static MinimalHttpClient createMinimal(final HttpClientConnectionManager connManager) {
+ return new MinimalHttpClient(connManager);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/6d17126c/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpRequestFutureTask.java
----------------------------------------------------------------------
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpRequestFutureTask.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpRequestFutureTask.java
new file mode 100644
index 0000000..048593c
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpRequestFutureTask.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
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.client5.http.impl.classic;
+
+import java.util.concurrent.FutureTask;
+
+import org.apache.hc.core5.concurrent.Cancellable;
+import org.apache.hc.core5.http.ClassicHttpRequest;
+
+/**
+ * FutureTask implementation that wraps a HttpAsyncClientCallable and exposes various task
+ * specific metrics.
+ *
+ * @param <V>
+ */
+public class HttpRequestFutureTask<V> extends FutureTask<V> {
+
+ private final ClassicHttpRequest request;
+ private final HttpRequestTaskCallable<V> callable;
+
+ public HttpRequestFutureTask(
+ final ClassicHttpRequest request,
+ final HttpRequestTaskCallable<V> 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 instanceof Cancellable) {
+ ((Cancellable) request).cancel();
+ }
+ 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.toString();
+ }
+
+}
\ No newline at end of file