Removed deprecated code
git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@1681460 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
parent
a929148fb4
commit
b29c819645
|
@ -28,7 +28,7 @@
|
|||
<parent>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpcomponents-client</artifactId>
|
||||
<version>4.5-alpha1-SNAPSHOT</version>
|
||||
<version>5.0-alpha1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>fluent-hc</artifactId>
|
||||
<name>Apache HttpClient Fluent API</name>
|
||||
|
|
|
@ -231,20 +231,6 @@ public class Executor {
|
|||
return new Response(request.internalExecute(this.httpclient, localContext));
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated (4.3) do not use.
|
||||
*/
|
||||
@Deprecated
|
||||
public static void registerScheme(final org.apache.http.conn.scheme.Scheme scheme) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated (4.3) do not use.
|
||||
*/
|
||||
@Deprecated
|
||||
public static void unregisterScheme(final String name) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes all idle persistent connections used by the internal pool.
|
||||
* @since 4.4
|
||||
|
|
|
@ -252,26 +252,6 @@ public class Request {
|
|||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method has no effect. Do not use.
|
||||
*
|
||||
* @deprecated (4.3)
|
||||
*/
|
||||
@Deprecated
|
||||
public Request config(final String param, final Object object) {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method has no effect. Do not use.
|
||||
*
|
||||
* @deprecated (4.3)
|
||||
*/
|
||||
@Deprecated
|
||||
public Request removeConfig(final String param) {
|
||||
return this;
|
||||
}
|
||||
|
||||
//// HTTP protocol parameter operations
|
||||
|
||||
public Request version(final HttpVersion version) {
|
||||
|
@ -279,19 +259,6 @@ public class Request {
|
|||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* This parameter can no longer be used at the request level.
|
||||
* <p>
|
||||
* This method has no effect. Do not use.
|
||||
* </p>
|
||||
*
|
||||
* @deprecated (4.3)
|
||||
*/
|
||||
@Deprecated
|
||||
public Request elementCharset(final String charset) {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Request useExpectContinue() {
|
||||
this.useExpectContinue = Boolean.TRUE;
|
||||
return this;
|
||||
|
@ -314,16 +281,6 @@ public class Request {
|
|||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method has no effect. Do not use.
|
||||
*
|
||||
* @deprecated (4.4)
|
||||
*/
|
||||
@Deprecated
|
||||
public Request staleConnectionCheck(final boolean b) {
|
||||
return this;
|
||||
}
|
||||
|
||||
//// HTTP connection route operations
|
||||
|
||||
public Request viaProxy(final HttpHost proxy) {
|
||||
|
|
|
@ -28,7 +28,7 @@
|
|||
<parent>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpcomponents-client</artifactId>
|
||||
<version>4.5-alpha1-SNAPSHOT</version>
|
||||
<version>5.0-alpha1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>httpclient-cache</artifactId>
|
||||
<name>Apache HttpClient Cache</name>
|
||||
|
@ -109,25 +109,6 @@
|
|||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<version>1.8</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>add-source</id>
|
||||
<phase>generate-sources</phase>
|
||||
<goals>
|
||||
<goal>add-source</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>src/main/java-deprecated</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -29,8 +29,8 @@ package org.apache.http.impl.client.cache;
|
|||
import org.apache.http.util.Args;
|
||||
|
||||
/**
|
||||
* <p>Java Beans-style configuration for a {@link CachingHttpClient}. Any class
|
||||
* in the caching module that has configuration options should take a
|
||||
* <p>Java Beans-style configuration for caching {@link org.apache.http.client.HttpClient}.
|
||||
* 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
|
||||
|
@ -78,10 +78,10 @@ import org.apache.http.util.Args;
|
|||
* 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},
|
||||
* CacheConfig#isHeuristicCachingEnabled()} 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
|
||||
* CacheConfig#getHeuristicCoefficient() fraction of the time since
|
||||
* the resource was last modified}. See Sections
|
||||
* <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.2.2">
|
||||
* 13.2.2</a> and <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.2.4">
|
||||
|
@ -160,42 +160,20 @@ public class CacheConfig implements Cloneable {
|
|||
|
||||
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;
|
||||
}
|
||||
private final long maxObjectSize;
|
||||
private final int maxCacheEntries;
|
||||
private final int maxUpdateRetries;
|
||||
private final boolean allow303Caching;
|
||||
private final boolean weakETagOnPutDeleteAllowed;
|
||||
private final boolean heuristicCachingEnabled;
|
||||
private final float heuristicCoefficient;
|
||||
private final long heuristicDefaultLifetime;
|
||||
private final boolean isSharedCache;
|
||||
private final int asynchronousWorkersMax;
|
||||
private final int asynchronousWorkersCore;
|
||||
private final int asynchronousWorkerIdleLifetimeSecs;
|
||||
private final int revalidationQueueSize;
|
||||
private final boolean neverCacheHTTP10ResponsesWithQuery;
|
||||
|
||||
CacheConfig(
|
||||
final long maxObjectSize,
|
||||
|
@ -226,32 +204,7 @@ public class CacheConfig implements Cloneable {
|
|||
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;
|
||||
}
|
||||
this.neverCacheHTTP10ResponsesWithQuery = neverCacheHTTP10ResponsesWithQuery;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -264,19 +217,6 @@ public class CacheConfig implements Cloneable {
|
|||
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
|
||||
|
@ -293,16 +233,6 @@ public class CacheConfig implements Cloneable {
|
|||
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
|
||||
*/
|
||||
|
@ -310,16 +240,6 @@ public class CacheConfig implements Cloneable {
|
|||
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.
|
||||
|
@ -344,18 +264,6 @@ public class CacheConfig implements Cloneable {
|
|||
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.
|
||||
*/
|
||||
|
@ -363,21 +271,6 @@ public class CacheConfig implements Cloneable {
|
|||
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.
|
||||
|
@ -386,24 +279,6 @@ public class CacheConfig implements Cloneable {
|
|||
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-
|
||||
|
@ -413,19 +288,6 @@ public class CacheConfig implements Cloneable {
|
|||
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
|
||||
|
@ -435,19 +297,6 @@ public class CacheConfig implements Cloneable {
|
|||
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.
|
||||
|
@ -456,19 +305,6 @@ public class CacheConfig implements Cloneable {
|
|||
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 {@code 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
|
||||
|
@ -479,20 +315,6 @@ public class CacheConfig implements Cloneable {
|
|||
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.
|
||||
*/
|
||||
|
@ -500,16 +322,6 @@ public class CacheConfig implements Cloneable {
|
|||
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();
|
||||
|
|
|
@ -171,16 +171,6 @@ class CacheValidityPolicy {
|
|||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated (4.3) use {@link HttpCacheEntry#getDate()}.
|
||||
* @param entry
|
||||
* @return
|
||||
*/
|
||||
@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) {
|
||||
|
|
|
@ -162,25 +162,4 @@ public class ExponentialBackOffSchedulingStrategy implements SchedulingStrategy
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link org.apache.http.util.Args#notNull(Object, String)}
|
||||
*/
|
||||
@Deprecated
|
||||
protected static <T> T checkNotNull(final String parameterName, final T value) {
|
||||
if (value == null) {
|
||||
throw new IllegalArgumentException(parameterName + " may not be null");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link org.apache.http.util.Args#notNegative(long, String)}
|
||||
*/
|
||||
@Deprecated
|
||||
protected static long checkNotNegative(final String parameterName, final long value) {
|
||||
if (value < 0) {
|
||||
throw new IllegalArgumentException(parameterName + " may not be negative");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -45,7 +45,6 @@ import org.apache.http.params.HttpParams;
|
|||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
@Immutable
|
||||
final class OptionsHttp11Response extends AbstractHttpMessage implements HttpResponse {
|
||||
|
||||
|
|
|
@ -29,21 +29,20 @@ package org.apache.http.impl.client.cache.memcached;
|
|||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.client.cache.HttpCacheEntry;
|
||||
import org.apache.http.client.cache.HttpCacheStorage;
|
||||
import org.apache.http.client.cache.HttpCacheUpdateCallback;
|
||||
import org.apache.http.client.cache.HttpCacheUpdateException;
|
||||
import org.apache.http.impl.client.cache.CacheConfig;
|
||||
|
||||
import net.spy.memcached.CASResponse;
|
||||
import net.spy.memcached.CASValue;
|
||||
import net.spy.memcached.MemcachedClient;
|
||||
import net.spy.memcached.MemcachedClientIF;
|
||||
import net.spy.memcached.OperationTimeoutException;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.client.cache.HttpCacheEntry;
|
||||
import org.apache.http.client.cache.HttpCacheEntrySerializer;
|
||||
import org.apache.http.client.cache.HttpCacheStorage;
|
||||
import org.apache.http.client.cache.HttpCacheUpdateCallback;
|
||||
import org.apache.http.client.cache.HttpCacheUpdateException;
|
||||
import org.apache.http.impl.client.cache.CacheConfig;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* This class is a storage backend that uses an external <i>memcached</i>
|
||||
|
@ -122,30 +121,6 @@ public class MemcachedHttpCacheStorage implements HttpCacheStorage {
|
|||
new SHA256KeyHashingScheme());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a storage backend using the given <i>memcached</i> client and
|
||||
* applying the given cache configuration and cache entry serialization
|
||||
* mechanism. <b>Deprecation note:</b> In the process of fixing a bug
|
||||
* based on the need to hash logical storage keys onto memcached cache
|
||||
* keys, the serialization process was revamped. This constructor still
|
||||
* works, but the serializer argument will be ignored and default
|
||||
* implementations of the new framework will be used. You can still
|
||||
* provide custom serialization by using the
|
||||
* {@link #MemcachedHttpCacheStorage(MemcachedClientIF, CacheConfig,
|
||||
* MemcachedCacheEntryFactory, KeyHashingScheme)} constructor.
|
||||
* @param client how to talk to <i>memcached</i>
|
||||
* @param config apply HTTP cache-related options
|
||||
* @param serializer <b>ignored</b>
|
||||
*
|
||||
* @deprecated (4.2) do not use
|
||||
*/
|
||||
@Deprecated
|
||||
public MemcachedHttpCacheStorage(final MemcachedClientIF client, final CacheConfig config,
|
||||
final HttpCacheEntrySerializer serializer) {
|
||||
this(client, config, new MemcachedCacheEntryFactoryImpl(),
|
||||
new SHA256KeyHashingScheme());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a storage backend using the given <i>memcached</i> client and
|
||||
* applying the given cache configuration, serialization, and hashing
|
||||
|
|
|
@ -28,7 +28,7 @@
|
|||
<parent>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpcomponents-client</artifactId>
|
||||
<version>4.5-alpha1-SNAPSHOT</version>
|
||||
<version>5.0-alpha1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>httpclient-osgi</artifactId>
|
||||
<name>Apache HttpClient OSGi bundle</name>
|
||||
|
|
|
@ -28,7 +28,7 @@
|
|||
<parent>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpcomponents-client</artifactId>
|
||||
<version>4.5-alpha1-SNAPSHOT</version>
|
||||
<version>5.0-alpha1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>httpclient-win</artifactId>
|
||||
<name>Apache HttpClient Windows features</name>
|
||||
|
|
|
@ -298,12 +298,4 @@ public class WindowsNegotiateScheme extends AuthSchemeBase {
|
|||
return !continueNeeded;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Deprecated
|
||||
public Header authenticate(
|
||||
final Credentials credentials,
|
||||
final HttpRequest request) throws AuthenticationException {
|
||||
return authenticate(credentials, request, null);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -28,7 +28,7 @@
|
|||
<parent>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpcomponents-client</artifactId>
|
||||
<version>4.5-alpha1-SNAPSHOT</version>
|
||||
<version>5.0-alpha1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<name>Apache HttpClient</name>
|
||||
|
@ -77,25 +77,6 @@
|
|||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<version>1.8</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>add-source</id>
|
||||
<phase>generate-sources</phase>
|
||||
<goals>
|
||||
<goal>add-source</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>src/main/java-deprecated</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>com.googlecode.maven-download-plugin</groupId>
|
||||
<artifactId>download-maven-plugin</artifactId>
|
||||
|
|
|
@ -1,55 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.auth.params;
|
||||
|
||||
import org.apache.http.params.HttpAbstractParamBean;
|
||||
import org.apache.http.params.HttpParams;
|
||||
|
||||
/**
|
||||
* This is a Java Bean class that can be used to wrap an instance of
|
||||
* {@link HttpParams} and manipulate HTTP authentication parameters
|
||||
* using Java Beans conventions.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) use {@link org.apache.http.client.config.RequestConfig}
|
||||
* and constructor parameters of
|
||||
* {@link org.apache.http.auth.AuthSchemeProvider}s.
|
||||
*/
|
||||
@Deprecated
|
||||
public class AuthParamBean extends HttpAbstractParamBean {
|
||||
|
||||
public AuthParamBean (final HttpParams params) {
|
||||
super(params);
|
||||
}
|
||||
|
||||
public void setCredentialCharset (final String charset) {
|
||||
AuthParams.setCredentialCharset(params, charset);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,82 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.auth.params;
|
||||
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.protocol.HTTP;
|
||||
import org.apache.http.util.Args;
|
||||
|
||||
/**
|
||||
* An adaptor for manipulating HTTP authentication parameters
|
||||
* in {@link HttpParams}.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) use {@link org.apache.http.client.config.RequestConfig}
|
||||
* and constructor parameters of
|
||||
* {@link org.apache.http.auth.AuthSchemeProvider}s.
|
||||
*/
|
||||
@Immutable
|
||||
@Deprecated
|
||||
public final class AuthParams {
|
||||
|
||||
private AuthParams() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains the charset for encoding
|
||||
* {@link org.apache.http.auth.Credentials}.If not configured,
|
||||
* {@link HTTP#DEFAULT_PROTOCOL_CHARSET}is used instead.
|
||||
*
|
||||
* @return The charset
|
||||
*/
|
||||
public static String getCredentialCharset(final HttpParams params) {
|
||||
Args.notNull(params, "HTTP parameters");
|
||||
String charset = (String) params.getParameter
|
||||
(AuthPNames.CREDENTIAL_CHARSET);
|
||||
if (charset == null) {
|
||||
charset = HTTP.DEF_PROTOCOL_CHARSET.name();
|
||||
}
|
||||
return charset;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sets the charset to be used when encoding
|
||||
* {@link org.apache.http.auth.Credentials}.
|
||||
*
|
||||
* @param charset The charset
|
||||
*/
|
||||
public static void setCredentialCharset(final HttpParams params, final String charset) {
|
||||
Args.notNull(params, "HTTP parameters");
|
||||
params.setParameter(AuthPNames.CREDENTIAL_CHARSET, charset);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,101 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.auth.AuthScheme;
|
||||
import org.apache.http.auth.AuthenticationException;
|
||||
import org.apache.http.auth.MalformedChallengeException;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
|
||||
/**
|
||||
/**
|
||||
* A handler for determining if an HTTP response represents an authentication
|
||||
* challenge that was sent back to the client as a result of authentication
|
||||
* failure.
|
||||
* <p>
|
||||
* 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
|
||||
*
|
||||
* @deprecated (4.2) use {@link AuthenticationStrategy}
|
||||
*/
|
||||
@Deprecated
|
||||
public interface AuthenticationHandler {
|
||||
|
||||
/**
|
||||
* Determines if the given HTTP response response represents
|
||||
* an authentication challenge that was sent back as a result
|
||||
* of authentication failure
|
||||
* @param response HTTP response.
|
||||
* @param context HTTP context.
|
||||
* @return {@code true} if user authentication is required,
|
||||
* {@code false} otherwise.
|
||||
*/
|
||||
boolean isAuthenticationRequested(
|
||||
HttpResponse response,
|
||||
HttpContext context);
|
||||
|
||||
/**
|
||||
* Extracts from the given HTTP response a collection of authentication
|
||||
* challenges, each of which represents an authentication scheme supported
|
||||
* by the authentication host.
|
||||
*
|
||||
* @param response HTTP response.
|
||||
* @param context HTTP context.
|
||||
* @return a collection of challenges keyed by names of corresponding
|
||||
* authentication schemes.
|
||||
* @throws MalformedChallengeException if one of the authentication
|
||||
* challenges is not valid or malformed.
|
||||
*/
|
||||
Map<String, Header> getChallenges(
|
||||
HttpResponse response,
|
||||
HttpContext context) throws MalformedChallengeException;
|
||||
|
||||
/**
|
||||
* Selects one authentication challenge out of all available and
|
||||
* creates and generates {@link AuthScheme} instance capable of
|
||||
* processing that challenge.
|
||||
* @param challenges collection of challenges.
|
||||
* @param response HTTP response.
|
||||
* @param context HTTP context.
|
||||
* @return authentication scheme to use for authentication.
|
||||
* @throws AuthenticationException if an authentication scheme
|
||||
* could not be selected.
|
||||
*/
|
||||
AuthScheme selectScheme(
|
||||
Map<String, Header> challenges,
|
||||
HttpResponse response,
|
||||
HttpContext context) throws AuthenticationException;
|
||||
|
||||
}
|
|
@ -1,77 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.ProtocolException;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
|
||||
/**
|
||||
* A handler for determining if an HTTP request should be redirected to
|
||||
* a new location in response to an HTTP response received from the target
|
||||
* server.
|
||||
* <p>
|
||||
* 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
|
||||
*
|
||||
* @deprecated (4.1) use {@link RedirectStrategy}
|
||||
*/
|
||||
@Deprecated
|
||||
public interface RedirectHandler {
|
||||
|
||||
/**
|
||||
* Determines if a request should be redirected to a new location
|
||||
* given the response from the target server.
|
||||
*
|
||||
* @param response the response received from the target server
|
||||
* @param context the context for the request execution
|
||||
*
|
||||
* @return {@code true} if the request should be redirected, {@code false}
|
||||
* otherwise
|
||||
*/
|
||||
boolean isRedirectRequested(HttpResponse response, HttpContext context);
|
||||
|
||||
/**
|
||||
* Determines the location request is expected to be redirected to
|
||||
* given the response from the target server and the current request
|
||||
* execution context.
|
||||
*
|
||||
* @param response the response received from the target server
|
||||
* @param context the context for the request execution
|
||||
*
|
||||
* @return redirect URI
|
||||
*/
|
||||
URI getLocationURI(HttpResponse response, HttpContext context)
|
||||
throws ProtocolException;
|
||||
|
||||
}
|
|
@ -1,78 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.http.HttpException;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
|
||||
/**
|
||||
* A client-side request director.
|
||||
* The director decides which steps are necessary to execute a request.
|
||||
* It establishes connections and optionally processes redirects and
|
||||
* authentication challenges. The director may therefore generate and
|
||||
* send a sequence of requests in order to execute one initial request.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) No longer used
|
||||
*/
|
||||
@Deprecated
|
||||
public interface RequestDirector {
|
||||
|
||||
|
||||
/**
|
||||
* Executes a request.
|
||||
* <p>
|
||||
* <b>Note:</b> For the time being, a new director is instantiated for each request.
|
||||
* This is the same behavior as for {@code HttpMethodDirector}
|
||||
* in HttpClient 3.
|
||||
* </p>
|
||||
*
|
||||
* @param target the target host for the request.
|
||||
* Implementations may accept {@code 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 for executing the request
|
||||
*
|
||||
* @return the final response to the request.
|
||||
* This is never an intermediate response with status code 1xx.
|
||||
*
|
||||
* @throws HttpException in case of a problem
|
||||
* @throws IOException in case of an IO problem
|
||||
* or if the connection was aborted
|
||||
*/
|
||||
HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
|
||||
throws HttpException, IOException;
|
||||
|
||||
}
|
|
@ -1,79 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client.params;
|
||||
|
||||
import org.apache.http.annotation.Immutable;
|
||||
|
||||
/**
|
||||
* Standard authentication schemes supported by HttpClient.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) use {@link org.apache.http.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";
|
||||
|
||||
}
|
|
@ -1,106 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client.params;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.annotation.NotThreadSafe;
|
||||
import org.apache.http.params.HttpAbstractParamBean;
|
||||
import org.apache.http.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 org.apache.http.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 <Header> 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);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,80 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client.params;
|
||||
|
||||
import org.apache.http.annotation.Immutable;
|
||||
|
||||
/**
|
||||
* Standard cookie specifications supported by HttpClient.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) use {@link org.apache.http.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();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,116 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client.params;
|
||||
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.params.HttpConnectionParams;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.util.Args;
|
||||
|
||||
/**
|
||||
* An adaptor for manipulating HTTP client parameters in {@link HttpParams}.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) use {@link org.apache.http.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);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,132 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client.protocol;
|
||||
|
||||
/**
|
||||
* {@link org.apache.http.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 org.apache.http.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 org.apache.http.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 org.apache.http.config.Lookup} object that represents
|
||||
* the actual {@link org.apache.http.cookie.CookieSpecRegistry} registry.
|
||||
*/
|
||||
public static final String COOKIESPEC_REGISTRY = "http.cookiespec-registry";
|
||||
|
||||
/**
|
||||
* Attribute name of a {@link org.apache.http.cookie.CookieSpec}
|
||||
* object that represents the actual cookie specification.
|
||||
*/
|
||||
public static final String COOKIE_SPEC = "http.cookie-spec";
|
||||
|
||||
/**
|
||||
* Attribute name of a {@link org.apache.http.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 org.apache.http.client.CookieStore}
|
||||
* object that represents the actual cookie store.
|
||||
*/
|
||||
public static final String COOKIE_STORE = "http.cookie-store";
|
||||
|
||||
/**
|
||||
* Attribute name of a {@link org.apache.http.client.CredentialsProvider}
|
||||
* object that represents the actual credentials provider.
|
||||
*/
|
||||
public static final String CREDS_PROVIDER = "http.auth.credentials-provider";
|
||||
|
||||
/**
|
||||
* Attribute name of a {@link org.apache.http.client.AuthCache} object
|
||||
* that represents the auth scheme cache.
|
||||
*/
|
||||
public static final String AUTH_CACHE = "http.auth.auth-cache";
|
||||
|
||||
/**
|
||||
* Attribute name of a {@link org.apache.http.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 org.apache.http.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 org.apache.http.config.Lookup} object that represents
|
||||
* the actual {@link org.apache.http.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 org.apache.http.client.config.RequestConfig} object that
|
||||
* represents the actual request configuration.
|
||||
*
|
||||
* @since 4.3
|
||||
*/
|
||||
public static final String REQUEST_CONFIG = "http.request-config";
|
||||
|
||||
}
|
|
@ -1,72 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client.protocol;
|
||||
|
||||
import org.apache.http.annotation.NotThreadSafe;
|
||||
import org.apache.http.auth.AuthSchemeRegistry;
|
||||
import org.apache.http.client.CookieStore;
|
||||
import org.apache.http.client.CredentialsProvider;
|
||||
import org.apache.http.cookie.CookieSpecRegistry;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.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);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,126 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client.protocol;
|
||||
|
||||
import java.util.Queue;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.HttpRequestInterceptor;
|
||||
import org.apache.http.auth.AuthOption;
|
||||
import org.apache.http.auth.AuthScheme;
|
||||
import org.apache.http.auth.AuthState;
|
||||
import org.apache.http.auth.AuthenticationException;
|
||||
import org.apache.http.auth.ContextAwareAuthScheme;
|
||||
import org.apache.http.auth.Credentials;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.util.Asserts;
|
||||
|
||||
@Deprecated
|
||||
abstract class RequestAuthenticationBase implements HttpRequestInterceptor {
|
||||
|
||||
final Log log = LogFactory.getLog(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()) { // TODO add UNCHALLENGED and HANDSHAKE cases
|
||||
case FAILURE:
|
||||
return;
|
||||
case SUCCESS:
|
||||
ensureAuthScheme(authScheme);
|
||||
if (authScheme.isConnectionBased()) {
|
||||
return;
|
||||
}
|
||||
break;
|
||||
case CHALLENGED:
|
||||
final Queue<AuthOption> 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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,92 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client.protocol;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.http.HttpException;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.auth.AUTH;
|
||||
import org.apache.http.auth.AuthState;
|
||||
import org.apache.http.conn.HttpRoutedConnection;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.protocol.ExecutionContext;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.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 org.apache.http.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);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,83 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client.protocol;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.http.HttpException;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.auth.AUTH;
|
||||
import org.apache.http.auth.AuthState;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.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 org.apache.http.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);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,151 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client.protocol;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.HttpException;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.HttpResponseInterceptor;
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.auth.AuthScheme;
|
||||
import org.apache.http.auth.AuthState;
|
||||
import org.apache.http.client.AuthCache;
|
||||
import org.apache.http.client.params.AuthPolicy;
|
||||
import org.apache.http.conn.scheme.Scheme;
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.impl.client.BasicAuthCache;
|
||||
import org.apache.http.protocol.ExecutionContext;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.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 org.apache.http.client.AuthenticationStrategy}
|
||||
*/
|
||||
@Immutable
|
||||
@Deprecated
|
||||
public class ResponseAuthCache implements HttpResponseInterceptor {
|
||||
|
||||
private final Log log = LogFactory.getLog(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()) { // TODO add SUCCESS, UNCHALLENGED and HANDSHAKE cases
|
||||
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()) { // TODO add SUCCESS, UNCHALLENGED and HANDSHAKE cases
|
||||
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);
|
||||
}
|
||||
}
|
|
@ -1,45 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client.utils;
|
||||
|
||||
/**
|
||||
* Abstraction of international domain name (IDN) conversion.
|
||||
*
|
||||
* @deprecated (4.4) use standard {@link java.net.IDN}.
|
||||
*
|
||||
* @since 4.0
|
||||
*/
|
||||
@Deprecated
|
||||
public interface Idn {
|
||||
/**
|
||||
* Converts a name from its punycode representation to Unicode.
|
||||
* The name may be a single hostname or a dot-separated qualified domain name.
|
||||
* @param punycode the Punycode representation
|
||||
* @return the Unicode domain name
|
||||
*/
|
||||
String toUnicode(String punycode);
|
||||
}
|
|
@ -1,75 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client.utils;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import org.apache.http.annotation.Immutable;
|
||||
|
||||
/**
|
||||
* Uses the java.net.IDN class through reflection.
|
||||
*
|
||||
* @deprecated (4.4) use standard {@link java.net.IDN}.
|
||||
*
|
||||
* @since 4.0
|
||||
*/
|
||||
@Immutable
|
||||
@Deprecated
|
||||
public class JdkIdn implements Idn {
|
||||
private final Method toUnicode;
|
||||
|
||||
/**
|
||||
*
|
||||
* @throws ClassNotFoundException if java.net.IDN is not available
|
||||
*/
|
||||
public JdkIdn() throws ClassNotFoundException {
|
||||
final Class<?> clazz = Class.forName("java.net.IDN");
|
||||
try {
|
||||
toUnicode = clazz.getMethod("toUnicode", String.class);
|
||||
} catch (final SecurityException e) {
|
||||
// doesn't happen
|
||||
throw new IllegalStateException(e.getMessage(), e);
|
||||
} catch (final NoSuchMethodException e) {
|
||||
// doesn't happen
|
||||
throw new IllegalStateException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toUnicode(final String punycode) {
|
||||
try {
|
||||
return (String) toUnicode.invoke(null, punycode);
|
||||
} catch (final IllegalAccessException e) {
|
||||
throw new IllegalStateException(e.getMessage(), e);
|
||||
} catch (final InvocationTargetException e) {
|
||||
final Throwable t = e.getCause();
|
||||
throw new RuntimeException(t.getMessage(), t);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,57 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client.utils;
|
||||
|
||||
import org.apache.http.annotation.Immutable;
|
||||
|
||||
/**
|
||||
* Facade that provides conversion between Unicode and Punycode domain names.
|
||||
* It will use an appropriate implementation.
|
||||
*
|
||||
* @deprecated (4.4) use standard {@link java.net.IDN}.
|
||||
*
|
||||
* @since 4.0
|
||||
*/
|
||||
@Immutable
|
||||
@Deprecated
|
||||
public class Punycode {
|
||||
private static final Idn impl;
|
||||
static {
|
||||
Idn _impl;
|
||||
try {
|
||||
_impl = new JdkIdn();
|
||||
} catch (final Exception e) {
|
||||
_impl = new Rfc3492Idn();
|
||||
}
|
||||
impl = _impl;
|
||||
}
|
||||
|
||||
public static String toUnicode(final String punycode) {
|
||||
return impl.toUnicode(punycode);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,145 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.client.utils;
|
||||
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
import org.apache.http.annotation.Immutable;
|
||||
|
||||
/**
|
||||
* Implementation from pseudo code in RFC 3492.
|
||||
*
|
||||
* @deprecated (4.4) use standard {@link java.net.IDN}.
|
||||
*
|
||||
* @since 4.0
|
||||
*/
|
||||
@Immutable
|
||||
@Deprecated
|
||||
public class Rfc3492Idn implements Idn {
|
||||
private static final int base = 36;
|
||||
private static final int tmin = 1;
|
||||
private static final int tmax = 26;
|
||||
private static final int skew = 38;
|
||||
private static final int damp = 700;
|
||||
private static final int initial_bias = 72;
|
||||
private static final int initial_n = 128;
|
||||
private static final char delimiter = '-';
|
||||
private static final String ACE_PREFIX = "xn--";
|
||||
|
||||
private int adapt(final int delta, final int numpoints, final boolean firsttime) {
|
||||
int d = delta;
|
||||
if (firsttime) {
|
||||
d = d / damp;
|
||||
} else {
|
||||
d = d / 2;
|
||||
}
|
||||
d = d + (d / numpoints);
|
||||
int k = 0;
|
||||
while (d > ((base - tmin) * tmax) / 2) {
|
||||
d = d / (base - tmin);
|
||||
k = k + base;
|
||||
}
|
||||
return k + (((base - tmin + 1) * d) / (d + skew));
|
||||
}
|
||||
|
||||
private int digit(final char c) {
|
||||
if ((c >= 'A') && (c <= 'Z')) {
|
||||
return (c - 'A');
|
||||
}
|
||||
if ((c >= 'a') && (c <= 'z')) {
|
||||
return (c - 'a');
|
||||
}
|
||||
if ((c >= '0') && (c <= '9')) {
|
||||
return (c - '0') + 26;
|
||||
}
|
||||
throw new IllegalArgumentException("illegal digit: "+ c);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toUnicode(final String punycode) {
|
||||
final StringBuilder unicode = new StringBuilder(punycode.length());
|
||||
final StringTokenizer tok = new StringTokenizer(punycode, ".");
|
||||
while (tok.hasMoreTokens()) {
|
||||
String t = tok.nextToken();
|
||||
if (unicode.length() > 0) {
|
||||
unicode.append('.');
|
||||
}
|
||||
if (t.startsWith(ACE_PREFIX)) {
|
||||
t = decode(t.substring(4));
|
||||
}
|
||||
unicode.append(t);
|
||||
}
|
||||
return unicode.toString();
|
||||
}
|
||||
|
||||
protected String decode(final String s) {
|
||||
String input = s;
|
||||
int n = initial_n;
|
||||
int i = 0;
|
||||
int bias = initial_bias;
|
||||
final StringBuilder output = new StringBuilder(input.length());
|
||||
final int lastdelim = input.lastIndexOf(delimiter);
|
||||
if (lastdelim != -1) {
|
||||
output.append(input.subSequence(0, lastdelim));
|
||||
input = input.substring(lastdelim + 1);
|
||||
}
|
||||
|
||||
while (!input.isEmpty()) {
|
||||
final int oldi = i;
|
||||
int w = 1;
|
||||
for (int k = base;; k += base) {
|
||||
if (input.isEmpty()) {
|
||||
break;
|
||||
}
|
||||
final char c = input.charAt(0);
|
||||
input = input.substring(1);
|
||||
final int digit = digit(c);
|
||||
i = i + digit * w; // FIXME fail on overflow
|
||||
final int t;
|
||||
if (k <= bias + tmin) {
|
||||
t = tmin;
|
||||
} else if (k >= bias + tmax) {
|
||||
t = tmax;
|
||||
} else {
|
||||
t = k - bias;
|
||||
}
|
||||
if (digit < t) {
|
||||
break;
|
||||
}
|
||||
w = w * (base - t); // FIXME fail on overflow
|
||||
}
|
||||
bias = adapt(i - oldi, output.length() + 1, (oldi == 0));
|
||||
n = n + i / (output.length() + 1); // FIXME fail on overflow
|
||||
i = i % (output.length() + 1);
|
||||
// {if n is a basic code point then fail}
|
||||
output.insert(i, (char) n);
|
||||
i++;
|
||||
}
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,105 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import org.apache.http.annotation.NotThreadSafe;
|
||||
import org.apache.http.util.Args;
|
||||
|
||||
/**
|
||||
* Basic implementation of {@link EofSensorWatcher}. The underlying connection
|
||||
* is released on close or EOF.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) do not use.
|
||||
*/
|
||||
@Deprecated
|
||||
@NotThreadSafe
|
||||
public class BasicEofSensorWatcher implements EofSensorWatcher {
|
||||
|
||||
/** The connection to auto-release. */
|
||||
protected final ManagedClientConnection managedConn;
|
||||
|
||||
/** Whether to keep the connection alive. */
|
||||
protected final boolean attemptReuse;
|
||||
|
||||
/**
|
||||
* Creates a new watcher for auto-releasing a connection.
|
||||
*
|
||||
* @param conn the connection to auto-release
|
||||
* @param reuse whether the connection should be re-used
|
||||
*/
|
||||
public BasicEofSensorWatcher(final ManagedClientConnection conn,
|
||||
final boolean reuse) {
|
||||
Args.notNull(conn, "Connection");
|
||||
managedConn = conn;
|
||||
attemptReuse = reuse;
|
||||
}
|
||||
|
||||
public boolean eofDetected(final InputStream wrapped)
|
||||
throws IOException {
|
||||
|
||||
try {
|
||||
if (attemptReuse) {
|
||||
// there may be some cleanup required, such as
|
||||
// reading trailers after the response body:
|
||||
wrapped.close();
|
||||
managedConn.markReusable();
|
||||
}
|
||||
} finally {
|
||||
managedConn.releaseConnection();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean streamClosed(final InputStream wrapped)
|
||||
throws IOException {
|
||||
|
||||
try {
|
||||
if (attemptReuse) {
|
||||
// this assumes that closing the stream will
|
||||
// consume the remainder of the response body:
|
||||
wrapped.close();
|
||||
managedConn.markReusable();
|
||||
}
|
||||
} finally {
|
||||
managedConn.releaseConnection();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean streamAbort(final InputStream wrapped)
|
||||
throws IOException {
|
||||
|
||||
managedConn.abortConnection();
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,208 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.SocketException;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.annotation.NotThreadSafe;
|
||||
import org.apache.http.entity.HttpEntityWrapper;
|
||||
import org.apache.http.util.Args;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
||||
/**
|
||||
* An entity that releases a {@link ManagedClientConnection connection}.
|
||||
* A {@link ManagedClientConnection} will
|
||||
* typically <i>not</i> return a managed entity, but you can replace
|
||||
* the unmanaged entity in the response with a managed one.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) do not use.
|
||||
*/
|
||||
@Deprecated
|
||||
@NotThreadSafe
|
||||
public class BasicManagedEntity extends HttpEntityWrapper
|
||||
implements ConnectionReleaseTrigger, EofSensorWatcher {
|
||||
|
||||
/** The connection to release. */
|
||||
protected ManagedClientConnection managedConn;
|
||||
|
||||
/** Whether to keep the connection alive. */
|
||||
protected final boolean attemptReuse;
|
||||
|
||||
/**
|
||||
* Creates a new managed entity that can release a connection.
|
||||
*
|
||||
* @param entity the entity of which to wrap the content.
|
||||
* Note that the argument entity can no longer be used
|
||||
* afterwards, since the content will be taken by this
|
||||
* managed entity.
|
||||
* @param conn the connection to release
|
||||
* @param reuse whether the connection should be re-used
|
||||
*/
|
||||
public BasicManagedEntity(final HttpEntity entity,
|
||||
final ManagedClientConnection conn,
|
||||
final boolean reuse) {
|
||||
super(entity);
|
||||
Args.notNull(conn, "Connection");
|
||||
this.managedConn = conn;
|
||||
this.attemptReuse = reuse;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRepeatable() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getContent() throws IOException {
|
||||
return new EofSensorInputStream(wrappedEntity.getContent(), this);
|
||||
}
|
||||
|
||||
private void ensureConsumed() throws IOException {
|
||||
if (managedConn == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (attemptReuse) {
|
||||
// this will not trigger a callback from EofSensorInputStream
|
||||
EntityUtils.consume(wrappedEntity);
|
||||
managedConn.markReusable();
|
||||
} else {
|
||||
managedConn.unmarkReusable();
|
||||
}
|
||||
} finally {
|
||||
releaseManagedConnection();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated (4.1) Use {@link EntityUtils#consume(HttpEntity)}
|
||||
*/
|
||||
@Deprecated
|
||||
@Override
|
||||
public void consumeContent() throws IOException {
|
||||
ensureConsumed();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeTo(final OutputStream outstream) throws IOException {
|
||||
super.writeTo(outstream);
|
||||
ensureConsumed();
|
||||
}
|
||||
|
||||
public void releaseConnection() throws IOException {
|
||||
ensureConsumed();
|
||||
}
|
||||
|
||||
public void abortConnection() throws IOException {
|
||||
|
||||
if (managedConn != null) {
|
||||
try {
|
||||
managedConn.abortConnection();
|
||||
} finally {
|
||||
managedConn = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean eofDetected(final InputStream wrapped) throws IOException {
|
||||
try {
|
||||
if (managedConn != null) {
|
||||
if (attemptReuse) {
|
||||
// there may be some cleanup required, such as
|
||||
// reading trailers after the response body:
|
||||
wrapped.close();
|
||||
managedConn.markReusable();
|
||||
} else {
|
||||
managedConn.unmarkReusable();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
releaseManagedConnection();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean streamClosed(final InputStream wrapped) throws IOException {
|
||||
try {
|
||||
if (managedConn != null) {
|
||||
if (attemptReuse) {
|
||||
final boolean valid = managedConn.isOpen();
|
||||
// this assumes that closing the stream will
|
||||
// consume the remainder of the response body:
|
||||
try {
|
||||
wrapped.close();
|
||||
managedConn.markReusable();
|
||||
} catch (final SocketException ex) {
|
||||
if (valid) {
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
managedConn.unmarkReusable();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
releaseManagedConnection();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean streamAbort(final InputStream wrapped) throws IOException {
|
||||
if (managedConn != null) {
|
||||
managedConn.abortConnection();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases the connection gracefully.
|
||||
* The connection attribute will be nullified.
|
||||
* Subsequent invocations are no-ops.
|
||||
*
|
||||
* @throws IOException in case of an IO problem.
|
||||
* The connection attribute will be nullified anyway.
|
||||
*/
|
||||
protected void releaseManagedConnection()
|
||||
throws IOException {
|
||||
|
||||
if (managedConn != null) {
|
||||
try {
|
||||
managedConn.releaseConnection();
|
||||
} finally {
|
||||
managedConn = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,47 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn;
|
||||
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.params.HttpParams;
|
||||
|
||||
/**
|
||||
* A factory for creating new {@link ClientConnectionManager} instances.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) replaced by {@link HttpClientConnectionManager}.
|
||||
*/
|
||||
@Deprecated
|
||||
public interface ClientConnectionManagerFactory {
|
||||
|
||||
ClientConnectionManager newInstance(
|
||||
HttpParams params,
|
||||
SchemeRegistry schemeRegistry);
|
||||
|
||||
}
|
|
@ -1,107 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
|
||||
/**
|
||||
* ClientConnectionOperator represents a strategy for creating
|
||||
* {@link OperatedClientConnection} instances and updating the underlying
|
||||
* {@link java.net.Socket} of those objects. Implementations will most
|
||||
* likely make use of {@link org.apache.http.conn.scheme.SchemeSocketFactory}s
|
||||
* to create {@link java.net.Socket} instances.
|
||||
* <p>
|
||||
* The methods in this interface allow the creation of plain and layered
|
||||
* sockets. Creating a tunnelled connection through a proxy, however,
|
||||
* is not within the scope of the operator.
|
||||
* <p>
|
||||
* 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
|
||||
*
|
||||
* @deprecated (4.3) replaced by {@link HttpClientConnectionManager}.
|
||||
*/
|
||||
@Deprecated
|
||||
public interface ClientConnectionOperator {
|
||||
|
||||
/**
|
||||
* Creates a new connection that can be operated.
|
||||
*
|
||||
* @return a new, unopened connection for use with this operator
|
||||
*/
|
||||
OperatedClientConnection createConnection();
|
||||
|
||||
/**
|
||||
* Opens a connection to the given target host.
|
||||
*
|
||||
* @param conn the connection to open
|
||||
* @param target the target host to connect to
|
||||
* @param local the local address to route from, or
|
||||
* {@code null} for the default
|
||||
* @param context the context for the connection
|
||||
* @param params the parameters for the connection
|
||||
*
|
||||
* @throws IOException in case of a problem
|
||||
*/
|
||||
void openConnection(OperatedClientConnection conn,
|
||||
HttpHost target,
|
||||
InetAddress local,
|
||||
HttpContext context,
|
||||
HttpParams params)
|
||||
throws IOException;
|
||||
|
||||
/**
|
||||
* Updates a connection with a layered secure connection.
|
||||
* The typical use of this method is to update a tunnelled plain
|
||||
* connection (HTTP) to a secure TLS/SSL connection (HTTPS).
|
||||
*
|
||||
* @param conn the open connection to update
|
||||
* @param target the target host for the updated connection.
|
||||
* The connection must already be open or tunnelled
|
||||
* to the host and port, but the scheme of the target
|
||||
* will be used to create a layered connection.
|
||||
* @param context the context for the connection
|
||||
* @param params the parameters for the updated connection
|
||||
*
|
||||
* @throws IOException in case of a problem
|
||||
*/
|
||||
void updateSecureConnection(OperatedClientConnection conn,
|
||||
HttpHost target,
|
||||
HttpContext context,
|
||||
HttpParams params)
|
||||
throws IOException;
|
||||
|
||||
}
|
||||
|
|
@ -1,173 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.conn.scheme.SocketFactory;
|
||||
import org.apache.http.params.HttpConnectionParams;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.util.Args;
|
||||
import org.apache.http.util.Asserts;
|
||||
|
||||
/**
|
||||
* Socket factory that implements a simple multi-home fail-over on connect failure,
|
||||
* provided the same hostname resolves to multiple {@link InetAddress}es. Please note
|
||||
* the {@link #connectSocket(Socket, String, int, InetAddress, int, HttpParams)}
|
||||
* method cannot be reliably interrupted by closing the socket returned by the
|
||||
* {@link #createSocket()} method.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.1) Do not use. For multihome support socket factories must implement
|
||||
* {@link org.apache.http.conn.scheme.SchemeSocketFactory} interface.
|
||||
*/
|
||||
@Deprecated
|
||||
@Immutable
|
||||
public final class MultihomePlainSocketFactory implements SocketFactory {
|
||||
|
||||
/**
|
||||
* The factory singleton.
|
||||
*/
|
||||
private static final
|
||||
MultihomePlainSocketFactory DEFAULT_FACTORY = new MultihomePlainSocketFactory();
|
||||
|
||||
/**
|
||||
* Gets the singleton instance of this class.
|
||||
* @return the one and only plain socket factory
|
||||
*/
|
||||
public static MultihomePlainSocketFactory getSocketFactory() {
|
||||
return DEFAULT_FACTORY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restricted default constructor.
|
||||
*/
|
||||
private MultihomePlainSocketFactory() {
|
||||
super();
|
||||
}
|
||||
|
||||
|
||||
// non-javadoc, see interface org.apache.http.conn.SocketFactory
|
||||
public Socket createSocket() {
|
||||
return new Socket();
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to connects the socket to any of the {@link InetAddress}es the
|
||||
* given host name resolves to. If connection to all addresses fail, the
|
||||
* last I/O exception is propagated to the caller.
|
||||
*
|
||||
* @param socket socket to connect to any of the given addresses
|
||||
* @param host Host name to connect to
|
||||
* @param port the port to connect to
|
||||
* @param localAddress local address
|
||||
* @param localPort local port
|
||||
* @param params HTTP parameters
|
||||
*
|
||||
* @throws IOException if an error occurs during the connection
|
||||
* @throws SocketTimeoutException if timeout expires before connecting
|
||||
*/
|
||||
public Socket connectSocket(final Socket socket, final String host, final int port,
|
||||
final InetAddress localAddress, final int localPort,
|
||||
final HttpParams params)
|
||||
throws IOException {
|
||||
Args.notNull(host, "Target host");
|
||||
Args.notNull(params, "HTTP parameters");
|
||||
|
||||
Socket sock = socket;
|
||||
if (sock == null) {
|
||||
sock = createSocket();
|
||||
}
|
||||
|
||||
if ((localAddress != null) || (localPort > 0)) {
|
||||
final InetSocketAddress isa = new InetSocketAddress(localAddress,
|
||||
localPort > 0 ? localPort : 0);
|
||||
sock.bind(isa);
|
||||
}
|
||||
|
||||
final int timeout = HttpConnectionParams.getConnectionTimeout(params);
|
||||
|
||||
final InetAddress[] inetadrs = InetAddress.getAllByName(host);
|
||||
final List<InetAddress> addresses = new ArrayList<InetAddress>(inetadrs.length);
|
||||
addresses.addAll(Arrays.asList(inetadrs));
|
||||
Collections.shuffle(addresses);
|
||||
|
||||
IOException lastEx = null;
|
||||
for (final InetAddress remoteAddress: addresses) {
|
||||
try {
|
||||
sock.connect(new InetSocketAddress(remoteAddress, port), timeout);
|
||||
break;
|
||||
} catch (final SocketTimeoutException ex) {
|
||||
throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
|
||||
} catch (final IOException ex) {
|
||||
// create new socket
|
||||
sock = new Socket();
|
||||
// keep the last exception and retry
|
||||
lastEx = ex;
|
||||
}
|
||||
}
|
||||
if (lastEx != null) {
|
||||
throw lastEx;
|
||||
}
|
||||
return sock;
|
||||
} // connectSocket
|
||||
|
||||
|
||||
/**
|
||||
* Checks whether a socket connection is secure.
|
||||
* This factory creates plain socket connections
|
||||
* which are not considered secure.
|
||||
*
|
||||
* @param sock the connected socket
|
||||
*
|
||||
* @return {@code false}
|
||||
*
|
||||
* @throws IllegalArgumentException if the argument is invalid
|
||||
*/
|
||||
public final boolean isSecure(final Socket sock)
|
||||
throws IllegalArgumentException {
|
||||
|
||||
Args.notNull(sock, "Socket");
|
||||
// This check is performed last since it calls a method implemented
|
||||
// by the argument object. getClass() is final in java.lang.Object.
|
||||
Asserts.check(!sock.isClosed(), "Socket is closed");
|
||||
return false;
|
||||
|
||||
} // isSecure
|
||||
|
||||
}
|
|
@ -1,157 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
|
||||
import org.apache.http.HttpClientConnection;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpInetConnection;
|
||||
import org.apache.http.params.HttpParams;
|
||||
|
||||
/**
|
||||
* A client-side connection that relies on outside logic to connect sockets to the
|
||||
* appropriate hosts. It can be operated directly by an application, or through an
|
||||
* {@link ClientConnectionOperator operator}.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) replaced by {@link HttpClientConnectionManager}.
|
||||
*/
|
||||
@Deprecated
|
||||
public interface OperatedClientConnection extends HttpClientConnection, HttpInetConnection {
|
||||
|
||||
/**
|
||||
* Obtains the target host for this connection.
|
||||
* If the connection is to a proxy but not tunnelled, this is
|
||||
* the proxy. If the connection is tunnelled through a proxy,
|
||||
* this is the target of the tunnel.
|
||||
* <p>
|
||||
* The return value is well-defined only while the connection is open.
|
||||
* It may change even while the connection is open,
|
||||
* because of an {@link #update update}.
|
||||
* </p>
|
||||
*
|
||||
* @return the host to which this connection is opened
|
||||
*/
|
||||
HttpHost getTargetHost();
|
||||
|
||||
/**
|
||||
* Indicates whether this connection is secure.
|
||||
* The return value is well-defined only while the connection is open.
|
||||
* It may change even while the connection is open,
|
||||
* because of an {@link #update update}.
|
||||
*
|
||||
* @return {@code true} if this connection is secure,
|
||||
* {@code false} otherwise
|
||||
*/
|
||||
boolean isSecure();
|
||||
|
||||
/**
|
||||
* Obtains the socket for this connection.
|
||||
* The return value is well-defined only while the connection is open.
|
||||
* It may change even while the connection is open,
|
||||
* because of an {@link #update update}.
|
||||
*
|
||||
* @return the socket for communicating with the
|
||||
* {@link #getTargetHost target host}
|
||||
*/
|
||||
Socket getSocket();
|
||||
|
||||
/**
|
||||
* Signals that this connection is in the process of being open.
|
||||
* <p>
|
||||
* By calling this method, the connection can be re-initialized
|
||||
* with a new Socket instance before {@link #openCompleted} is called.
|
||||
* This enabled the connection to close that socket if
|
||||
* {@link org.apache.http.HttpConnection#shutdown shutdown}
|
||||
* is called before it is fully open. Closing an unconnected socket
|
||||
* will interrupt a thread that is blocked on the connect.
|
||||
* Otherwise, that thread will either time out on the connect,
|
||||
* or it returns successfully and then opens this connection
|
||||
* which was just shut down.
|
||||
* <p>
|
||||
* This method can be called multiple times if the connection
|
||||
* is layered over another protocol. <b>Note:</b> This method
|
||||
* will <i>not</i> close the previously used socket. It is
|
||||
* the caller's responsibility to close that socket if it is
|
||||
* no longer required.
|
||||
* <p>
|
||||
* The caller must invoke {@link #openCompleted} in order to complete
|
||||
* the process.
|
||||
*
|
||||
* @param sock the unconnected socket which is about to
|
||||
* be connected.
|
||||
* @param target the target host of this connection
|
||||
*/
|
||||
void opening(Socket sock, HttpHost target)
|
||||
throws IOException;
|
||||
|
||||
/**
|
||||
* Signals that the connection has been successfully open.
|
||||
* An attempt to call this method on an open connection will cause
|
||||
* an exception.
|
||||
*
|
||||
* @param secure {@code true} if this connection is secure, for
|
||||
* example if an {@code SSLSocket} is used, or
|
||||
* {@code false} if it is not secure
|
||||
* @param params parameters for this connection. The parameters will
|
||||
* be used when creating dependent objects, for example
|
||||
* to determine buffer sizes.
|
||||
*/
|
||||
void openCompleted(boolean secure, HttpParams params)
|
||||
throws IOException;
|
||||
|
||||
/**
|
||||
* Updates this connection.
|
||||
* A connection can be updated only while it is open.
|
||||
* Updates are used for example when a tunnel has been established,
|
||||
* or when a TLS/SSL connection has been layered on top of a plain
|
||||
* socket connection.
|
||||
* <p>
|
||||
* <b>Note:</b> Updating the connection will <i>not</i> close the
|
||||
* previously used socket. It is the caller's responsibility to close
|
||||
* that socket if it is no longer required.
|
||||
* </p>
|
||||
*
|
||||
* @param sock the new socket for communicating with the target host,
|
||||
* or {@code null} to continue using the old socket.
|
||||
* If {@code null} is passed, helper objects that
|
||||
* depend on the socket should be re-used. In that case,
|
||||
* some changes in the parameters will not take effect.
|
||||
* @param target the new target host of this connection
|
||||
* @param secure {@code true} if this connection is now secure,
|
||||
* {@code false} if it is not secure
|
||||
* @param params new parameters for this connection
|
||||
*/
|
||||
void update(Socket sock, HttpHost target,
|
||||
boolean secure, HttpParams params)
|
||||
throws IOException;
|
||||
|
||||
}
|
|
@ -1,59 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn.params;
|
||||
|
||||
import org.apache.http.params.HttpAbstractParamBean;
|
||||
import org.apache.http.params.HttpParams;
|
||||
|
||||
/**
|
||||
* This is a Java Bean class that can be used to wrap an instance of
|
||||
* {@link HttpParams} and manipulate HTTP client connection parameters
|
||||
* using Java Beans conventions.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.1) use custom {@link
|
||||
* org.apache.http.impl.conn.DefaultHttpResponseParser} implementation.
|
||||
*/
|
||||
@Deprecated
|
||||
public class ConnConnectionParamBean extends HttpAbstractParamBean {
|
||||
|
||||
public ConnConnectionParamBean (final HttpParams params) {
|
||||
super(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated (4.2) Use custom {@link
|
||||
* org.apache.http.impl.conn.DefaultHttpResponseParser} implementation
|
||||
*/
|
||||
@Deprecated
|
||||
public void setMaxStatusLineGarbage (final int maxStatusLineGarbage) {
|
||||
params.setIntParameter(ConnConnectionPNames.MAX_STATUS_LINE_GARBAGE, maxStatusLineGarbage);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,63 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn.params;
|
||||
|
||||
import org.apache.http.annotation.NotThreadSafe;
|
||||
import org.apache.http.params.HttpAbstractParamBean;
|
||||
import org.apache.http.params.HttpParams;
|
||||
|
||||
/**
|
||||
* This is a Java Bean class that can be used to wrap an instance of
|
||||
* {@link HttpParams} and manipulate connection manager parameters
|
||||
* using Java Beans conventions.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.1) use configuration methods of the specific connection manager implementation.
|
||||
*/
|
||||
@NotThreadSafe
|
||||
@Deprecated
|
||||
public class ConnManagerParamBean extends HttpAbstractParamBean {
|
||||
|
||||
public ConnManagerParamBean (final HttpParams params) {
|
||||
super(params);
|
||||
}
|
||||
|
||||
public void setTimeout (final long timeout) {
|
||||
params.setLongParameter(ConnManagerPNames.TIMEOUT, timeout);
|
||||
}
|
||||
|
||||
public void setMaxTotalConnections (final int maxConnections) {
|
||||
params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, maxConnections);
|
||||
}
|
||||
|
||||
public void setConnectionsPerRoute(final ConnPerRouteBean connPerRoute) {
|
||||
params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, connPerRoute);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,147 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn.params;
|
||||
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.util.Args;
|
||||
|
||||
/**
|
||||
* An adaptor for manipulating HTTP connection management
|
||||
* parameters in {@link HttpParams}.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @see ConnManagerPNames
|
||||
*
|
||||
* @deprecated (4.1) use configuration methods of the specific connection manager implementation.
|
||||
*/
|
||||
@Deprecated
|
||||
@Immutable
|
||||
public final class ConnManagerParams implements ConnManagerPNames {
|
||||
|
||||
/** The default maximum number of connections allowed overall */
|
||||
public static final int DEFAULT_MAX_TOTAL_CONNECTIONS = 20;
|
||||
|
||||
/**
|
||||
* Returns the timeout in milliseconds used when retrieving a
|
||||
* {@link org.apache.http.conn.ManagedClientConnection} from the
|
||||
* {@link org.apache.http.conn.ClientConnectionManager}.
|
||||
*
|
||||
* @return timeout in milliseconds.
|
||||
*
|
||||
* @deprecated (4.1) use {@link
|
||||
* org.apache.http.params.HttpConnectionParams#getConnectionTimeout(HttpParams)}
|
||||
*/
|
||||
@Deprecated
|
||||
public static long getTimeout(final HttpParams params) {
|
||||
Args.notNull(params, "HTTP parameters");
|
||||
return params.getLongParameter(TIMEOUT, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the timeout in milliseconds used when retrieving a
|
||||
* {@link org.apache.http.conn.ManagedClientConnection} from the
|
||||
* {@link org.apache.http.conn.ClientConnectionManager}.
|
||||
*
|
||||
* @param timeout the timeout in milliseconds
|
||||
*
|
||||
* @deprecated (4.1) use {@link
|
||||
* org.apache.http.params.HttpConnectionParams#setConnectionTimeout(HttpParams, int)}
|
||||
*/
|
||||
@Deprecated
|
||||
public static void setTimeout(final HttpParams params, final long timeout) {
|
||||
Args.notNull(params, "HTTP parameters");
|
||||
params.setLongParameter(TIMEOUT, timeout);
|
||||
}
|
||||
|
||||
/** The default maximum number of connections allowed per host */
|
||||
private static final ConnPerRoute DEFAULT_CONN_PER_ROUTE = new ConnPerRoute() {
|
||||
|
||||
public int getMaxForRoute(final HttpRoute route) {
|
||||
return ConnPerRouteBean.DEFAULT_MAX_CONNECTIONS_PER_ROUTE;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets lookup interface for maximum number of connections allowed per route.
|
||||
*
|
||||
* @param params HTTP parameters
|
||||
* @param connPerRoute lookup interface for maximum number of connections allowed
|
||||
* per route
|
||||
*/
|
||||
public static void setMaxConnectionsPerRoute(final HttpParams params,
|
||||
final ConnPerRoute connPerRoute) {
|
||||
Args.notNull(params, "HTTP parameters");
|
||||
params.setParameter(MAX_CONNECTIONS_PER_ROUTE, connPerRoute);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns lookup interface for maximum number of connections allowed per route.
|
||||
*
|
||||
* @param params HTTP parameters
|
||||
*
|
||||
* @return lookup interface for maximum number of connections allowed per route.
|
||||
*/
|
||||
public static ConnPerRoute getMaxConnectionsPerRoute(final HttpParams params) {
|
||||
Args.notNull(params, "HTTP parameters");
|
||||
ConnPerRoute connPerRoute = (ConnPerRoute) params.getParameter(MAX_CONNECTIONS_PER_ROUTE);
|
||||
if (connPerRoute == null) {
|
||||
connPerRoute = DEFAULT_CONN_PER_ROUTE;
|
||||
}
|
||||
return connPerRoute;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the maximum number of connections allowed.
|
||||
*
|
||||
* @param params HTTP parameters
|
||||
* @param maxTotalConnections The maximum number of connections allowed.
|
||||
*/
|
||||
public static void setMaxTotalConnections(
|
||||
final HttpParams params,
|
||||
final int maxTotalConnections) {
|
||||
Args.notNull(params, "HTTP parameters");
|
||||
params.setIntParameter(MAX_TOTAL_CONNECTIONS, maxTotalConnections);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the maximum number of connections allowed.
|
||||
*
|
||||
* @param params HTTP parameters
|
||||
*
|
||||
* @return The maximum number of connections allowed.
|
||||
*/
|
||||
public static int getMaxTotalConnections(
|
||||
final HttpParams params) {
|
||||
Args.notNull(params, "HTTP parameters");
|
||||
return params.getIntParameter(MAX_TOTAL_CONNECTIONS, DEFAULT_MAX_TOTAL_CONNECTIONS);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,46 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn.params;
|
||||
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
|
||||
/**
|
||||
* This interface is intended for looking up maximum number of connections
|
||||
* allowed for a given route. This class can be used by pooling
|
||||
* {@link org.apache.http.conn.ClientConnectionManager connection managers} for
|
||||
* a fine-grained control of connections on a per route basis.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) no longer used.
|
||||
*/
|
||||
@Deprecated
|
||||
public interface ConnPerRoute {
|
||||
|
||||
int getMaxForRoute(HttpRoute route);
|
||||
|
||||
}
|
|
@ -1,112 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn.params;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.apache.http.annotation.ThreadSafe;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.util.Args;
|
||||
|
||||
/**
|
||||
* This class maintains a map of HTTP routes to maximum number of connections allowed
|
||||
* for those routes. This class can be used by pooling
|
||||
* {@link org.apache.http.conn.ClientConnectionManager connection managers} for
|
||||
* a fine-grained control of connections on a per route basis.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.2) use {@link org.apache.http.pool.ConnPoolControl}
|
||||
*/
|
||||
@Deprecated
|
||||
@ThreadSafe
|
||||
public final class ConnPerRouteBean implements ConnPerRoute {
|
||||
|
||||
/** The default maximum number of connections allowed per host */
|
||||
public static final int DEFAULT_MAX_CONNECTIONS_PER_ROUTE = 2; // Per RFC 2616 sec 8.1.4
|
||||
|
||||
private final ConcurrentHashMap<HttpRoute, Integer> maxPerHostMap;
|
||||
|
||||
private volatile int defaultMax;
|
||||
|
||||
public ConnPerRouteBean(final int defaultMax) {
|
||||
super();
|
||||
this.maxPerHostMap = new ConcurrentHashMap<HttpRoute, Integer>();
|
||||
setDefaultMaxPerRoute(defaultMax);
|
||||
}
|
||||
|
||||
public ConnPerRouteBean() {
|
||||
this(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
|
||||
}
|
||||
|
||||
public int getDefaultMax() {
|
||||
return this.defaultMax;
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public int getDefaultMaxPerRoute() {
|
||||
return this.defaultMax;
|
||||
}
|
||||
|
||||
public void setDefaultMaxPerRoute(final int max) {
|
||||
Args.positive(max, "Default max per route");
|
||||
this.defaultMax = max;
|
||||
}
|
||||
|
||||
public void setMaxForRoute(final HttpRoute route, final int max) {
|
||||
Args.notNull(route, "HTTP route");
|
||||
Args.positive(max, "Max per route");
|
||||
this.maxPerHostMap.put(route, Integer.valueOf(max));
|
||||
}
|
||||
|
||||
public int getMaxForRoute(final HttpRoute route) {
|
||||
Args.notNull(route, "HTTP route");
|
||||
final Integer max = this.maxPerHostMap.get(route);
|
||||
if (max != null) {
|
||||
return max.intValue();
|
||||
} else {
|
||||
return this.defaultMax;
|
||||
}
|
||||
}
|
||||
|
||||
public void setMaxForRoutes(final Map<HttpRoute, Integer> map) {
|
||||
if (map == null) {
|
||||
return;
|
||||
}
|
||||
this.maxPerHostMap.clear();
|
||||
this.maxPerHostMap.putAll(map);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.maxPerHostMap.toString();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,70 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn.params;
|
||||
|
||||
import java.net.InetAddress;
|
||||
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.annotation.NotThreadSafe;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.params.HttpAbstractParamBean;
|
||||
import org.apache.http.params.HttpParams;
|
||||
|
||||
/**
|
||||
* This is a Java Bean class that can be used to wrap an instance of
|
||||
* {@link HttpParams} and manipulate connection routing parameters
|
||||
* using Java Beans conventions.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) use {@link org.apache.http.client.config.RequestConfig}.
|
||||
*/
|
||||
@Deprecated
|
||||
@NotThreadSafe
|
||||
public class ConnRouteParamBean extends HttpAbstractParamBean {
|
||||
|
||||
public ConnRouteParamBean (final HttpParams params) {
|
||||
super(params);
|
||||
}
|
||||
|
||||
/** @see ConnRoutePNames#DEFAULT_PROXY */
|
||||
public void setDefaultProxy (final HttpHost defaultProxy) {
|
||||
params.setParameter(ConnRoutePNames.DEFAULT_PROXY, defaultProxy);
|
||||
}
|
||||
|
||||
/** @see ConnRoutePNames#LOCAL_ADDRESS */
|
||||
public void setLocalAddress (final InetAddress address) {
|
||||
params.setParameter(ConnRoutePNames.LOCAL_ADDRESS, address);
|
||||
}
|
||||
|
||||
/** @see ConnRoutePNames#FORCED_ROUTE */
|
||||
public void setForcedRoute (final HttpRoute route) {
|
||||
params.setParameter(ConnRoutePNames.FORCED_ROUTE, route);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,178 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn.params;
|
||||
|
||||
import java.net.InetAddress;
|
||||
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.util.Args;
|
||||
|
||||
/**
|
||||
* An adaptor for manipulating HTTP routing parameters
|
||||
* in {@link HttpParams}.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) use {@link org.apache.http.client.config.RequestConfig}.
|
||||
*/
|
||||
@Deprecated
|
||||
@Immutable
|
||||
public class ConnRouteParams implements ConnRoutePNames {
|
||||
|
||||
/**
|
||||
* A special value indicating "no host".
|
||||
* This relies on a nonsense scheme name to avoid conflicts
|
||||
* with actual hosts. Note that this is a <i>valid</i> host.
|
||||
*/
|
||||
public static final HttpHost NO_HOST =
|
||||
new HttpHost("127.0.0.255", 0, "no-host"); // Immutable
|
||||
|
||||
/**
|
||||
* A special value indicating "no route".
|
||||
* This is a route with {@link #NO_HOST} as the target.
|
||||
*/
|
||||
public static final HttpRoute NO_ROUTE = new HttpRoute(NO_HOST); // Immutable
|
||||
|
||||
/** Disabled default constructor. */
|
||||
private ConnRouteParams() {
|
||||
// no body
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains the {@link ConnRoutePNames#DEFAULT_PROXY DEFAULT_PROXY}
|
||||
* parameter value.
|
||||
* {@link #NO_HOST} will be mapped to {@code null},
|
||||
* to allow unsetting in a hierarchy.
|
||||
*
|
||||
* @param params the parameters in which to look up
|
||||
*
|
||||
* @return the default proxy set in the argument parameters, or
|
||||
* {@code null} if not set
|
||||
*/
|
||||
public static HttpHost getDefaultProxy(final HttpParams params) {
|
||||
Args.notNull(params, "Parameters");
|
||||
HttpHost proxy = (HttpHost)
|
||||
params.getParameter(DEFAULT_PROXY);
|
||||
if ((proxy != null) && NO_HOST.equals(proxy)) {
|
||||
// value is explicitly unset
|
||||
proxy = null;
|
||||
}
|
||||
return proxy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link ConnRoutePNames#DEFAULT_PROXY DEFAULT_PROXY}
|
||||
* parameter value.
|
||||
*
|
||||
* @param params the parameters in which to set the value
|
||||
* @param proxy the value to set, may be {@code null}.
|
||||
* Note that {@link #NO_HOST} will be mapped to
|
||||
* {@code null} by {@link #getDefaultProxy},
|
||||
* to allow for explicit unsetting in hierarchies.
|
||||
*/
|
||||
public static void setDefaultProxy(final HttpParams params,
|
||||
final HttpHost proxy) {
|
||||
Args.notNull(params, "Parameters");
|
||||
params.setParameter(DEFAULT_PROXY, proxy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains the {@link ConnRoutePNames#FORCED_ROUTE FORCED_ROUTE}
|
||||
* parameter value.
|
||||
* {@link #NO_ROUTE} will be mapped to {@code null},
|
||||
* to allow unsetting in a hierarchy.
|
||||
*
|
||||
* @param params the parameters in which to look up
|
||||
*
|
||||
* @return the forced route set in the argument parameters, or
|
||||
* {@code null} if not set
|
||||
*/
|
||||
public static HttpRoute getForcedRoute(final HttpParams params) {
|
||||
Args.notNull(params, "Parameters");
|
||||
HttpRoute route = (HttpRoute)
|
||||
params.getParameter(FORCED_ROUTE);
|
||||
if ((route != null) && NO_ROUTE.equals(route)) {
|
||||
// value is explicitly unset
|
||||
route = null;
|
||||
}
|
||||
return route;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link ConnRoutePNames#FORCED_ROUTE FORCED_ROUTE}
|
||||
* parameter value.
|
||||
*
|
||||
* @param params the parameters in which to set the value
|
||||
* @param route the value to set, may be {@code null}.
|
||||
* Note that {@link #NO_ROUTE} will be mapped to
|
||||
* {@code null} by {@link #getForcedRoute},
|
||||
* to allow for explicit unsetting in hierarchies.
|
||||
*/
|
||||
public static void setForcedRoute(final HttpParams params,
|
||||
final HttpRoute route) {
|
||||
Args.notNull(params, "Parameters");
|
||||
params.setParameter(FORCED_ROUTE, route);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains the {@link ConnRoutePNames#LOCAL_ADDRESS LOCAL_ADDRESS}
|
||||
* parameter value.
|
||||
* There is no special value that would automatically be mapped to
|
||||
* {@code null}. You can use the wildcard address (0.0.0.0 for IPv4,
|
||||
* :: for IPv6) to override a specific local address in a hierarchy.
|
||||
*
|
||||
* @param params the parameters in which to look up
|
||||
*
|
||||
* @return the local address set in the argument parameters, or
|
||||
* {@code null} if not set
|
||||
*/
|
||||
public static InetAddress getLocalAddress(final HttpParams params) {
|
||||
Args.notNull(params, "Parameters");
|
||||
final InetAddress local = (InetAddress)
|
||||
params.getParameter(LOCAL_ADDRESS);
|
||||
// no explicit unsetting
|
||||
return local;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link ConnRoutePNames#LOCAL_ADDRESS LOCAL_ADDRESS}
|
||||
* parameter value.
|
||||
*
|
||||
* @param params the parameters in which to set the value
|
||||
* @param local the value to set, may be {@code null}
|
||||
*/
|
||||
public static void setLocalAddress(final HttpParams params,
|
||||
final InetAddress local) {
|
||||
Args.notNull(params, "Parameters");
|
||||
params.setParameter(LOCAL_ADDRESS, local);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn.scheme;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
|
||||
/**
|
||||
* Hostname to IP address resolver.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.1) Do not use
|
||||
*/
|
||||
@Deprecated
|
||||
public interface HostNameResolver {
|
||||
|
||||
/**
|
||||
* Resolves given hostname to its IP address
|
||||
*
|
||||
* @param hostname the hostname.
|
||||
* @return IP address.
|
||||
* @throws IOException
|
||||
*/
|
||||
InetAddress resolve (String hostname) throws IOException;
|
||||
|
||||
}
|
|
@ -1,160 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn.scheme;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.conn.ConnectTimeoutException;
|
||||
import org.apache.http.params.HttpConnectionParams;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.util.Args;
|
||||
|
||||
/**
|
||||
* The default class for creating plain (unencrypted) sockets.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) use {@link org.apache.http.conn.socket.PlainConnectionSocketFactory}
|
||||
*/
|
||||
@Immutable
|
||||
@Deprecated
|
||||
public class PlainSocketFactory implements SocketFactory, SchemeSocketFactory {
|
||||
|
||||
private final HostNameResolver nameResolver;
|
||||
|
||||
/**
|
||||
* Gets the default factory.
|
||||
*
|
||||
* @return the default factory
|
||||
*/
|
||||
public static PlainSocketFactory getSocketFactory() {
|
||||
return new PlainSocketFactory();
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated (4.1) use {@link org.apache.http.conn.DnsResolver}
|
||||
*/
|
||||
@Deprecated
|
||||
public PlainSocketFactory(final HostNameResolver nameResolver) {
|
||||
super();
|
||||
this.nameResolver = nameResolver;
|
||||
}
|
||||
|
||||
public PlainSocketFactory() {
|
||||
super();
|
||||
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
|
||||
* using default constructor.
|
||||
*
|
||||
* @since 4.1
|
||||
*/
|
||||
public Socket createSocket(final HttpParams params) {
|
||||
return new Socket();
|
||||
}
|
||||
|
||||
public Socket createSocket() {
|
||||
return new Socket();
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public Socket connectSocket(
|
||||
final Socket socket,
|
||||
final InetSocketAddress remoteAddress,
|
||||
final InetSocketAddress localAddress,
|
||||
final HttpParams params) throws IOException, ConnectTimeoutException {
|
||||
Args.notNull(remoteAddress, "Remote address");
|
||||
Args.notNull(params, "HTTP parameters");
|
||||
Socket sock = socket;
|
||||
if (sock == null) {
|
||||
sock = createSocket();
|
||||
}
|
||||
if (localAddress != null) {
|
||||
sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
|
||||
sock.bind(localAddress);
|
||||
}
|
||||
final int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
|
||||
final int soTimeout = HttpConnectionParams.getSoTimeout(params);
|
||||
|
||||
try {
|
||||
sock.setSoTimeout(soTimeout);
|
||||
sock.connect(remoteAddress, connTimeout);
|
||||
} catch (final SocketTimeoutException ex) {
|
||||
throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
|
||||
}
|
||||
return sock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a socket connection is secure.
|
||||
* This factory creates plain socket connections
|
||||
* which are not considered secure.
|
||||
*
|
||||
* @param sock the connected socket
|
||||
*
|
||||
* @return {@code false}
|
||||
*/
|
||||
public final boolean isSecure(final Socket sock) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated (4.1) Use {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams)}
|
||||
*/
|
||||
@Deprecated
|
||||
public Socket connectSocket(
|
||||
final Socket socket,
|
||||
final String host, final int port,
|
||||
final InetAddress localAddress, final int localPort,
|
||||
final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
|
||||
InetSocketAddress local = null;
|
||||
if (localAddress != null || localPort > 0) {
|
||||
local = new InetSocketAddress(localAddress, localPort > 0 ? localPort : 0);
|
||||
}
|
||||
final InetAddress remoteAddress;
|
||||
if (this.nameResolver != null) {
|
||||
remoteAddress = this.nameResolver.resolve(host);
|
||||
} else {
|
||||
remoteAddress = InetAddress.getByName(host);
|
||||
}
|
||||
final InetSocketAddress remote = new InetSocketAddress(remoteAddress, port);
|
||||
return connectSocket(socket, remote, local, params);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,66 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn.ssl;
|
||||
|
||||
import org.apache.http.util.Args;
|
||||
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Private key details.
|
||||
*
|
||||
* @since 4.3
|
||||
*
|
||||
* @deprecated (4.4) use {@link org.apache.http.ssl.PrivateKeyDetails}.
|
||||
*/
|
||||
@Deprecated
|
||||
public final class PrivateKeyDetails {
|
||||
|
||||
private final String type;
|
||||
private final X509Certificate[] certChain;
|
||||
|
||||
public PrivateKeyDetails(final String type, final X509Certificate[] certChain) {
|
||||
super();
|
||||
this.type = Args.notNull(type, "Private key type");
|
||||
this.certChain = certChain;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public X509Certificate[] getCertChain() {
|
||||
return certChain;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return type + ':' + Arrays.toString(certChain);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,47 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn.ssl;
|
||||
|
||||
import java.net.Socket;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A strategy allowing for a choice of an alias during SSL authentication.
|
||||
*
|
||||
* @since 4.3
|
||||
*
|
||||
* @deprecated (4.4) use {@link org.apache.http.ssl.PrivateKeyStrategy}.
|
||||
*/
|
||||
@Deprecated
|
||||
public interface PrivateKeyStrategy {
|
||||
|
||||
/**
|
||||
* Determines what key material to use for SSL authentication.
|
||||
*/
|
||||
String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket);
|
||||
|
||||
}
|
|
@ -1,271 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.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.LinkedHashSet;
|
||||
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 org.apache.http.annotation.NotThreadSafe;
|
||||
|
||||
/**
|
||||
* Builder for {@link SSLContext} instances.
|
||||
*
|
||||
* @since 4.3
|
||||
*
|
||||
* @deprecated (4.4) use {@link org.apache.http.ssl.SSLContextBuilder}.
|
||||
*/
|
||||
@NotThreadSafe
|
||||
@Deprecated
|
||||
public class SSLContextBuilder {
|
||||
|
||||
static final String TLS = "TLS";
|
||||
static final String SSL = "SSL";
|
||||
|
||||
private String protocol;
|
||||
private Set<KeyManager> keymanagers;
|
||||
private Set<TrustManager> trustmanagers;
|
||||
private SecureRandom secureRandom;
|
||||
|
||||
public SSLContextBuilder() {
|
||||
super();
|
||||
this.keymanagers = new LinkedHashSet<KeyManager>();
|
||||
this.trustmanagers = new LinkedHashSet<TrustManager>();
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkClientTrusted(
|
||||
final X509Certificate[] chain, final String authType) throws CertificateException {
|
||||
this.trustManager.checkClientTrusted(chain, authType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkServerTrusted(
|
||||
final X509Certificate[] chain, final String authType) throws CertificateException {
|
||||
if (!this.trustStrategy.isTrusted(chain, authType)) {
|
||||
this.trustManager.checkServerTrusted(chain, authType);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getClientAliases(
|
||||
final String keyType, final Principal[] issuers) {
|
||||
return this.keyManager.getClientAliases(keyType, issuers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chooseClientAlias(
|
||||
final String[] keyTypes, final Principal[] issuers, final Socket socket) {
|
||||
final Map<String, PrivateKeyDetails> validAliases = new HashMap<String, PrivateKeyDetails>();
|
||||
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);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getServerAliases(
|
||||
final String keyType, final Principal[] issuers) {
|
||||
return this.keyManager.getServerAliases(keyType, issuers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chooseServerAlias(
|
||||
final String keyType, final Principal[] issuers, final Socket socket) {
|
||||
final Map<String, PrivateKeyDetails> validAliases = new HashMap<String, PrivateKeyDetails>();
|
||||
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);
|
||||
}
|
||||
|
||||
@Override
|
||||
public X509Certificate[] getCertificateChain(final String alias) {
|
||||
return this.keyManager.getCertificateChain(alias);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PrivateKey getPrivateKey(final String alias) {
|
||||
return this.keyManager.getPrivateKey(alias);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -1,93 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.conn.ssl;
|
||||
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
|
||||
import org.apache.http.annotation.Immutable;
|
||||
|
||||
/**
|
||||
* {@link SSLContext} factory methods.
|
||||
*
|
||||
* @since 4.3
|
||||
*
|
||||
* @deprecated (4.4) use {@link org.apache.http.ssl.SSLContexts}.
|
||||
*/
|
||||
@Immutable
|
||||
@Deprecated
|
||||
public class SSLContexts {
|
||||
|
||||
/**
|
||||
* Creates default factory based on the standard JSSE trust material
|
||||
* ({@code 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 {@code SSLContext.getInstance("Default")}.
|
||||
* Please note that {@code Default} algorithm is supported as of Java 6.
|
||||
* This method will fall back onto {@link #createDefault()} when
|
||||
* {@code Default} algorithm is not available.
|
||||
*
|
||||
* @return default system SSL context
|
||||
*/
|
||||
public static SSLContext createSystemDefault() throws SSLInitializationException {
|
||||
try {
|
||||
return SSLContext.getDefault();
|
||||
} catch (final NoSuchAlgorithmException ex) {
|
||||
return createDefault();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates custom SSL context.
|
||||
*
|
||||
* @return default system SSL context
|
||||
*/
|
||||
public static SSLContextBuilder custom() {
|
||||
return new SSLContextBuilder();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,578 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.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 org.apache.http.HttpHost;
|
||||
import org.apache.http.annotation.ThreadSafe;
|
||||
import org.apache.http.conn.ConnectTimeoutException;
|
||||
import org.apache.http.conn.HttpInetSocketAddress;
|
||||
import org.apache.http.conn.scheme.HostNameResolver;
|
||||
import org.apache.http.conn.scheme.LayeredSchemeSocketFactory;
|
||||
import org.apache.http.conn.scheme.LayeredSocketFactory;
|
||||
import org.apache.http.conn.scheme.SchemeLayeredSocketFactory;
|
||||
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
|
||||
import org.apache.http.params.HttpConnectionParams;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.util.Args;
|
||||
import org.apache.http.util.Asserts;
|
||||
import org.apache.http.util.TextUtils;
|
||||
|
||||
/**
|
||||
* Layered socket factory for TLS/SSL connections.
|
||||
* <p>
|
||||
* 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.
|
||||
* </p>
|
||||
* <p>
|
||||
* 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.
|
||||
* </p>
|
||||
* <p>
|
||||
* Use JDK keytool utility to import a trusted certificate and generate a trust-store file:
|
||||
* </p>
|
||||
* <pre>keytool -import -alias "my server cert" -file server.crt -keystore my.truststore
|
||||
* </pre>
|
||||
* <p>
|
||||
* 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.
|
||||
* </p>
|
||||
* <p>
|
||||
* 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.
|
||||
* </p>
|
||||
* <p>
|
||||
* Use the following sequence of actions to generate a key-store file
|
||||
* </p>
|
||||
* <ul>
|
||||
* <li>
|
||||
* <p>
|
||||
* Use JDK keytool utility to generate a new key
|
||||
* </p>
|
||||
* <pre>keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore</pre>
|
||||
* <p>
|
||||
* For simplicity use the same password for the key as that of the key-store
|
||||
* </p>
|
||||
* </li>
|
||||
* <li>
|
||||
* <p>
|
||||
* Issue a certificate signing request (CSR)
|
||||
* </p>
|
||||
* <pre>keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore</pre>
|
||||
* </li>
|
||||
* <li>
|
||||
* <p>
|
||||
* 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.
|
||||
* </p>
|
||||
* </li>
|
||||
* <li>
|
||||
* <p>
|
||||
* Import the trusted CA root certificate
|
||||
* </p>
|
||||
* <pre>keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore</pre>
|
||||
* </li>
|
||||
* <li>
|
||||
* <p>
|
||||
* Import the PKCS#7 file containg the complete certificate chain
|
||||
* </p>
|
||||
* <pre>keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore</pre>
|
||||
* </li>
|
||||
* <li>
|
||||
* <p>
|
||||
* Verify the content the resultant keystore file
|
||||
* </p>
|
||||
* <pre>keytool -list -v -keystore my.keystore</pre>
|
||||
* </li>
|
||||
* </ul>
|
||||
*
|
||||
* @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 ({@code 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
|
||||
* <a href="http://docs.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html">
|
||||
* "JavaTM Secure Socket Extension (JSSE) Reference Guide for the JavaTM 2 Platform
|
||||
* Standard Edition 5</a>
|
||||
*
|
||||
* @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.
|
||||
* <p>
|
||||
* Derived classes may override this method to perform
|
||||
* runtime checks, for example based on the cypher suite.
|
||||
* </p>
|
||||
*
|
||||
* @param sock the connected socket
|
||||
*
|
||||
* @return {@code 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[])}.
|
||||
* @throws IOException (only if overridden)
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,62 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.cookie.params;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.apache.http.annotation.NotThreadSafe;
|
||||
import org.apache.http.params.HttpAbstractParamBean;
|
||||
import org.apache.http.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
|
||||
* org.apache.http.cookie.CookieSpecProvider}s.
|
||||
*/
|
||||
@Deprecated
|
||||
@NotThreadSafe
|
||||
public class CookieSpecParamBean extends HttpAbstractParamBean {
|
||||
|
||||
public CookieSpecParamBean (final HttpParams params) {
|
||||
super(params);
|
||||
}
|
||||
|
||||
public void setDatePatterns (final Collection <String> patterns) {
|
||||
params.setParameter(CookieSpecPNames.DATE_PATTERNS, patterns);
|
||||
}
|
||||
|
||||
public void setSingleHeader (final boolean singleHeader) {
|
||||
params.setBooleanParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, singleHeader);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,209 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.auth;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.auth.AuthenticationException;
|
||||
import org.apache.http.auth.Credentials;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.util.Args;
|
||||
import org.ietf.jgss.GSSException;
|
||||
import org.ietf.jgss.Oid;
|
||||
|
||||
/**
|
||||
* SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) authentication
|
||||
* scheme.
|
||||
*
|
||||
* @since 4.1
|
||||
*
|
||||
* @deprecated (4.2) use {@link SPNegoScheme} or {@link KerberosScheme}.
|
||||
*/
|
||||
@Deprecated
|
||||
public class NegotiateScheme extends GGSSchemeBase {
|
||||
|
||||
private final Log log = LogFactory.getLog(getClass());
|
||||
|
||||
private static final String SPNEGO_OID = "1.3.6.1.5.5.2";
|
||||
private static final String KERBEROS_OID = "1.2.840.113554.1.2.2";
|
||||
|
||||
private final SpnegoTokenGenerator spengoGenerator;
|
||||
|
||||
/**
|
||||
* Default constructor for the Negotiate authentication scheme.
|
||||
*
|
||||
*/
|
||||
public NegotiateScheme(final SpnegoTokenGenerator spengoGenerator, final boolean stripPort) {
|
||||
super(stripPort);
|
||||
this.spengoGenerator = spengoGenerator;
|
||||
}
|
||||
|
||||
public NegotiateScheme(final SpnegoTokenGenerator spengoGenerator) {
|
||||
this(spengoGenerator, false);
|
||||
}
|
||||
|
||||
public NegotiateScheme() {
|
||||
this(null, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns textual designation of the Negotiate authentication scheme.
|
||||
*
|
||||
* @return {@code Negotiate}
|
||||
*/
|
||||
public String getSchemeName() {
|
||||
return "Negotiate";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Header authenticate(
|
||||
final Credentials credentials,
|
||||
final HttpRequest request) throws AuthenticationException {
|
||||
return authenticate(credentials, request, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces Negotiate authorization Header based on token created by
|
||||
* processChallenge.
|
||||
*
|
||||
* @param credentials Never used be the Negotiate scheme but must be provided to
|
||||
* satisfy common-httpclient API. Credentials from JAAS will be used instead.
|
||||
* @param request The request being authenticated
|
||||
*
|
||||
* @throws AuthenticationException if authorisation string cannot
|
||||
* be generated due to an authentication failure
|
||||
*
|
||||
* @return an Negotiate authorisation Header
|
||||
*/
|
||||
@Override
|
||||
public Header authenticate(
|
||||
final Credentials credentials,
|
||||
final HttpRequest request,
|
||||
final HttpContext context) throws AuthenticationException {
|
||||
return super.authenticate(credentials, request, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected byte[] generateToken(final byte[] input, final String authServer) throws GSSException {
|
||||
return super.generateToken(input, authServer);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected byte[] generateToken(final byte[] input, final String authServer, final Credentials credentials) throws GSSException {
|
||||
/* Using the SPNEGO OID is the correct method.
|
||||
* Kerberos v5 works for IIS but not JBoss. Unwrapping
|
||||
* the initial token when using SPNEGO OID looks like what is
|
||||
* described here...
|
||||
*
|
||||
* http://msdn.microsoft.com/en-us/library/ms995330.aspx
|
||||
*
|
||||
* Another helpful URL...
|
||||
*
|
||||
* http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/tsec_SPNEGO_token.html
|
||||
*
|
||||
* Unfortunately SPNEGO is JRE >=1.6.
|
||||
*/
|
||||
|
||||
/** Try SPNEGO by default, fall back to Kerberos later if error */
|
||||
Oid negotiationOid = new Oid(SPNEGO_OID);
|
||||
|
||||
byte[] token = input;
|
||||
boolean tryKerberos = false;
|
||||
try {
|
||||
token = generateGSSToken(token, negotiationOid, authServer, credentials);
|
||||
} catch (final GSSException ex){
|
||||
// BAD MECH means we are likely to be using 1.5, fall back to Kerberos MECH.
|
||||
// Rethrow any other exception.
|
||||
if (ex.getMajor() == GSSException.BAD_MECH ){
|
||||
log.debug("GSSException BAD_MECH, retry with Kerberos MECH");
|
||||
tryKerberos = true;
|
||||
} else {
|
||||
throw ex;
|
||||
}
|
||||
|
||||
}
|
||||
if (tryKerberos){
|
||||
/* Kerberos v5 GSS-API mechanism defined in RFC 1964.*/
|
||||
log.debug("Using Kerberos MECH " + KERBEROS_OID);
|
||||
negotiationOid = new Oid(KERBEROS_OID);
|
||||
token = generateGSSToken(token, negotiationOid, authServer, credentials);
|
||||
|
||||
/*
|
||||
* IIS accepts Kerberos and SPNEGO tokens. Some other servers Jboss, Glassfish?
|
||||
* seem to only accept SPNEGO. Below wraps Kerberos into SPNEGO token.
|
||||
*/
|
||||
if (token != null && spengoGenerator != null) {
|
||||
try {
|
||||
token = spengoGenerator.generateSpnegoDERObject(token);
|
||||
} catch (final IOException ex) {
|
||||
log.error(ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the authentication parameter with the given name, if available.
|
||||
*
|
||||
* <p>There are no valid parameters for Negotiate authentication so this
|
||||
* method always returns {@code null}.</p>
|
||||
*
|
||||
* @param name The name of the parameter to be returned
|
||||
*
|
||||
* @return the parameter with the given name
|
||||
*/
|
||||
public String getParameter(final String name) {
|
||||
Args.notNull(name, "Parameter name");
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The concept of an authentication realm is not supported by the Negotiate
|
||||
* authentication scheme. Always returns {@code null}.
|
||||
*
|
||||
* @return {@code null}
|
||||
*/
|
||||
public String getRealm() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns {@code true}.
|
||||
* Negotiate authentication scheme is connection based.
|
||||
*
|
||||
* @return {@code true}.
|
||||
*/
|
||||
public boolean isConnectionBased() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,73 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.auth;
|
||||
|
||||
import org.apache.http.auth.AuthScheme;
|
||||
import org.apache.http.auth.AuthSchemeFactory;
|
||||
import org.apache.http.params.HttpParams;
|
||||
|
||||
/**
|
||||
* SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) authentication
|
||||
* scheme factory.
|
||||
*
|
||||
* @since 4.1
|
||||
*
|
||||
* @deprecated (4.2) use {@link SPNegoSchemeFactory} or {@link KerberosSchemeFactory}.
|
||||
*/
|
||||
@Deprecated
|
||||
public class NegotiateSchemeFactory implements AuthSchemeFactory {
|
||||
|
||||
private final SpnegoTokenGenerator spengoGenerator;
|
||||
private final boolean stripPort;
|
||||
|
||||
public NegotiateSchemeFactory(final SpnegoTokenGenerator spengoGenerator, final boolean stripPort) {
|
||||
super();
|
||||
this.spengoGenerator = spengoGenerator;
|
||||
this.stripPort = stripPort;
|
||||
}
|
||||
|
||||
public NegotiateSchemeFactory(final SpnegoTokenGenerator spengoGenerator) {
|
||||
this(spengoGenerator, false);
|
||||
}
|
||||
|
||||
public NegotiateSchemeFactory() {
|
||||
this(null, false);
|
||||
}
|
||||
|
||||
public AuthScheme newInstance(final HttpParams params) {
|
||||
return new NegotiateScheme(this.spengoGenerator, this.stripPort);
|
||||
}
|
||||
|
||||
public boolean isStripPort() {
|
||||
return stripPort;
|
||||
}
|
||||
|
||||
public SpnegoTokenGenerator getSpengoGenerator() {
|
||||
return spengoGenerator;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,47 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.auth;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Abstract SPNEGO token generator. Implementations should take an Kerberos ticket and transform
|
||||
* into a SPNEGO token.
|
||||
* <p>
|
||||
* 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;
|
||||
|
||||
}
|
|
@ -1,189 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.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 org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.FormattedHeader;
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.auth.AuthScheme;
|
||||
import org.apache.http.auth.AuthSchemeRegistry;
|
||||
import org.apache.http.auth.AuthenticationException;
|
||||
import org.apache.http.auth.MalformedChallengeException;
|
||||
import org.apache.http.client.AuthenticationHandler;
|
||||
import org.apache.http.client.params.AuthPolicy;
|
||||
import org.apache.http.client.protocol.ClientContext;
|
||||
import org.apache.http.protocol.HTTP;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.util.Asserts;
|
||||
import org.apache.http.util.CharArrayBuffer;
|
||||
|
||||
/**
|
||||
* Base class for {@link AuthenticationHandler} implementations.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.2) use {@link org.apache.http.client.AuthenticationStrategy}
|
||||
*/
|
||||
@Deprecated
|
||||
@Immutable
|
||||
public abstract class AbstractAuthenticationHandler implements AuthenticationHandler {
|
||||
|
||||
private final Log log = LogFactory.getLog(getClass());
|
||||
|
||||
private static final List<String> DEFAULT_SCHEME_PRIORITY =
|
||||
Collections.unmodifiableList(Arrays.asList(new String[] {
|
||||
AuthPolicy.SPNEGO,
|
||||
AuthPolicy.NTLM,
|
||||
AuthPolicy.DIGEST,
|
||||
AuthPolicy.BASIC
|
||||
}));
|
||||
|
||||
public AbstractAuthenticationHandler() {
|
||||
super();
|
||||
}
|
||||
|
||||
protected Map<String, Header> parseChallenges(
|
||||
final Header[] headers) throws MalformedChallengeException {
|
||||
|
||||
final Map<String, Header> map = new HashMap<String, Header>(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.ROOT), header);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns default list of auth scheme names in their order of preference.
|
||||
*
|
||||
* @return list of auth scheme names
|
||||
*/
|
||||
protected List<String> 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<String> getAuthPreferences(
|
||||
final HttpResponse response,
|
||||
final HttpContext context) {
|
||||
return getAuthPreferences();
|
||||
}
|
||||
|
||||
public AuthScheme selectScheme(
|
||||
final Map<String, Header> challenges,
|
||||
final HttpResponse response,
|
||||
final HttpContext context) throws AuthenticationException {
|
||||
|
||||
final AuthSchemeRegistry registry = (AuthSchemeRegistry) context.getAttribute(
|
||||
ClientContext.AUTHSCHEME_REGISTRY);
|
||||
Asserts.notNull(registry, "AuthScheme registry");
|
||||
Collection<String> 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;
|
||||
}
|
||||
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -1,172 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.client;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.auth.AuthOption;
|
||||
import org.apache.http.auth.AuthScheme;
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.AuthenticationException;
|
||||
import org.apache.http.auth.Credentials;
|
||||
import org.apache.http.auth.MalformedChallengeException;
|
||||
import org.apache.http.client.AuthCache;
|
||||
import org.apache.http.client.AuthenticationHandler;
|
||||
import org.apache.http.client.AuthenticationStrategy;
|
||||
import org.apache.http.client.CredentialsProvider;
|
||||
import org.apache.http.client.params.AuthPolicy;
|
||||
import org.apache.http.client.protocol.ClientContext;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.util.Args;
|
||||
|
||||
/**
|
||||
* @deprecated (4.2) do not use
|
||||
*/
|
||||
@Immutable
|
||||
@Deprecated
|
||||
class AuthenticationStrategyAdaptor implements AuthenticationStrategy {
|
||||
|
||||
private final Log log = LogFactory.getLog(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<String, Header> getChallenges(
|
||||
final HttpHost authhost,
|
||||
final HttpResponse response,
|
||||
final HttpContext context) throws MalformedChallengeException {
|
||||
return this.handler.getChallenges(response, context);
|
||||
}
|
||||
|
||||
public Queue<AuthOption> select(
|
||||
final Map<String, Header> 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<AuthOption> options = new LinkedList<AuthOption>();
|
||||
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.ROOT));
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,190 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.client;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InterruptedIOException;
|
||||
import java.net.URI;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.annotation.ThreadSafe;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.ResponseHandler;
|
||||
import org.apache.http.client.ServiceUnavailableRetryStrategy;
|
||||
import org.apache.http.client.methods.HttpUriRequest;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.util.Args;
|
||||
import org.apache.http.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;
|
||||
|
||||
private final Log log = LogFactory.getLog(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> T execute(final HttpHost target, final HttpRequest request,
|
||||
final ResponseHandler<? extends T> responseHandler) throws IOException {
|
||||
return execute(target, request, responseHandler, null);
|
||||
}
|
||||
|
||||
public <T> 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> T execute(final HttpUriRequest request,
|
||||
final ResponseHandler<? extends T> responseHandler) throws IOException {
|
||||
return execute(request, responseHandler, null);
|
||||
}
|
||||
|
||||
public <T> 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();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,270 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.client;
|
||||
|
||||
import org.apache.http.annotation.NotThreadSafe;
|
||||
import org.apache.http.params.AbstractHttpParams;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.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:
|
||||
* <ol>
|
||||
* <li>Application parameters:
|
||||
* expected to be the same for all clients used by an application.
|
||||
* These provide "global", that is application-wide, defaults.
|
||||
* </li>
|
||||
* <li>Client parameters:
|
||||
* specific to an instance of
|
||||
* {@link org.apache.http.client.HttpClient HttpClient}.
|
||||
* These provide client specific defaults.
|
||||
* </li>
|
||||
* <li>Request parameters:
|
||||
* specific to a single request execution.
|
||||
* For overriding client and global defaults.
|
||||
* </li>
|
||||
* <li>Override parameters:
|
||||
* specific to an instance of
|
||||
* {@link org.apache.http.client.HttpClient HttpClient}.
|
||||
* These can be used to set parameters that cannot be overridden
|
||||
* on a per-request basis.
|
||||
* </li>
|
||||
* </ol>
|
||||
* Each stack entry may be {@code 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 'org.apache.http.config'
|
||||
* and 'org.apache.http.client.config'
|
||||
*/
|
||||
@NotThreadSafe
|
||||
@Deprecated
|
||||
public class ClientParamsStack extends AbstractHttpParams {
|
||||
|
||||
/** The application parameter collection, or {@code null}. */
|
||||
protected final HttpParams applicationParams;
|
||||
|
||||
/** The client parameter collection, or {@code null}. */
|
||||
protected final HttpParams clientParams;
|
||||
|
||||
/** The request parameter collection, or {@code null}. */
|
||||
protected final HttpParams requestParams;
|
||||
|
||||
/** The override parameter collection, or {@code 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 {@code null}
|
||||
* @param cparams client parameters, or {@code null}
|
||||
* @param rparams request parameters, or {@code null}
|
||||
* @param oparams override parameters, or {@code 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 {@code 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 {@code null}
|
||||
* @param cparams client parameters, or {@code null}
|
||||
* @param rparams request parameters, or {@code null}
|
||||
* @param oparams override parameters, or {@code 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 {@code null}
|
||||
*/
|
||||
public final HttpParams getApplicationParams() {
|
||||
return applicationParams;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains the client parameters of this stack.
|
||||
*
|
||||
* @return the client parameters, or {@code null}
|
||||
*/
|
||||
public final HttpParams getClientParams() {
|
||||
return clientParams;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains the request parameters of this stack.
|
||||
*
|
||||
* @return the request parameters, or {@code null}
|
||||
*/
|
||||
public final HttpParams getRequestParams() {
|
||||
return requestParams;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains the override parameters of this stack.
|
||||
*
|
||||
* @return the override parameters, or {@code 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
|
||||
* {@code 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 <i>not</i> 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 <i>not</i> 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 <i>not</i> 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.
|
||||
* <p>
|
||||
* Derived classes may change this behavior.
|
||||
* </p>
|
||||
*
|
||||
* @return {@code this} parameter stack
|
||||
*/
|
||||
public HttpParams copy() {
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -1,106 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.client;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.annotation.NotThreadSafe;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
||||
/**
|
||||
* @since 4.3
|
||||
*/
|
||||
@Deprecated
|
||||
@NotThreadSafe
|
||||
class CloseableHttpResponseProxy implements InvocationHandler {
|
||||
|
||||
private final static Constructor<?> CONSTRUCTOR;
|
||||
|
||||
static {
|
||||
try {
|
||||
CONSTRUCTOR = Proxy.getProxyClass(CloseableHttpResponseProxy.class.getClassLoader(),
|
||||
new Class<?>[] { CloseableHttpResponse.class }).getConstructor(new Class[] { InvocationHandler.class });
|
||||
} catch (NoSuchMethodException ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@Override
|
||||
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) {
|
||||
try {
|
||||
return (CloseableHttpResponse) CONSTRUCTOR.newInstance(new CloseableHttpResponseProxy(original));
|
||||
} catch (InstantiationException ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
} catch (InvocationTargetException ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
} catch (IllegalAccessException ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,93 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.client;
|
||||
|
||||
import org.apache.http.annotation.ThreadSafe;
|
||||
import org.apache.http.client.protocol.RequestAcceptEncoding;
|
||||
import org.apache.http.client.protocol.ResponseContentEncoding;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.protocol.BasicHttpProcessor;
|
||||
|
||||
/**
|
||||
* {@link DefaultHttpClient} sub-class which includes a {@link RequestAcceptEncoding}
|
||||
* for the request and response.
|
||||
*
|
||||
* <b>Deprecation note:</b> 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
|
||||
* org.apache.http.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;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,214 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.client;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpEntityEnclosingRequest;
|
||||
import org.apache.http.HttpException;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.HttpRequestInterceptor;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.HttpResponseInterceptor;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.ResponseHandler;
|
||||
import org.apache.http.client.methods.HttpUriRequest;
|
||||
import org.apache.http.client.protocol.RequestAcceptEncoding;
|
||||
import org.apache.http.client.protocol.ResponseContentEncoding;
|
||||
import org.apache.http.client.utils.URIUtils;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.protocol.BasicHttpContext;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
||||
/**
|
||||
* <p>Decorator adding support for compressed responses. This class sets
|
||||
* the {@code Accept-Encoding} header on requests to indicate
|
||||
* support for the {@code gzip} and {@code deflate}
|
||||
* compression schemes; it then checks the {@code 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.</p>
|
||||
*
|
||||
* <p><b>N.B.</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 {@code 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!).</p>
|
||||
*
|
||||
* <p>That said, this decorator is compatible with the
|
||||
* {@code CachingHttpClient} in that the two decorators can be added
|
||||
* in either order and still have cacheable responses be cached.</p>
|
||||
*
|
||||
* @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> T execute(final HttpUriRequest request,
|
||||
final ResponseHandler<? extends T> responseHandler) throws IOException,
|
||||
ClientProtocolException {
|
||||
return execute(getHttpHost(request), request, responseHandler);
|
||||
}
|
||||
|
||||
public <T> 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> T execute(final HttpHost target, final HttpRequest request,
|
||||
final ResponseHandler<? extends T> responseHandler) throws IOException,
|
||||
ClientProtocolException {
|
||||
return execute(target, request, responseHandler, null);
|
||||
}
|
||||
|
||||
public <T> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,227 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.client;
|
||||
|
||||
import org.apache.http.HttpVersion;
|
||||
import org.apache.http.annotation.ThreadSafe;
|
||||
import org.apache.http.client.protocol.RequestAddCookies;
|
||||
import org.apache.http.client.protocol.RequestAuthCache;
|
||||
import org.apache.http.client.protocol.RequestClientConnControl;
|
||||
import org.apache.http.client.protocol.RequestDefaultHeaders;
|
||||
import org.apache.http.client.protocol.RequestProxyAuthentication;
|
||||
import org.apache.http.client.protocol.RequestTargetAuthentication;
|
||||
import org.apache.http.client.protocol.ResponseProcessCookies;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.params.HttpConnectionParams;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.params.HttpProtocolParams;
|
||||
import org.apache.http.params.SyncBasicHttpParams;
|
||||
import org.apache.http.protocol.BasicHttpProcessor;
|
||||
import org.apache.http.protocol.HTTP;
|
||||
import org.apache.http.protocol.RequestContent;
|
||||
import org.apache.http.protocol.RequestExpectContinue;
|
||||
import org.apache.http.protocol.RequestTargetHost;
|
||||
import org.apache.http.protocol.RequestUserAgent;
|
||||
import org.apache.http.util.VersionInfo;
|
||||
|
||||
/**
|
||||
* Default implementation of {@link org.apache.http.client.HttpClient} pre-configured
|
||||
* for most common use scenarios.
|
||||
* <p>
|
||||
* Please see the Javadoc for {@link #createHttpProcessor()} for the details of the interceptors
|
||||
* that are set up by default.
|
||||
* <p>
|
||||
* Additional interceptors can be added as follows, but
|
||||
* take care not to add the same interceptor more than once.
|
||||
* <pre>
|
||||
* DefaultHttpClient httpclient = new DefaultHttpClient();
|
||||
* httpclient.addRequestInterceptor(new RequestAcceptEncoding());
|
||||
* httpclient.addResponseInterceptor(new ResponseContentEncoding());
|
||||
* </pre>
|
||||
* <p>
|
||||
* This class sets up the following parameters if not explicitly set:
|
||||
* <ul>
|
||||
* <li>Version: HttpVersion.HTTP_1_1</li>
|
||||
* <li>ContentCharset: HTTP.DEFAULT_CONTENT_CHARSET</li>
|
||||
* <li>NoTcpDelay: true</li>
|
||||
* <li>SocketBufferSize: 8192</li>
|
||||
* <li>UserAgent: Apache-HttpClient/release (java 1.5)</li>
|
||||
* </ul>
|
||||
* <p>
|
||||
* The following parameters can be used to customize the behavior of this
|
||||
* class:
|
||||
* <ul>
|
||||
* <li>{@link org.apache.http.params.CoreProtocolPNames#PROTOCOL_VERSION}</li>
|
||||
* <li>{@link org.apache.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
|
||||
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
|
||||
* <li>{@link org.apache.http.params.CoreProtocolPNames#USE_EXPECT_CONTINUE}</li>
|
||||
* <li>{@link org.apache.http.params.CoreProtocolPNames#WAIT_FOR_CONTINUE}</li>
|
||||
* <li>{@link org.apache.http.params.CoreProtocolPNames#USER_AGENT}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_LINGER}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_REUSEADDR}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#STALE_CONNECTION_CHECK}</li>
|
||||
* <li>{@link org.apache.http.conn.params.ConnRoutePNames#FORCED_ROUTE}</li>
|
||||
* <li>{@link org.apache.http.conn.params.ConnRoutePNames#LOCAL_ADDRESS}</li>
|
||||
* <li>{@link org.apache.http.conn.params.ConnRoutePNames#DEFAULT_PROXY}</li>
|
||||
* <li>{@link org.apache.http.cookie.params.CookieSpecPNames#DATE_PATTERNS}</li>
|
||||
* <li>{@link org.apache.http.cookie.params.CookieSpecPNames#SINGLE_COOKIE_HEADER}</li>
|
||||
* <li>{@link org.apache.http.auth.params.AuthPNames#CREDENTIAL_CHARSET}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#COOKIE_POLICY}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#HANDLE_AUTHENTICATION}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#HANDLE_REDIRECTS}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#MAX_REDIRECTS}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#ALLOW_CIRCULAR_REDIRECTS}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#VIRTUAL_HOST}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#DEFAULT_HOST}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#DEFAULT_HEADERS}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#CONN_MANAGER_TIMEOUT}</li>
|
||||
* </ul>
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) use {@link HttpClientBuilder} see also {@link CloseableHttpClient}.
|
||||
*/
|
||||
@ThreadSafe
|
||||
@Deprecated
|
||||
public class DefaultHttpClient extends AbstractHttpClient {
|
||||
|
||||
/**
|
||||
* Creates a new HTTP client from parameters and a connection manager.
|
||||
*
|
||||
* @param params the parameters
|
||||
* @param conman the connection manager
|
||||
*/
|
||||
public DefaultHttpClient(
|
||||
final ClientConnectionManager conman,
|
||||
final HttpParams params) {
|
||||
super(conman, params);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public DefaultHttpClient(
|
||||
final ClientConnectionManager conman) {
|
||||
super(conman, null);
|
||||
}
|
||||
|
||||
|
||||
public DefaultHttpClient(final HttpParams params) {
|
||||
super(null, params);
|
||||
}
|
||||
|
||||
|
||||
public DefaultHttpClient() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates the default set of HttpParams by invoking {@link DefaultHttpClient#setDefaultHttpParams(HttpParams)}
|
||||
*
|
||||
* @return a new instance of {@link SyncBasicHttpParams} with the defaults applied to it.
|
||||
*/
|
||||
@Override
|
||||
protected HttpParams createHttpParams() {
|
||||
final HttpParams params = new SyncBasicHttpParams();
|
||||
setDefaultHttpParams(params);
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the default set of HttpParams in the provided parameter.
|
||||
* These are:
|
||||
* <ul>
|
||||
* <li>{@link org.apache.http.params.CoreProtocolPNames#PROTOCOL_VERSION}:
|
||||
* 1.1</li>
|
||||
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_CONTENT_CHARSET}:
|
||||
* ISO-8859-1</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#TCP_NODELAY}:
|
||||
* true</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}:
|
||||
* 8192</li>
|
||||
* <li>{@link org.apache.http.params.CoreProtocolPNames#USER_AGENT}:
|
||||
* Apache-HttpClient (Java 1.5)</li>
|
||||
* </ul>
|
||||
*/
|
||||
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, VersionInfo.getUserAgent("Apache-HttpClient",
|
||||
"org.apache.http.client", DefaultHttpClient.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the processor with the following interceptors:
|
||||
* <ul>
|
||||
* <li>{@link RequestDefaultHeaders}</li>
|
||||
* <li>{@link RequestContent}</li>
|
||||
* <li>{@link RequestTargetHost}</li>
|
||||
* <li>{@link RequestClientConnControl}</li>
|
||||
* <li>{@link RequestUserAgent}</li>
|
||||
* <li>{@link RequestExpectContinue}</li>
|
||||
* <li>{@link RequestAddCookies}</li>
|
||||
* <li>{@link ResponseProcessCookies}</li>
|
||||
* <li>{@link RequestAuthCache}</li>
|
||||
* <li>{@link RequestTargetAuthentication}</li>
|
||||
* <li>{@link RequestProxyAuthentication}</li>
|
||||
* </ul>
|
||||
* <p>
|
||||
* @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;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,90 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.client;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.auth.AUTH;
|
||||
import org.apache.http.auth.MalformedChallengeException;
|
||||
import org.apache.http.auth.params.AuthPNames;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.util.Args;
|
||||
|
||||
/**
|
||||
* Default {@link org.apache.http.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<String, Header> 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<String> getAuthPreferences(
|
||||
final HttpResponse response,
|
||||
final HttpContext context) {
|
||||
@SuppressWarnings("unchecked")
|
||||
final
|
||||
List<String> authpref = (List<String>) response.getParams().getParameter(
|
||||
AuthPNames.PROXY_AUTH_PREF);
|
||||
if (authpref != null) {
|
||||
return authpref;
|
||||
} else {
|
||||
return super.getAuthPreferences(response, context);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,180 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.client;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.apache.http.ProtocolException;
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.client.CircularRedirectException;
|
||||
import org.apache.http.client.RedirectHandler;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpHead;
|
||||
import org.apache.http.client.params.ClientPNames;
|
||||
import org.apache.http.client.utils.URIUtils;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.protocol.ExecutionContext;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.util.Args;
|
||||
import org.apache.http.util.Asserts;
|
||||
|
||||
/**
|
||||
* Default implementation of {@link RedirectHandler}.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.1) use {@link DefaultRedirectStrategy}.
|
||||
*/
|
||||
@Immutable
|
||||
@Deprecated
|
||||
public class DefaultRedirectHandler implements RedirectHandler {
|
||||
|
||||
private final Log log = LogFactory.getLog(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;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,81 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.client;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.ProtocolException;
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.client.RedirectHandler;
|
||||
import org.apache.http.client.RedirectStrategy;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpHead;
|
||||
import org.apache.http.client.methods.HttpUriRequest;
|
||||
import org.apache.http.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;
|
||||
}
|
||||
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -1,91 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.client;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.auth.AUTH;
|
||||
import org.apache.http.auth.MalformedChallengeException;
|
||||
import org.apache.http.auth.params.AuthPNames;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.util.Args;
|
||||
|
||||
/**
|
||||
* Default {@link org.apache.http.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<String, Header> 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<String> getAuthPreferences(
|
||||
final HttpResponse response,
|
||||
final HttpContext context) {
|
||||
@SuppressWarnings("unchecked")
|
||||
final
|
||||
List<String> authpref = (List<String>) response.getParams().getParameter(
|
||||
AuthPNames.TARGET_AUTH_PREF);
|
||||
if (authpref != null) {
|
||||
return authpref;
|
||||
} else {
|
||||
return super.getAuthPreferences(response, context);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,61 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.client;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.auth.AuthState;
|
||||
import org.apache.http.client.AuthenticationStrategy;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
|
||||
/**
|
||||
* @deprecated (4.3) reserved for internal use.
|
||||
*
|
||||
*/
|
||||
@Deprecated
|
||||
public class HttpAuthenticator extends org.apache.http.impl.auth.HttpAuthenticator {
|
||||
|
||||
public HttpAuthenticator(final Log 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);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,67 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.client;
|
||||
|
||||
import org.apache.http.annotation.NotThreadSafe;
|
||||
import org.apache.http.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;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,149 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.client;
|
||||
|
||||
import java.net.ProxySelector;
|
||||
|
||||
import org.apache.http.ConnectionReuseStrategy;
|
||||
import org.apache.http.annotation.ThreadSafe;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.conn.routing.HttpRoutePlanner;
|
||||
import org.apache.http.impl.DefaultConnectionReuseStrategy;
|
||||
import org.apache.http.impl.NoConnectionReuseStrategy;
|
||||
import org.apache.http.impl.conn.PoolingClientConnectionManager;
|
||||
import org.apache.http.impl.conn.ProxySelectorRoutePlanner;
|
||||
import org.apache.http.impl.conn.SchemeRegistryFactory;
|
||||
import org.apache.http.params.HttpParams;
|
||||
|
||||
/**
|
||||
* An extension of {@link DefaultHttpClient} pre-configured using system properties.
|
||||
* <p>
|
||||
* The following system properties are taken into account by this class:
|
||||
* <ul>
|
||||
* <li>ssl.TrustManagerFactory.algorithm</li>
|
||||
* <li>javax.net.ssl.trustStoreType</li>
|
||||
* <li>javax.net.ssl.trustStore</li>
|
||||
* <li>javax.net.ssl.trustStoreProvider</li>
|
||||
* <li>javax.net.ssl.trustStorePassword</li>
|
||||
* <li>java.home</li>
|
||||
* <li>ssl.KeyManagerFactory.algorithm</li>
|
||||
* <li>javax.net.ssl.keyStoreType</li>
|
||||
* <li>javax.net.ssl.keyStore</li>
|
||||
* <li>javax.net.ssl.keyStoreProvider</li>
|
||||
* <li>javax.net.ssl.keyStorePassword</li>
|
||||
* <li>http.proxyHost</li>
|
||||
* <li>http.proxyPort</li>
|
||||
* <li>http.nonProxyHosts</li>
|
||||
* <li>http.keepAlive</li>
|
||||
* <li>http.maxConnections</li>
|
||||
* </ul>
|
||||
* <p>
|
||||
* <p>
|
||||
* The following parameters can be used to customize the behavior of this
|
||||
* class:
|
||||
* </p>
|
||||
* <ul>
|
||||
* <li>{@link org.apache.http.params.CoreProtocolPNames#PROTOCOL_VERSION}</li>
|
||||
* <li>{@link org.apache.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
|
||||
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
|
||||
* <li>{@link org.apache.http.params.CoreProtocolPNames#USE_EXPECT_CONTINUE}</li>
|
||||
* <li>{@link org.apache.http.params.CoreProtocolPNames#WAIT_FOR_CONTINUE}</li>
|
||||
* <li>{@link org.apache.http.params.CoreProtocolPNames#USER_AGENT}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_LINGER}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_REUSEADDR}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#STALE_CONNECTION_CHECK}</li>
|
||||
* <li>{@link org.apache.http.conn.params.ConnRoutePNames#FORCED_ROUTE}</li>
|
||||
* <li>{@link org.apache.http.conn.params.ConnRoutePNames#LOCAL_ADDRESS}</li>
|
||||
* <li>{@link org.apache.http.conn.params.ConnRoutePNames#DEFAULT_PROXY}</li>
|
||||
* <li>{@link org.apache.http.cookie.params.CookieSpecPNames#DATE_PATTERNS}</li>
|
||||
* <li>{@link org.apache.http.cookie.params.CookieSpecPNames#SINGLE_COOKIE_HEADER}</li>
|
||||
* <li>{@link org.apache.http.auth.params.AuthPNames#CREDENTIAL_CHARSET}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#COOKIE_POLICY}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#HANDLE_AUTHENTICATION}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#HANDLE_REDIRECTS}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#MAX_REDIRECTS}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#ALLOW_CIRCULAR_REDIRECTS}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#VIRTUAL_HOST}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#DEFAULT_HOST}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#DEFAULT_HEADERS}</li>
|
||||
* <li>{@link org.apache.http.client.params.ClientPNames#CONN_MANAGER_TIMEOUT}</li>
|
||||
* </ul>
|
||||
*
|
||||
* @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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,58 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.client;
|
||||
|
||||
import org.apache.http.HttpException;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.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;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,369 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.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 org.apache.http.HttpConnectionMetrics;
|
||||
import org.apache.http.HttpEntityEnclosingRequest;
|
||||
import org.apache.http.HttpException;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.annotation.NotThreadSafe;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.conn.ManagedClientConnection;
|
||||
import org.apache.http.conn.OperatedClientConnection;
|
||||
import org.apache.http.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.
|
||||
* <p>
|
||||
* 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.
|
||||
* <p>
|
||||
* 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 <i>not</i>
|
||||
* {@link #isMarkedReusable marked} as reusable.
|
||||
*
|
||||
* @param mgr the connection manager, or {@code null}
|
||||
* @param conn the connection to wrap, or {@code 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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,262 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InterruptedIOException;
|
||||
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.conn.ClientConnectionOperator;
|
||||
import org.apache.http.conn.OperatedClientConnection;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.conn.routing.RouteTracker;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.util.Args;
|
||||
import org.apache.http.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.
|
||||
* <p>
|
||||
* 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 {@code 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 {@code 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 {@code true} if the tunnel should be
|
||||
* considered secure, {@code 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 org.apache.http.conn.ManagedClientConnection#tunnelProxy
|
||||
* ManagedClientConnection.tunnelProxy}
|
||||
* for details.
|
||||
* @param secure {@code true} if the tunnel should be
|
||||
* considered secure, {@code 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;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,191 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.conn.OperatedClientConnection;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
|
||||
/**
|
||||
* Abstract adapter from pool {@link AbstractPoolEntry entries} to
|
||||
* {@link org.apache.http.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 {@code 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);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,278 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.HttpClientConnection;
|
||||
import org.apache.http.annotation.GuardedBy;
|
||||
import org.apache.http.annotation.ThreadSafe;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.conn.ClientConnectionOperator;
|
||||
import org.apache.http.conn.ClientConnectionRequest;
|
||||
import org.apache.http.conn.ManagedClientConnection;
|
||||
import org.apache.http.conn.OperatedClientConnection;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.util.Args;
|
||||
import org.apache.http.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.
|
||||
* <p>
|
||||
* 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.
|
||||
* </p>
|
||||
* <p>
|
||||
* This connection manager implementation should be used inside an EJB container instead of
|
||||
* {@link PoolingClientConnectionManager}.
|
||||
* </p>
|
||||
*
|
||||
* @since 4.2
|
||||
*
|
||||
* @deprecated (4.3) use {@link BasicHttpClientConnectionManager}.
|
||||
*/
|
||||
@ThreadSafe
|
||||
@Deprecated
|
||||
public class BasicClientConnectionManager implements ClientConnectionManager {
|
||||
|
||||
private final Log log = LogFactory.getLog(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 opconn = this.connOperator.createConnection();
|
||||
this.poolEntry = new HttpPoolEntry(this.log, id, route, opconn, 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,292 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.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 org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpException;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.HttpResponseFactory;
|
||||
import org.apache.http.annotation.NotThreadSafe;
|
||||
import org.apache.http.conn.OperatedClientConnection;
|
||||
import org.apache.http.conn.ManagedHttpClientConnection;
|
||||
import org.apache.http.impl.SocketHttpClientConnection;
|
||||
import org.apache.http.io.HttpMessageParser;
|
||||
import org.apache.http.io.SessionInputBuffer;
|
||||
import org.apache.http.io.SessionOutputBuffer;
|
||||
import org.apache.http.params.BasicHttpParams;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.params.HttpProtocolParams;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.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 {
|
||||
|
||||
private final Log log = LogFactory.getLog(getClass());
|
||||
private final Log headerLog = LogFactory.getLog("org.apache.http.headers");
|
||||
private final Log wireLog = LogFactory.getLog("org.apache.http.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<String, Object> attributes;
|
||||
|
||||
public DefaultClientConnection() {
|
||||
super();
|
||||
this.attributes = new HashMap<String, Object>();
|
||||
}
|
||||
|
||||
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<HttpResponse> 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);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,263 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.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 org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.annotation.ThreadSafe;
|
||||
import org.apache.http.client.protocol.ClientContext;
|
||||
import org.apache.http.conn.ClientConnectionOperator;
|
||||
import org.apache.http.conn.ConnectTimeoutException;
|
||||
import org.apache.http.conn.DnsResolver;
|
||||
import org.apache.http.conn.HttpInetSocketAddress;
|
||||
import org.apache.http.conn.OperatedClientConnection;
|
||||
import org.apache.http.conn.scheme.Scheme;
|
||||
import org.apache.http.conn.scheme.SchemeLayeredSocketFactory;
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.conn.scheme.SchemeSocketFactory;
|
||||
import org.apache.http.params.HttpConnectionParams;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.util.Args;
|
||||
import org.apache.http.util.Asserts;
|
||||
|
||||
/**
|
||||
* Default implementation of a {@link ClientConnectionOperator}. It uses a {@link SchemeRegistry}
|
||||
* to look up {@link SchemeSocketFactory} objects.
|
||||
* <p>
|
||||
* 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 org.apache.http.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 {@code CONNECTION_TIMEOUT * n} where {@code 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.
|
||||
* <p>
|
||||
* The following parameters can be used to customize the behavior of this
|
||||
* class:
|
||||
* <ul>
|
||||
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_LINGER}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_REUSEADDR}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
|
||||
* </ul>
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) use {@link PoolingHttpClientConnectionManager}.
|
||||
*/
|
||||
@Deprecated
|
||||
@ThreadSafe
|
||||
public class DefaultClientConnectionOperator implements ClientConnectionOperator {
|
||||
|
||||
private final Log log = LogFactory.getLog(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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,123 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn;
|
||||
|
||||
|
||||
import java.net.InetAddress;
|
||||
|
||||
import org.apache.http.HttpException;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.annotation.ThreadSafe;
|
||||
import org.apache.http.conn.params.ConnRouteParams;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.conn.routing.HttpRoutePlanner;
|
||||
import org.apache.http.conn.scheme.Scheme;
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.util.Args;
|
||||
import org.apache.http.util.Asserts;
|
||||
|
||||
/**
|
||||
* Default implementation of an {@link HttpRoutePlanner}. This implementation
|
||||
* is based on {@link org.apache.http.conn.params.ConnRoutePNames parameters}.
|
||||
* It will not make use of any Java system properties, nor of system or
|
||||
* browser proxy settings.
|
||||
* <p>
|
||||
* The following parameters can be used to customize the behavior of this
|
||||
* class:
|
||||
* <ul>
|
||||
* <li>{@link org.apache.http.conn.params.ConnRoutePNames#DEFAULT_PROXY}</li>
|
||||
* <li>{@link org.apache.http.conn.params.ConnRoutePNames#LOCAL_ADDRESS}</li>
|
||||
* <li>{@link org.apache.http.conn.params.ConnRoutePNames#FORCED_ROUTE}</li>
|
||||
* </ul>
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,125 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.HttpException;
|
||||
import org.apache.http.HttpMessage;
|
||||
import org.apache.http.HttpResponseFactory;
|
||||
import org.apache.http.NoHttpResponseException;
|
||||
import org.apache.http.ProtocolException;
|
||||
import org.apache.http.StatusLine;
|
||||
import org.apache.http.annotation.ThreadSafe;
|
||||
import org.apache.http.impl.io.AbstractMessageParser;
|
||||
import org.apache.http.io.SessionInputBuffer;
|
||||
import org.apache.http.message.LineParser;
|
||||
import org.apache.http.message.ParserCursor;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.util.Args;
|
||||
import org.apache.http.util.CharArrayBuffer;
|
||||
|
||||
/**
|
||||
* Default HTTP response parser implementation.
|
||||
* <p>
|
||||
* The following parameters can be used to customize the behavior of this
|
||||
* class:
|
||||
* <ul>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
|
||||
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
|
||||
* <li>{@link org.apache.http.conn.params.ConnConnectionPNames#MAX_STATUS_LINE_GARBAGE}</li>
|
||||
* </ul>
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.2) use {@link DefaultHttpResponseParser}
|
||||
*/
|
||||
@Deprecated
|
||||
@ThreadSafe // no public methods
|
||||
public class DefaultResponseParser extends AbstractMessageParser<HttpMessage> {
|
||||
|
||||
private final Log log = LogFactory.getLog(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(
|
||||
org.apache.http.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);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,84 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.http.conn.ClientConnectionOperator;
|
||||
import org.apache.http.conn.OperatedClientConnection;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.pool.AbstractConnPool;
|
||||
import org.apache.http.pool.ConnFactory;
|
||||
|
||||
/**
|
||||
* @since 4.2
|
||||
*
|
||||
* @deprecated (4.3) no longer used.
|
||||
*/
|
||||
@Deprecated
|
||||
class HttpConnPool extends AbstractConnPool<HttpRoute, OperatedClientConnection, HttpPoolEntry> {
|
||||
|
||||
private static final AtomicLong COUNTER = new AtomicLong();
|
||||
|
||||
private final Log log;
|
||||
private final long timeToLive;
|
||||
private final TimeUnit tunit;
|
||||
|
||||
public HttpConnPool(final Log 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<HttpRoute, OperatedClientConnection> {
|
||||
|
||||
private final ClientConnectionOperator connOperator;
|
||||
|
||||
InternalConnFactory(final ClientConnectionOperator connOperator) {
|
||||
this.connOperator = connOperator;
|
||||
}
|
||||
|
||||
public OperatedClientConnection create(final HttpRoute route) throws IOException {
|
||||
return connOperator.createConnection();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -1,98 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Date;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.http.conn.OperatedClientConnection;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.conn.routing.RouteTracker;
|
||||
import org.apache.http.pool.PoolEntry;
|
||||
|
||||
/**
|
||||
* @since 4.2
|
||||
*
|
||||
* @deprecated (4.3) no longer used.
|
||||
*/
|
||||
@Deprecated
|
||||
class HttpPoolEntry extends PoolEntry<HttpRoute, OperatedClientConnection> {
|
||||
|
||||
private final Log log;
|
||||
private final RouteTracker tracker;
|
||||
|
||||
public HttpPoolEntry(
|
||||
final Log 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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,181 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.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 org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.HttpConnection;
|
||||
|
||||
// Currently only used by AbstractConnPool
|
||||
/**
|
||||
* A helper class for connection managers to track idle connections.
|
||||
*
|
||||
* <p>This class is not synchronized.</p>
|
||||
*
|
||||
* @see org.apache.http.conn.ClientConnectionManager#closeIdleConnections
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.1) no longer used
|
||||
*/
|
||||
@Deprecated
|
||||
public class IdleConnectionHandler {
|
||||
|
||||
private final Log log = LogFactory.getLog(getClass());
|
||||
|
||||
/** Holds connections and the time they were added. */
|
||||
private final Map<HttpConnection,TimeValues> connectionToTimes;
|
||||
|
||||
|
||||
public IdleConnectionHandler() {
|
||||
super();
|
||||
connectionToTimes = new HashMap<HttpConnection,TimeValues>();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<HttpConnection, TimeValues> 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<HttpConnection, TimeValues> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,138 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.http.Consts;
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.io.EofSensor;
|
||||
import org.apache.http.io.HttpTransportMetrics;
|
||||
import org.apache.http.io.SessionInputBuffer;
|
||||
import org.apache.http.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, {@code ASCII} if {@code 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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,118 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.http.Consts;
|
||||
import org.apache.http.annotation.Immutable;
|
||||
import org.apache.http.io.HttpTransportMetrics;
|
||||
import org.apache.http.io.SessionOutputBuffer;
|
||||
import org.apache.http.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, {@code ASCII} if {@code 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();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,461 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.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 org.apache.http.HttpConnectionMetrics;
|
||||
import org.apache.http.HttpEntityEnclosingRequest;
|
||||
import org.apache.http.HttpException;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.annotation.NotThreadSafe;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.conn.ClientConnectionOperator;
|
||||
import org.apache.http.conn.ManagedClientConnection;
|
||||
import org.apache.http.conn.OperatedClientConnection;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.conn.routing.RouteTracker;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.util.Args;
|
||||
import org.apache.http.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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,329 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.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 org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.annotation.ThreadSafe;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.conn.ClientConnectionOperator;
|
||||
import org.apache.http.conn.ClientConnectionRequest;
|
||||
import org.apache.http.conn.ConnectionPoolTimeoutException;
|
||||
import org.apache.http.conn.DnsResolver;
|
||||
import org.apache.http.conn.ManagedClientConnection;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.pool.ConnPoolControl;
|
||||
import org.apache.http.pool.PoolStats;
|
||||
import org.apache.http.util.Args;
|
||||
import org.apache.http.util.Asserts;
|
||||
|
||||
/**
|
||||
* Manages a pool of {@link org.apache.http.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.
|
||||
* <p>
|
||||
* 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<HttpRoute> {
|
||||
|
||||
private final Log log = LogFactory.getLog(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<HttpPoolEntry> 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<HttpPoolEntry> 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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,280 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.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 org.apache.http.HttpException;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.annotation.NotThreadSafe;
|
||||
import org.apache.http.conn.params.ConnRouteParams;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.conn.routing.HttpRoutePlanner;
|
||||
import org.apache.http.conn.scheme.Scheme;
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.util.Args;
|
||||
import org.apache.http.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 org.apache.http.conn.params.ConnRoutePNames parameters},
|
||||
* though not the {@link
|
||||
* org.apache.http.conn.params.ConnRoutePNames#DEFAULT_PROXY DEFAULT_PROXY}.
|
||||
* <p>
|
||||
* The following parameters can be used to customize the behavior of this
|
||||
* class:
|
||||
* <ul>
|
||||
* <li>{@link org.apache.http.conn.params.ConnRoutePNames#LOCAL_ADDRESS}</li>
|
||||
* <li>{@link org.apache.http.conn.params.ConnRoutePNames#FORCED_ROUTE}</li>
|
||||
* </ul>
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.3) use {@link SystemDefaultRoutePlanner}
|
||||
*/
|
||||
@NotThreadSafe // e.g [gs]etProxySelector()
|
||||
@Deprecated
|
||||
public class ProxySelectorRoutePlanner implements HttpRoutePlanner {
|
||||
|
||||
/** The scheme registry. */
|
||||
protected final SchemeRegistry schemeRegistry; // @ThreadSafe
|
||||
|
||||
/** The proxy selector to use, or {@code null} for system default. */
|
||||
protected ProxySelector proxySelector;
|
||||
|
||||
/**
|
||||
* Creates a new proxy selector route planner.
|
||||
*
|
||||
* @param schreg the scheme registry
|
||||
* @param prosel the proxy selector, or
|
||||
* {@code null} for the system default
|
||||
*/
|
||||
public ProxySelectorRoutePlanner(final SchemeRegistry schreg,
|
||||
final ProxySelector prosel) {
|
||||
Args.notNull(schreg, "SchemeRegistry");
|
||||
schemeRegistry = schreg;
|
||||
proxySelector = prosel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains the proxy selector to use.
|
||||
*
|
||||
* @return the proxy selector, or {@code null} for the system default
|
||||
*/
|
||||
public ProxySelector getProxySelector() {
|
||||
return this.proxySelector;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the proxy selector to use.
|
||||
*
|
||||
* @param prosel the proxy selector, or
|
||||
* {@code null} to use the system default
|
||||
*/
|
||||
public void setProxySelector(final ProxySelector prosel) {
|
||||
this.proxySelector = prosel;
|
||||
}
|
||||
|
||||
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 = determineProxy(target, request, context);
|
||||
|
||||
final Scheme schm =
|
||||
this.schemeRegistry.getScheme(target.getSchemeName());
|
||||
// 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines a proxy for the given target.
|
||||
*
|
||||
* @param target the planned target, never {@code null}
|
||||
* @param request the request to be sent, never {@code null}
|
||||
* @param context the context, or {@code null}
|
||||
*
|
||||
* @return the proxy to use, or {@code null} for a direct route
|
||||
*
|
||||
* @throws HttpException
|
||||
* in case of system proxy settings that cannot be handled
|
||||
*/
|
||||
protected HttpHost determineProxy(final HttpHost target,
|
||||
final HttpRequest request,
|
||||
final HttpContext context)
|
||||
throws HttpException {
|
||||
|
||||
// the proxy selector can be 'unset', so we better deal with null here
|
||||
ProxySelector psel = this.proxySelector;
|
||||
if (psel == null) {
|
||||
psel = ProxySelector.getDefault();
|
||||
}
|
||||
if (psel == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
URI targetURI = null;
|
||||
try {
|
||||
targetURI = new URI(target.toURI());
|
||||
} catch (final URISyntaxException usx) {
|
||||
throw new HttpException
|
||||
("Cannot convert host to URI: " + target, usx);
|
||||
}
|
||||
final List<Proxy> proxies = psel.select(targetURI);
|
||||
|
||||
final Proxy p = chooseProxy(proxies, target, request, context);
|
||||
|
||||
HttpHost result = null;
|
||||
if (p.type() == Proxy.Type.HTTP) {
|
||||
// convert the socket address to an HttpHost
|
||||
if (!(p.address() instanceof InetSocketAddress)) {
|
||||
throw new HttpException
|
||||
("Unable to handle non-Inet proxy address: "+p.address());
|
||||
}
|
||||
final InetSocketAddress isa = (InetSocketAddress) p.address();
|
||||
// assume default scheme (http)
|
||||
result = new HttpHost(getHost(isa), isa.getPort());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains a host from an {@link InetSocketAddress}.
|
||||
*
|
||||
* @param isa the socket address
|
||||
*
|
||||
* @return a host string, either as a symbolic name or
|
||||
* as a literal IP address string
|
||||
* <p>
|
||||
* (TODO: determine format for IPv6 addresses, with or without [brackets])
|
||||
* </p>
|
||||
*/
|
||||
protected String getHost(final InetSocketAddress isa) {
|
||||
|
||||
//@@@ Will this work with literal IPv6 addresses, or do we
|
||||
//@@@ need to wrap these in [] for the string representation?
|
||||
//@@@ Having it in this method at least allows for easy workarounds.
|
||||
return isa.isUnresolved() ?
|
||||
isa.getHostName() : isa.getAddress().getHostAddress();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Chooses a proxy from a list of available proxies.
|
||||
* The default implementation just picks the first non-SOCKS proxy
|
||||
* from the list. If there are only SOCKS proxies,
|
||||
* {@link Proxy#NO_PROXY Proxy.NO_PROXY} is returned.
|
||||
* Derived classes may implement more advanced strategies,
|
||||
* such as proxy rotation if there are multiple options.
|
||||
*
|
||||
* @param proxies the list of proxies to choose from,
|
||||
* never {@code null} or empty
|
||||
* @param target the planned target, never {@code null}
|
||||
* @param request the request to be sent, never {@code null}
|
||||
* @param context the context, or {@code null}
|
||||
*
|
||||
* @return a proxy type
|
||||
*/
|
||||
protected Proxy chooseProxy(final List<Proxy> proxies,
|
||||
final HttpHost target,
|
||||
final HttpRequest request,
|
||||
final HttpContext context) {
|
||||
Args.notEmpty(proxies, "List of proxies");
|
||||
|
||||
Proxy result = null;
|
||||
|
||||
// check the list for one we can use
|
||||
for (int i=0; (result == null) && (i < proxies.size()); i++) {
|
||||
|
||||
final Proxy p = proxies.get(i);
|
||||
switch (p.type()) {
|
||||
|
||||
case DIRECT:
|
||||
case HTTP:
|
||||
result = p;
|
||||
break;
|
||||
|
||||
case SOCKS:
|
||||
// SOCKS hosts are not handled on the route level.
|
||||
// The socket may make use of the SOCKS host though.
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (result == null) {
|
||||
//@@@ log as warning or info that only a socks proxy is available?
|
||||
// result can only be null if all proxies are socks proxies
|
||||
// socks proxies are not handled on the route planning level
|
||||
result = Proxy.NO_PROXY;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,90 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn;
|
||||
|
||||
import org.apache.http.annotation.ThreadSafe;
|
||||
import org.apache.http.conn.scheme.PlainSocketFactory;
|
||||
import org.apache.http.conn.scheme.Scheme;
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.conn.ssl.SSLSocketFactory;
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*
|
||||
* @deprecated (4.3) use {@link org.apache.http.impl.client.HttpClientBuilder}.
|
||||
*/
|
||||
@ThreadSafe
|
||||
@Deprecated
|
||||
public final class SchemeRegistryFactory {
|
||||
|
||||
/**
|
||||
* Initializes default scheme registry based on JSSE defaults. System properties will
|
||||
* not be taken into consideration.
|
||||
*/
|
||||
public static SchemeRegistry createDefault() {
|
||||
final SchemeRegistry registry = new SchemeRegistry();
|
||||
registry.register(
|
||||
new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
|
||||
registry.register(
|
||||
new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
|
||||
return registry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes default scheme registry using system properties as described in
|
||||
* <a href="http://download.oracle.com/javase/1,5.0/docs/guide/security/jsse/JSSERefGuide.html">
|
||||
* "JavaTM Secure Socket Extension (JSSE) Reference Guide for the JavaTM 2 Platform
|
||||
* Standard Edition 5</a>
|
||||
* <p>
|
||||
* The following system properties are taken into account by this method:
|
||||
* <ul>
|
||||
* <li>ssl.TrustManagerFactory.algorithm</li>
|
||||
* <li>javax.net.ssl.trustStoreType</li>
|
||||
* <li>javax.net.ssl.trustStore</li>
|
||||
* <li>javax.net.ssl.trustStoreProvider</li>
|
||||
* <li>javax.net.ssl.trustStorePassword</li>
|
||||
* <li>java.home</li>
|
||||
* <li>ssl.KeyManagerFactory.algorithm</li>
|
||||
* <li>javax.net.ssl.keyStoreType</li>
|
||||
* <li>javax.net.ssl.keyStore</li>
|
||||
* <li>javax.net.ssl.keyStoreProvider</li>
|
||||
* <li>javax.net.ssl.keyStorePassword</li>
|
||||
* </ul>
|
||||
* <p>
|
||||
*
|
||||
* @since 4.2
|
||||
*/
|
||||
public static SchemeRegistry createSystemDefault() {
|
||||
final SchemeRegistry registry = new SchemeRegistry();
|
||||
registry.register(
|
||||
new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
|
||||
registry.register(
|
||||
new Scheme("https", 443, SSLSocketFactory.getSystemSocketFactory()));
|
||||
return registry;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,427 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.annotation.GuardedBy;
|
||||
import org.apache.http.annotation.ThreadSafe;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.conn.ClientConnectionOperator;
|
||||
import org.apache.http.conn.ClientConnectionRequest;
|
||||
import org.apache.http.conn.ManagedClientConnection;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.conn.routing.RouteTracker;
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.util.Args;
|
||||
import org.apache.http.util.Asserts;
|
||||
|
||||
/**
|
||||
* A connection manager for a single connection. This connection manager
|
||||
* maintains only one active connection at a time. Even though this class
|
||||
* is thread-safe it ought to be used by one execution thread only.
|
||||
* <p>
|
||||
* SingleClientConnManager 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.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.2) use {@link BasicClientConnectionManager}
|
||||
*/
|
||||
@ThreadSafe
|
||||
@Deprecated
|
||||
public class SingleClientConnManager implements ClientConnectionManager {
|
||||
|
||||
private final Log log = LogFactory.getLog(getClass());
|
||||
|
||||
/** The message to be logged on multiple allocation. */
|
||||
public final static String MISUSE_MESSAGE =
|
||||
"Invalid use of SingleClientConnManager: connection still allocated.\n" +
|
||||
"Make sure to release the connection before allocating another one.";
|
||||
|
||||
/** The schemes supported by this connection manager. */
|
||||
protected final SchemeRegistry schemeRegistry;
|
||||
|
||||
/** The operator for opening and updating connections. */
|
||||
protected final ClientConnectionOperator connOperator;
|
||||
|
||||
/** Whether the connection should be shut down on release. */
|
||||
protected final boolean alwaysShutDown;
|
||||
|
||||
/** The one and only entry in this pool. */
|
||||
@GuardedBy("this")
|
||||
protected volatile PoolEntry uniquePoolEntry;
|
||||
|
||||
/** The currently issued managed connection, if any. */
|
||||
@GuardedBy("this")
|
||||
protected volatile ConnAdapter managedConn;
|
||||
|
||||
/** The time of the last connection release, or -1. */
|
||||
@GuardedBy("this")
|
||||
protected volatile long lastReleaseTime;
|
||||
|
||||
/** The time the last released connection expires and shouldn't be reused. */
|
||||
@GuardedBy("this")
|
||||
protected volatile long connectionExpiresTime;
|
||||
|
||||
/** Indicates whether this connection manager is shut down. */
|
||||
protected volatile boolean isShutDown;
|
||||
|
||||
/**
|
||||
* Creates a new simple connection manager.
|
||||
*
|
||||
* @param params the parameters for this manager
|
||||
* @param schreg the scheme registry
|
||||
*
|
||||
* @deprecated (4.1) use {@link SingleClientConnManager#SingleClientConnManager(SchemeRegistry)}
|
||||
*/
|
||||
@Deprecated
|
||||
public SingleClientConnManager(final HttpParams params,
|
||||
final SchemeRegistry schreg) {
|
||||
this(schreg);
|
||||
}
|
||||
/**
|
||||
* Creates a new simple connection manager.
|
||||
*
|
||||
* @param schreg the scheme registry
|
||||
*/
|
||||
public SingleClientConnManager(final SchemeRegistry schreg) {
|
||||
Args.notNull(schreg, "Scheme registry");
|
||||
this.schemeRegistry = schreg;
|
||||
this.connOperator = createConnectionOperator(schreg);
|
||||
this.uniquePoolEntry = new PoolEntry();
|
||||
this.managedConn = null;
|
||||
this.lastReleaseTime = -1L;
|
||||
this.alwaysShutDown = false; //@@@ from params? as argument?
|
||||
this.isShutDown = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public SingleClientConnManager() {
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 to use, or {@code null}
|
||||
*
|
||||
* @return the connection operator to use
|
||||
*/
|
||||
protected ClientConnectionOperator
|
||||
createConnectionOperator(final SchemeRegistry schreg) {
|
||||
return new DefaultClientConnectionOperator(schreg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that this manager is not shut down.
|
||||
*
|
||||
* @throws IllegalStateException if this manager is shut down
|
||||
*/
|
||||
protected final void assertStillUp() throws IllegalStateException {
|
||||
Asserts.check(!this.isShutDown, "Manager is shut down");
|
||||
}
|
||||
|
||||
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 SingleClientConnManager.this.getConnection(
|
||||
route, state);
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains a connection.
|
||||
*
|
||||
* @param route where the connection should point to
|
||||
*
|
||||
* @return a connection that can be used to communicate
|
||||
* along the given route
|
||||
*/
|
||||
public ManagedClientConnection getConnection(final HttpRoute route, final Object state) {
|
||||
Args.notNull(route, "Route");
|
||||
assertStillUp();
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Get connection for route " + route);
|
||||
}
|
||||
|
||||
synchronized (this) {
|
||||
|
||||
Asserts.check(managedConn == null, MISUSE_MESSAGE);
|
||||
|
||||
// check re-usability of the connection
|
||||
boolean recreate = false;
|
||||
boolean shutdown = false;
|
||||
|
||||
// Kill the connection if it expired.
|
||||
closeExpiredConnections();
|
||||
|
||||
if (uniquePoolEntry.connection.isOpen()) {
|
||||
final RouteTracker tracker = uniquePoolEntry.tracker;
|
||||
shutdown = (tracker == null || // can happen if method is aborted
|
||||
!tracker.toRoute().equals(route));
|
||||
} else {
|
||||
// If the connection is not open, create a new PoolEntry,
|
||||
// as the connection may have been marked not reusable,
|
||||
// due to aborts -- and the PoolEntry should not be reused
|
||||
// either. There's no harm in recreating an entry if
|
||||
// the connection is closed.
|
||||
recreate = true;
|
||||
}
|
||||
|
||||
if (shutdown) {
|
||||
recreate = true;
|
||||
try {
|
||||
uniquePoolEntry.shutdown();
|
||||
} catch (final IOException iox) {
|
||||
log.debug("Problem shutting down connection.", iox);
|
||||
}
|
||||
}
|
||||
|
||||
if (recreate) {
|
||||
uniquePoolEntry = new PoolEntry();
|
||||
}
|
||||
|
||||
managedConn = new ConnAdapter(uniquePoolEntry, route);
|
||||
|
||||
return managedConn;
|
||||
}
|
||||
}
|
||||
|
||||
public void releaseConnection(
|
||||
final ManagedClientConnection conn,
|
||||
final long validDuration, final TimeUnit timeUnit) {
|
||||
Args.check(conn instanceof ConnAdapter, "Connection class mismatch, " +
|
||||
"connection not obtained from this manager");
|
||||
assertStillUp();
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Releasing connection " + conn);
|
||||
}
|
||||
|
||||
final ConnAdapter sca = (ConnAdapter) conn;
|
||||
synchronized (sca) {
|
||||
if (sca.poolEntry == null)
|
||||
{
|
||||
return; // already released
|
||||
}
|
||||
final ClientConnectionManager manager = sca.getManager();
|
||||
Asserts.check(manager == this, "Connection not obtained from this manager");
|
||||
try {
|
||||
// make sure that the response has been read completely
|
||||
if (sca.isOpen() && (this.alwaysShutDown ||
|
||||
!sca.isMarkedReusable())
|
||||
) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug
|
||||
("Released connection open but not reusable.");
|
||||
}
|
||||
|
||||
// make sure this connection will not be re-used
|
||||
// we might have gotten here because of a shutdown trigger
|
||||
// shutdown of the adapter also clears the tracked route
|
||||
sca.shutdown();
|
||||
}
|
||||
} catch (final IOException iox) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Exception shutting down released connection.",
|
||||
iox);
|
||||
}
|
||||
} finally {
|
||||
sca.detach();
|
||||
synchronized (this) {
|
||||
managedConn = null;
|
||||
lastReleaseTime = System.currentTimeMillis();
|
||||
if(validDuration > 0) {
|
||||
connectionExpiresTime = timeUnit.toMillis(validDuration) + lastReleaseTime;
|
||||
} else {
|
||||
connectionExpiresTime = Long.MAX_VALUE;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void closeExpiredConnections() {
|
||||
final long time = connectionExpiresTime;
|
||||
if (System.currentTimeMillis() >= time) {
|
||||
closeIdleConnections(0, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
public void closeIdleConnections(final long idletime, final TimeUnit tunit) {
|
||||
assertStillUp();
|
||||
|
||||
// idletime can be 0 or negative, no problem there
|
||||
Args.notNull(tunit, "Time unit");
|
||||
|
||||
synchronized (this) {
|
||||
if ((managedConn == null) && uniquePoolEntry.connection.isOpen()) {
|
||||
final long cutoff =
|
||||
System.currentTimeMillis() - tunit.toMillis(idletime);
|
||||
if (lastReleaseTime <= cutoff) {
|
||||
try {
|
||||
uniquePoolEntry.close();
|
||||
} catch (final IOException iox) {
|
||||
// ignore
|
||||
log.debug("Problem closing idle connection.", iox);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
this.isShutDown = true;
|
||||
synchronized (this) {
|
||||
try {
|
||||
if (uniquePoolEntry != null) {
|
||||
uniquePoolEntry.shutdown();
|
||||
}
|
||||
} catch (final IOException iox) {
|
||||
// ignore
|
||||
log.debug("Problem while shutting down manager.", iox);
|
||||
} finally {
|
||||
uniquePoolEntry = null;
|
||||
managedConn = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected void revokeConnection() {
|
||||
final ConnAdapter conn = managedConn;
|
||||
if (conn == null) {
|
||||
return;
|
||||
}
|
||||
conn.detach();
|
||||
|
||||
synchronized (this) {
|
||||
try {
|
||||
uniquePoolEntry.shutdown();
|
||||
} catch (final IOException iox) {
|
||||
// ignore
|
||||
log.debug("Problem while shutting down connection.", iox);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The pool entry for this connection manager.
|
||||
*/
|
||||
protected class PoolEntry extends AbstractPoolEntry {
|
||||
|
||||
/**
|
||||
* Creates a new pool entry.
|
||||
*
|
||||
*/
|
||||
protected PoolEntry() {
|
||||
super(SingleClientConnManager.this.connOperator, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the connection in this pool entry.
|
||||
*/
|
||||
protected void close() throws IOException {
|
||||
shutdownEntry();
|
||||
if (connection.isOpen()) {
|
||||
connection.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shuts down the connection in this pool entry.
|
||||
*/
|
||||
protected void shutdown() throws IOException {
|
||||
shutdownEntry();
|
||||
if (connection.isOpen()) {
|
||||
connection.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The connection adapter used by this manager.
|
||||
*/
|
||||
protected class ConnAdapter extends AbstractPooledConnAdapter {
|
||||
|
||||
/**
|
||||
* Creates a new connection adapter.
|
||||
*
|
||||
* @param entry the pool entry for the connection being wrapped
|
||||
* @param route the planned route for this connection
|
||||
*/
|
||||
protected ConnAdapter(final PoolEntry entry, final HttpRoute route) {
|
||||
super(SingleClientConnManager.this, entry);
|
||||
markReusable();
|
||||
entry.route = route;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -1,238 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn.tsccm;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.ref.Reference;
|
||||
import java.lang.ref.ReferenceQueue;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.annotation.GuardedBy;
|
||||
import org.apache.http.conn.ConnectionPoolTimeoutException;
|
||||
import org.apache.http.conn.OperatedClientConnection;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.impl.conn.IdleConnectionHandler;
|
||||
import org.apache.http.util.Args;
|
||||
|
||||
/**
|
||||
* An abstract connection pool.
|
||||
* It is used by the {@link ThreadSafeClientConnManager}.
|
||||
* The abstract pool includes a {@link #poolLock}, which is used to
|
||||
* synchronize access to the internal pool datastructures.
|
||||
* Don't use {@code synchronized} for that purpose!
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.2) use {@link org.apache.http.pool.AbstractConnPool}
|
||||
*/
|
||||
@Deprecated
|
||||
public abstract class AbstractConnPool {
|
||||
|
||||
private final Log log;
|
||||
|
||||
/**
|
||||
* The global lock for this pool.
|
||||
*/
|
||||
protected final Lock poolLock;
|
||||
|
||||
/** References to issued connections */
|
||||
@GuardedBy("poolLock")
|
||||
protected Set<BasicPoolEntry> leasedConnections;
|
||||
|
||||
/** The current total number of connections. */
|
||||
@GuardedBy("poolLock")
|
||||
protected int numConnections;
|
||||
|
||||
/** Indicates whether this pool is shut down. */
|
||||
protected volatile boolean isShutDown;
|
||||
|
||||
protected Set<BasicPoolEntryRef> issuedConnections;
|
||||
|
||||
protected ReferenceQueue<Object> refQueue;
|
||||
|
||||
protected IdleConnectionHandler idleConnHandler;
|
||||
|
||||
/**
|
||||
* Creates a new connection pool.
|
||||
*/
|
||||
protected AbstractConnPool() {
|
||||
super();
|
||||
this.log = LogFactory.getLog(getClass());
|
||||
this.leasedConnections = new HashSet<BasicPoolEntry>();
|
||||
this.idleConnHandler = new IdleConnectionHandler();
|
||||
this.poolLock = new ReentrantLock();
|
||||
}
|
||||
|
||||
public void enableConnectionGC()
|
||||
throws IllegalStateException {
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains a pool entry with a connection within the given timeout.
|
||||
*
|
||||
* @param route the route for which to get the connection
|
||||
* @param state the state
|
||||
* @param timeout the timeout, 0 or negative for no timeout
|
||||
* @param tunit the unit for the {@code timeout},
|
||||
* may be {@code null} only if there is no timeout
|
||||
*
|
||||
* @return pool entry holding a connection for the route
|
||||
*
|
||||
* @throws ConnectionPoolTimeoutException
|
||||
* if the timeout expired
|
||||
* @throws InterruptedException
|
||||
* if the calling thread was interrupted
|
||||
*/
|
||||
public final
|
||||
BasicPoolEntry getEntry(
|
||||
final HttpRoute route,
|
||||
final Object state,
|
||||
final long timeout,
|
||||
final TimeUnit tunit)
|
||||
throws ConnectionPoolTimeoutException, InterruptedException {
|
||||
return requestPoolEntry(route, state).getPoolEntry(timeout, tunit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new {@link PoolEntryRequest}, from which a {@link BasicPoolEntry}
|
||||
* can be obtained, or the request can be aborted.
|
||||
* @param route the route
|
||||
* @param state the state
|
||||
* @return the entry request
|
||||
*/
|
||||
public abstract PoolEntryRequest requestPoolEntry(HttpRoute route, Object state);
|
||||
|
||||
|
||||
/**
|
||||
* Returns an entry into the pool.
|
||||
* The connection of the entry is expected to be in a suitable state,
|
||||
* either open and re-usable, or closed. The pool will not make any
|
||||
* attempt to determine whether it can be re-used or not.
|
||||
*
|
||||
* @param entry the entry for the connection to release
|
||||
* @param reusable {@code true} if the entry is deemed
|
||||
* reusable, {@code false} otherwise.
|
||||
* @param validDuration The duration that the entry should remain free and reusable.
|
||||
* @param timeUnit The unit of time the duration is measured in.
|
||||
*/
|
||||
public abstract void freeEntry(BasicPoolEntry entry, boolean reusable, long validDuration, TimeUnit timeUnit)
|
||||
;
|
||||
|
||||
public void handleReference(final Reference<?> ref) {
|
||||
}
|
||||
|
||||
protected abstract void handleLostEntry(HttpRoute route);
|
||||
|
||||
/**
|
||||
* Closes idle connections.
|
||||
*
|
||||
* @param idletime the time the connections should have been idle
|
||||
* in order to be closed now
|
||||
* @param tunit the unit for the {@code idletime}
|
||||
*/
|
||||
public void closeIdleConnections(final long idletime, final TimeUnit tunit) {
|
||||
|
||||
// idletime can be 0 or negative, no problem there
|
||||
Args.notNull(tunit, "Time unit");
|
||||
|
||||
poolLock.lock();
|
||||
try {
|
||||
idleConnHandler.closeIdleConnections(tunit.toMillis(idletime));
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void closeExpiredConnections() {
|
||||
poolLock.lock();
|
||||
try {
|
||||
idleConnHandler.closeExpiredConnections();
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Deletes all entries for closed connections.
|
||||
*/
|
||||
public abstract void deleteClosedConnections();
|
||||
|
||||
/**
|
||||
* Shuts down this pool and all associated resources.
|
||||
* Overriding methods MUST call the implementation here!
|
||||
*/
|
||||
public void shutdown() {
|
||||
|
||||
poolLock.lock();
|
||||
try {
|
||||
|
||||
if (isShutDown) {
|
||||
return;
|
||||
}
|
||||
|
||||
// close all connections that are issued to an application
|
||||
final Iterator<BasicPoolEntry> iter = leasedConnections.iterator();
|
||||
while (iter.hasNext()) {
|
||||
final BasicPoolEntry entry = iter.next();
|
||||
iter.remove();
|
||||
closeConnection(entry.getConnection());
|
||||
}
|
||||
idleConnHandler.removeAll();
|
||||
|
||||
isShutDown = true;
|
||||
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Closes a connection from this pool.
|
||||
*
|
||||
* @param conn the connection to close, or {@code null}
|
||||
*/
|
||||
protected void closeConnection(final OperatedClientConnection conn) {
|
||||
if (conn != null) {
|
||||
try {
|
||||
conn.close();
|
||||
} catch (final IOException ex) {
|
||||
log.debug("I/O error closing connection", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // class AbstractConnPool
|
||||
|
|
@ -1,163 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn.tsccm;
|
||||
|
||||
import java.lang.ref.ReferenceQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.http.conn.ClientConnectionOperator;
|
||||
import org.apache.http.conn.OperatedClientConnection;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.impl.conn.AbstractPoolEntry;
|
||||
import org.apache.http.util.Args;
|
||||
|
||||
/**
|
||||
* Basic implementation of a connection pool entry.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.2) use {@link org.apache.http.pool.PoolEntry}
|
||||
*/
|
||||
@Deprecated
|
||||
public class BasicPoolEntry extends AbstractPoolEntry {
|
||||
|
||||
private final long created;
|
||||
|
||||
private long updated;
|
||||
private final long validUntil;
|
||||
private long expiry;
|
||||
|
||||
public BasicPoolEntry(final ClientConnectionOperator op,
|
||||
final HttpRoute route,
|
||||
final ReferenceQueue<Object> queue) {
|
||||
super(op, route);
|
||||
Args.notNull(route, "HTTP route");
|
||||
this.created = System.currentTimeMillis();
|
||||
this.validUntil = Long.MAX_VALUE;
|
||||
this.expiry = this.validUntil;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new pool entry.
|
||||
*
|
||||
* @param op the connection operator
|
||||
* @param route the planned route for the connection
|
||||
*/
|
||||
public BasicPoolEntry(final ClientConnectionOperator op,
|
||||
final HttpRoute route) {
|
||||
this(op, route, -1, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new pool entry with a specified maximum lifetime.
|
||||
*
|
||||
* @param op the connection operator
|
||||
* @param route the planned route for the connection
|
||||
* @param connTTL maximum lifetime of this entry, <=0 implies "infinity"
|
||||
* @param timeunit TimeUnit of connTTL
|
||||
*
|
||||
* @since 4.1
|
||||
*/
|
||||
public BasicPoolEntry(final ClientConnectionOperator op,
|
||||
final HttpRoute route, final long connTTL, final TimeUnit timeunit) {
|
||||
super(op, route);
|
||||
Args.notNull(route, "HTTP route");
|
||||
this.created = System.currentTimeMillis();
|
||||
if (connTTL > 0) {
|
||||
this.validUntil = this.created + timeunit.toMillis(connTTL);
|
||||
} else {
|
||||
this.validUntil = Long.MAX_VALUE;
|
||||
}
|
||||
this.expiry = this.validUntil;
|
||||
}
|
||||
|
||||
protected final OperatedClientConnection getConnection() {
|
||||
return super.connection;
|
||||
}
|
||||
|
||||
protected final HttpRoute getPlannedRoute() {
|
||||
return super.route;
|
||||
}
|
||||
|
||||
protected final BasicPoolEntryRef getWeakRef() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void shutdownEntry() {
|
||||
super.shutdownEntry();
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public long getCreated() {
|
||||
return this.created;
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public long getUpdated() {
|
||||
return this.updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public long getExpiry() {
|
||||
return this.expiry;
|
||||
}
|
||||
|
||||
public long getValidUntil() {
|
||||
return this.validUntil;
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public void updateExpiry(final long time, final TimeUnit timeunit) {
|
||||
this.updated = System.currentTimeMillis();
|
||||
final long newExpiry;
|
||||
if (time > 0) {
|
||||
newExpiry = this.updated + timeunit.toMillis(time);
|
||||
} else {
|
||||
newExpiry = Long.MAX_VALUE;
|
||||
}
|
||||
this.expiry = Math.min(validUntil, newExpiry);
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public boolean isExpired(final long now) {
|
||||
return now >= this.expiry;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -1,76 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn.tsccm;
|
||||
|
||||
import java.lang.ref.ReferenceQueue;
|
||||
import java.lang.ref.WeakReference;
|
||||
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.util.Args;
|
||||
|
||||
/**
|
||||
* A weak reference to a {@link BasicPoolEntry BasicPoolEntry}.
|
||||
* This reference explicitly keeps the planned route, so the connection
|
||||
* can be reclaimed if it is lost to garbage collection.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.2) do not use
|
||||
*/
|
||||
@Deprecated
|
||||
public class BasicPoolEntryRef extends WeakReference<BasicPoolEntry> {
|
||||
|
||||
/** The planned route of the entry. */
|
||||
private final HttpRoute route; // HttpRoute is @Immutable
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new reference to a pool entry.
|
||||
*
|
||||
* @param entry the pool entry, must not be {@code null}
|
||||
* @param queue the reference queue, or {@code null}
|
||||
*/
|
||||
public BasicPoolEntryRef(final BasicPoolEntry entry,
|
||||
final ReferenceQueue<Object> queue) {
|
||||
super(entry, queue);
|
||||
Args.notNull(entry, "Pool entry");
|
||||
route = entry.getPlannedRoute();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Obtain the planned route for the referenced entry.
|
||||
* The planned route is still available, even if the entry is gone.
|
||||
*
|
||||
* @return the planned route
|
||||
*/
|
||||
public final HttpRoute getRoute() {
|
||||
return this.route;
|
||||
}
|
||||
|
||||
} // class BasicPoolEntryRef
|
||||
|
|
@ -1,75 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn.tsccm;
|
||||
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.impl.conn.AbstractPoolEntry;
|
||||
import org.apache.http.impl.conn.AbstractPooledConnAdapter;
|
||||
|
||||
/**
|
||||
* A connection wrapper and callback handler.
|
||||
* All connections given out by the manager are wrappers which
|
||||
* can be {@link #detach detach}ed to prevent further use on release.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.2) do not use
|
||||
*/
|
||||
@Deprecated
|
||||
public class BasicPooledConnAdapter extends AbstractPooledConnAdapter {
|
||||
|
||||
/**
|
||||
* Creates a new adapter.
|
||||
*
|
||||
* @param tsccm the connection manager
|
||||
* @param entry the pool entry for the connection being wrapped
|
||||
*/
|
||||
protected BasicPooledConnAdapter(final ThreadSafeClientConnManager tsccm,
|
||||
final AbstractPoolEntry entry) {
|
||||
super(tsccm, entry);
|
||||
markReusable();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ClientConnectionManager getManager() {
|
||||
// override needed only to make method visible in this package
|
||||
return super.getManager();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AbstractPoolEntry getPoolEntry() {
|
||||
// override needed only to make method visible in this package
|
||||
return super.getPoolEntry();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void detach() {
|
||||
// override needed only to make method visible in this package
|
||||
super.detach();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,829 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn.tsccm;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.Condition;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.conn.ClientConnectionOperator;
|
||||
import org.apache.http.conn.ConnectionPoolTimeoutException;
|
||||
import org.apache.http.conn.OperatedClientConnection;
|
||||
import org.apache.http.conn.params.ConnManagerParams;
|
||||
import org.apache.http.conn.params.ConnPerRoute;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.util.Args;
|
||||
import org.apache.http.util.Asserts;
|
||||
|
||||
/**
|
||||
* A connection pool that maintains connections by route.
|
||||
* This class is derived from {@code MultiThreadedHttpConnectionManager}
|
||||
* in HttpClient 3.x, see there for original authors. It implements the same
|
||||
* algorithm for connection re-use and connection-per-host enforcement:
|
||||
* <ul>
|
||||
* <li>connections are re-used only for the exact same route</li>
|
||||
* <li>connection limits are enforced per route rather than per host</li>
|
||||
* </ul>
|
||||
* Note that access to the pool data structures is synchronized via the
|
||||
* {@link AbstractConnPool#poolLock poolLock} in the base class,
|
||||
* not via {@code synchronized} methods.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.2) use {@link org.apache.http.pool.AbstractConnPool}
|
||||
*/
|
||||
@Deprecated
|
||||
public class ConnPoolByRoute extends AbstractConnPool {
|
||||
|
||||
private final Log log = LogFactory.getLog(getClass());
|
||||
|
||||
private final Lock poolLock;
|
||||
|
||||
/** Connection operator for this pool */
|
||||
protected final ClientConnectionOperator operator;
|
||||
|
||||
/** Connections per route lookup */
|
||||
protected final ConnPerRoute connPerRoute;
|
||||
|
||||
/** References to issued connections */
|
||||
protected final Set<BasicPoolEntry> leasedConnections;
|
||||
|
||||
/** The list of free connections */
|
||||
protected final Queue<BasicPoolEntry> freeConnections;
|
||||
|
||||
/** The list of WaitingThreads waiting for a connection */
|
||||
protected final Queue<WaitingThread> waitingThreads;
|
||||
|
||||
/** Map of route-specific pools */
|
||||
protected final Map<HttpRoute, RouteSpecificPool> routeToPool;
|
||||
|
||||
private final long connTTL;
|
||||
|
||||
private final TimeUnit connTTLTimeUnit;
|
||||
|
||||
protected volatile boolean shutdown;
|
||||
|
||||
protected volatile int maxTotalConnections;
|
||||
|
||||
protected volatile int numConnections;
|
||||
|
||||
/**
|
||||
* Creates a new connection pool, managed by route.
|
||||
*
|
||||
* @since 4.1
|
||||
*/
|
||||
public ConnPoolByRoute(
|
||||
final ClientConnectionOperator operator,
|
||||
final ConnPerRoute connPerRoute,
|
||||
final int maxTotalConnections) {
|
||||
this(operator, connPerRoute, maxTotalConnections, -1, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.1
|
||||
*/
|
||||
public ConnPoolByRoute(
|
||||
final ClientConnectionOperator operator,
|
||||
final ConnPerRoute connPerRoute,
|
||||
final int maxTotalConnections,
|
||||
final long connTTL,
|
||||
final TimeUnit connTTLTimeUnit) {
|
||||
super();
|
||||
Args.notNull(operator, "Connection operator");
|
||||
Args.notNull(connPerRoute, "Connections per route");
|
||||
this.poolLock = super.poolLock;
|
||||
this.leasedConnections = super.leasedConnections;
|
||||
this.operator = operator;
|
||||
this.connPerRoute = connPerRoute;
|
||||
this.maxTotalConnections = maxTotalConnections;
|
||||
this.freeConnections = createFreeConnQueue();
|
||||
this.waitingThreads = createWaitingThreadQueue();
|
||||
this.routeToPool = createRouteToPoolMap();
|
||||
this.connTTL = connTTL;
|
||||
this.connTTLTimeUnit = connTTLTimeUnit;
|
||||
}
|
||||
|
||||
protected Lock getLock() {
|
||||
return this.poolLock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new connection pool, managed by route.
|
||||
*
|
||||
* @deprecated (4.1) use {@link ConnPoolByRoute#ConnPoolByRoute(ClientConnectionOperator, ConnPerRoute, int)}
|
||||
*/
|
||||
@Deprecated
|
||||
public ConnPoolByRoute(final ClientConnectionOperator operator, final HttpParams params) {
|
||||
this(operator,
|
||||
ConnManagerParams.getMaxConnectionsPerRoute(params),
|
||||
ConnManagerParams.getMaxTotalConnections(params));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the queue for {@link #freeConnections}.
|
||||
* Called once by the constructor.
|
||||
*
|
||||
* @return a queue
|
||||
*/
|
||||
protected Queue<BasicPoolEntry> createFreeConnQueue() {
|
||||
return new LinkedList<BasicPoolEntry>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the queue for {@link #waitingThreads}.
|
||||
* Called once by the constructor.
|
||||
*
|
||||
* @return a queue
|
||||
*/
|
||||
protected Queue<WaitingThread> createWaitingThreadQueue() {
|
||||
return new LinkedList<WaitingThread>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the map for {@link #routeToPool}.
|
||||
* Called once by the constructor.
|
||||
*
|
||||
* @return a map
|
||||
*/
|
||||
protected Map<HttpRoute, RouteSpecificPool> createRouteToPoolMap() {
|
||||
return new HashMap<HttpRoute, RouteSpecificPool>();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new route-specific pool.
|
||||
* Called by {@link #getRoutePool} when necessary.
|
||||
*
|
||||
* @param route the route
|
||||
*
|
||||
* @return the new pool
|
||||
*/
|
||||
protected RouteSpecificPool newRouteSpecificPool(final HttpRoute route) {
|
||||
return new RouteSpecificPool(route, this.connPerRoute);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new waiting thread.
|
||||
* Called by {@link #getRoutePool} when necessary.
|
||||
*
|
||||
* @param cond the condition to wait for
|
||||
* @param rospl the route specific pool, or {@code null}
|
||||
*
|
||||
* @return a waiting thread representation
|
||||
*/
|
||||
protected WaitingThread newWaitingThread(final Condition cond,
|
||||
final RouteSpecificPool rospl) {
|
||||
return new WaitingThread(cond, rospl);
|
||||
}
|
||||
|
||||
private void closeConnection(final BasicPoolEntry entry) {
|
||||
final OperatedClientConnection conn = entry.getConnection();
|
||||
if (conn != null) {
|
||||
try {
|
||||
conn.close();
|
||||
} catch (final IOException ex) {
|
||||
log.debug("I/O error closing connection", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a route-specific pool of available connections.
|
||||
*
|
||||
* @param route the route
|
||||
* @param create whether to create the pool if it doesn't exist
|
||||
*
|
||||
* @return the pool for the argument route,
|
||||
* never {@code null} if {@code create} is {@code true}
|
||||
*/
|
||||
protected RouteSpecificPool getRoutePool(final HttpRoute route,
|
||||
final boolean create) {
|
||||
RouteSpecificPool rospl = null;
|
||||
poolLock.lock();
|
||||
try {
|
||||
|
||||
rospl = routeToPool.get(route);
|
||||
if ((rospl == null) && create) {
|
||||
// no pool for this route yet (or anymore)
|
||||
rospl = newRouteSpecificPool(route);
|
||||
routeToPool.put(route, rospl);
|
||||
}
|
||||
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
|
||||
return rospl;
|
||||
}
|
||||
|
||||
public int getConnectionsInPool(final HttpRoute route) {
|
||||
poolLock.lock();
|
||||
try {
|
||||
// don't allow a pool to be created here!
|
||||
final RouteSpecificPool rospl = getRoutePool(route, false);
|
||||
return (rospl != null) ? rospl.getEntryCount() : 0;
|
||||
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public int getConnectionsInPool() {
|
||||
poolLock.lock();
|
||||
try {
|
||||
return numConnections;
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PoolEntryRequest requestPoolEntry(
|
||||
final HttpRoute route,
|
||||
final Object state) {
|
||||
|
||||
final WaitingThreadAborter aborter = new WaitingThreadAborter();
|
||||
|
||||
return new PoolEntryRequest() {
|
||||
|
||||
public void abortRequest() {
|
||||
poolLock.lock();
|
||||
try {
|
||||
aborter.abort();
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public BasicPoolEntry getPoolEntry(
|
||||
final long timeout,
|
||||
final TimeUnit tunit)
|
||||
throws InterruptedException, ConnectionPoolTimeoutException {
|
||||
return getEntryBlocking(route, state, timeout, tunit, aborter);
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains a pool entry with a connection within the given timeout.
|
||||
* If a {@link WaitingThread} is used to block, {@link WaitingThreadAborter#setWaitingThread(WaitingThread)}
|
||||
* must be called before blocking, to allow the thread to be interrupted.
|
||||
*
|
||||
* @param route the route for which to get the connection
|
||||
* @param timeout the timeout, 0 or negative for no timeout
|
||||
* @param tunit the unit for the {@code timeout},
|
||||
* may be {@code null} only if there is no timeout
|
||||
* @param aborter an object which can abort a {@link WaitingThread}.
|
||||
*
|
||||
* @return pool entry holding a connection for the route
|
||||
*
|
||||
* @throws ConnectionPoolTimeoutException
|
||||
* if the timeout expired
|
||||
* @throws InterruptedException
|
||||
* if the calling thread was interrupted
|
||||
*/
|
||||
protected BasicPoolEntry getEntryBlocking(
|
||||
final HttpRoute route, final Object state,
|
||||
final long timeout, final TimeUnit tunit,
|
||||
final WaitingThreadAborter aborter)
|
||||
throws ConnectionPoolTimeoutException, InterruptedException {
|
||||
|
||||
Date deadline = null;
|
||||
if (timeout > 0) {
|
||||
deadline = new Date
|
||||
(System.currentTimeMillis() + tunit.toMillis(timeout));
|
||||
}
|
||||
|
||||
BasicPoolEntry entry = null;
|
||||
poolLock.lock();
|
||||
try {
|
||||
|
||||
RouteSpecificPool rospl = getRoutePool(route, true);
|
||||
WaitingThread waitingThread = null;
|
||||
|
||||
while (entry == null) {
|
||||
Asserts.check(!shutdown, "Connection pool shut down");
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("[" + route + "] total kept alive: " + freeConnections.size() +
|
||||
", total issued: " + leasedConnections.size() +
|
||||
", total allocated: " + numConnections + " out of " + maxTotalConnections);
|
||||
}
|
||||
|
||||
// the cases to check for:
|
||||
// - have a free connection for that route
|
||||
// - allowed to create a free connection for that route
|
||||
// - can delete and replace a free connection for another route
|
||||
// - need to wait for one of the things above to come true
|
||||
|
||||
entry = getFreeEntry(rospl, state);
|
||||
if (entry != null) {
|
||||
break;
|
||||
}
|
||||
|
||||
final boolean hasCapacity = rospl.getCapacity() > 0;
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Available capacity: " + rospl.getCapacity()
|
||||
+ " out of " + rospl.getMaxEntries()
|
||||
+ " [" + route + "][" + state + "]");
|
||||
}
|
||||
|
||||
if (hasCapacity && numConnections < maxTotalConnections) {
|
||||
|
||||
entry = createEntry(rospl, operator);
|
||||
|
||||
} else if (hasCapacity && !freeConnections.isEmpty()) {
|
||||
|
||||
deleteLeastUsedEntry();
|
||||
// if least used entry's route was the same as rospl,
|
||||
// rospl is now out of date : we preemptively refresh
|
||||
rospl = getRoutePool(route, true);
|
||||
entry = createEntry(rospl, operator);
|
||||
|
||||
} else {
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Need to wait for connection" +
|
||||
" [" + route + "][" + state + "]");
|
||||
}
|
||||
|
||||
if (waitingThread == null) {
|
||||
waitingThread =
|
||||
newWaitingThread(poolLock.newCondition(), rospl);
|
||||
aborter.setWaitingThread(waitingThread);
|
||||
}
|
||||
|
||||
boolean success = false;
|
||||
try {
|
||||
rospl.queueThread(waitingThread);
|
||||
waitingThreads.add(waitingThread);
|
||||
success = waitingThread.await(deadline);
|
||||
|
||||
} finally {
|
||||
// In case of 'success', we were woken up by the
|
||||
// connection pool and should now have a connection
|
||||
// waiting for us, or else we're shutting down.
|
||||
// Just continue in the loop, both cases are checked.
|
||||
rospl.removeThread(waitingThread);
|
||||
waitingThreads.remove(waitingThread);
|
||||
}
|
||||
|
||||
// check for spurious wakeup vs. timeout
|
||||
if (!success && (deadline != null) &&
|
||||
(deadline.getTime() <= System.currentTimeMillis())) {
|
||||
throw new ConnectionPoolTimeoutException
|
||||
("Timeout waiting for connection from pool");
|
||||
}
|
||||
}
|
||||
} // while no entry
|
||||
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void freeEntry(final BasicPoolEntry entry, final boolean reusable, final long validDuration, final TimeUnit timeUnit) {
|
||||
|
||||
final HttpRoute route = entry.getPlannedRoute();
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Releasing connection" +
|
||||
" [" + route + "][" + entry.getState() + "]");
|
||||
}
|
||||
|
||||
poolLock.lock();
|
||||
try {
|
||||
if (shutdown) {
|
||||
// the pool is shut down, release the
|
||||
// connection's resources and get out of here
|
||||
closeConnection(entry);
|
||||
return;
|
||||
}
|
||||
|
||||
// no longer issued, we keep a hard reference now
|
||||
leasedConnections.remove(entry);
|
||||
|
||||
final RouteSpecificPool rospl = getRoutePool(route, true);
|
||||
|
||||
if (reusable && rospl.getCapacity() >= 0) {
|
||||
if (log.isDebugEnabled()) {
|
||||
final String s;
|
||||
if (validDuration > 0) {
|
||||
s = "for " + validDuration + " " + timeUnit;
|
||||
} else {
|
||||
s = "indefinitely";
|
||||
}
|
||||
log.debug("Pooling connection" +
|
||||
" [" + route + "][" + entry.getState() + "]; keep alive " + s);
|
||||
}
|
||||
rospl.freeEntry(entry);
|
||||
entry.updateExpiry(validDuration, timeUnit);
|
||||
freeConnections.add(entry);
|
||||
} else {
|
||||
closeConnection(entry);
|
||||
rospl.dropEntry();
|
||||
numConnections--;
|
||||
}
|
||||
|
||||
notifyWaitingThread(rospl);
|
||||
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If available, get a free pool entry for a route.
|
||||
*
|
||||
* @param rospl the route-specific pool from which to get an entry
|
||||
*
|
||||
* @return an available pool entry for the given route, or
|
||||
* {@code null} if none is available
|
||||
*/
|
||||
protected BasicPoolEntry getFreeEntry(final RouteSpecificPool rospl, final Object state) {
|
||||
|
||||
BasicPoolEntry entry = null;
|
||||
poolLock.lock();
|
||||
try {
|
||||
boolean done = false;
|
||||
while(!done) {
|
||||
|
||||
entry = rospl.allocEntry(state);
|
||||
|
||||
if (entry != null) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Getting free connection"
|
||||
+ " [" + rospl.getRoute() + "][" + state + "]");
|
||||
|
||||
}
|
||||
freeConnections.remove(entry);
|
||||
if (entry.isExpired(System.currentTimeMillis())) {
|
||||
// If the free entry isn't valid anymore, get rid of it
|
||||
// and loop to find another one that might be valid.
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Closing expired free connection"
|
||||
+ " [" + rospl.getRoute() + "][" + state + "]");
|
||||
}
|
||||
closeConnection(entry);
|
||||
// We use dropEntry instead of deleteEntry because the entry
|
||||
// is no longer "free" (we just allocated it), and deleteEntry
|
||||
// can only be used to delete free entries.
|
||||
rospl.dropEntry();
|
||||
numConnections--;
|
||||
} else {
|
||||
leasedConnections.add(entry);
|
||||
done = true;
|
||||
}
|
||||
|
||||
} else {
|
||||
done = true;
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("No free connections"
|
||||
+ " [" + rospl.getRoute() + "][" + state + "]");
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new pool entry.
|
||||
* This method assumes that the new connection will be handed
|
||||
* out immediately.
|
||||
*
|
||||
* @param rospl the route-specific pool for which to create the entry
|
||||
* @param op the operator for creating a connection
|
||||
*
|
||||
* @return the new pool entry for a new connection
|
||||
*/
|
||||
protected BasicPoolEntry createEntry(final RouteSpecificPool rospl,
|
||||
final ClientConnectionOperator op) {
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Creating new connection [" + rospl.getRoute() + "]");
|
||||
}
|
||||
|
||||
// the entry will create the connection when needed
|
||||
final BasicPoolEntry entry = new BasicPoolEntry(op, rospl.getRoute(), connTTL, connTTLTimeUnit);
|
||||
|
||||
poolLock.lock();
|
||||
try {
|
||||
rospl.createdEntry(entry);
|
||||
numConnections++;
|
||||
leasedConnections.add(entry);
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
|
||||
return entry;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Deletes a given pool entry.
|
||||
* This closes the pooled connection and removes all references,
|
||||
* so that it can be GCed.
|
||||
*
|
||||
* <p><b>Note:</b> Does not remove the entry from the freeConnections list.
|
||||
* It is assumed that the caller has already handled this step.</p>
|
||||
* <!-- @@@ is that a good idea? or rather fix it? -->
|
||||
*
|
||||
* @param entry the pool entry for the connection to delete
|
||||
*/
|
||||
protected void deleteEntry(final BasicPoolEntry entry) {
|
||||
|
||||
final HttpRoute route = entry.getPlannedRoute();
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Deleting connection"
|
||||
+ " [" + route + "][" + entry.getState() + "]");
|
||||
}
|
||||
|
||||
poolLock.lock();
|
||||
try {
|
||||
|
||||
closeConnection(entry);
|
||||
|
||||
final RouteSpecificPool rospl = getRoutePool(route, true);
|
||||
rospl.deleteEntry(entry);
|
||||
numConnections--;
|
||||
if (rospl.isUnused()) {
|
||||
routeToPool.remove(route);
|
||||
}
|
||||
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Delete an old, free pool entry to make room for a new one.
|
||||
* Used to replace pool entries with ones for a different route.
|
||||
*/
|
||||
protected void deleteLeastUsedEntry() {
|
||||
poolLock.lock();
|
||||
try {
|
||||
|
||||
final BasicPoolEntry entry = freeConnections.remove();
|
||||
|
||||
if (entry != null) {
|
||||
deleteEntry(entry);
|
||||
} else if (log.isDebugEnabled()) {
|
||||
log.debug("No free connection to delete");
|
||||
}
|
||||
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void handleLostEntry(final HttpRoute route) {
|
||||
|
||||
poolLock.lock();
|
||||
try {
|
||||
|
||||
final RouteSpecificPool rospl = getRoutePool(route, true);
|
||||
rospl.dropEntry();
|
||||
if (rospl.isUnused()) {
|
||||
routeToPool.remove(route);
|
||||
}
|
||||
|
||||
numConnections--;
|
||||
notifyWaitingThread(rospl);
|
||||
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Notifies a waiting thread that a connection is available.
|
||||
* This will wake a thread waiting in the specific route pool,
|
||||
* if there is one.
|
||||
* Otherwise, a thread in the connection pool will be notified.
|
||||
*
|
||||
* @param rospl the pool in which to notify, or {@code null}
|
||||
*/
|
||||
protected void notifyWaitingThread(final RouteSpecificPool rospl) {
|
||||
|
||||
//@@@ while this strategy provides for best connection re-use,
|
||||
//@@@ is it fair? only do this if the connection is open?
|
||||
// Find the thread we are going to notify. We want to ensure that
|
||||
// each waiting thread is only interrupted once, so we will remove
|
||||
// it from all wait queues before interrupting.
|
||||
WaitingThread waitingThread = null;
|
||||
|
||||
poolLock.lock();
|
||||
try {
|
||||
|
||||
if ((rospl != null) && rospl.hasThread()) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Notifying thread waiting on pool" +
|
||||
" [" + rospl.getRoute() + "]");
|
||||
}
|
||||
waitingThread = rospl.nextThread();
|
||||
} else if (!waitingThreads.isEmpty()) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Notifying thread waiting on any pool");
|
||||
}
|
||||
waitingThread = waitingThreads.remove();
|
||||
} else if (log.isDebugEnabled()) {
|
||||
log.debug("Notifying no-one, there are no waiting threads");
|
||||
}
|
||||
|
||||
if (waitingThread != null) {
|
||||
waitingThread.wakeup();
|
||||
}
|
||||
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void deleteClosedConnections() {
|
||||
poolLock.lock();
|
||||
try {
|
||||
final Iterator<BasicPoolEntry> iter = freeConnections.iterator();
|
||||
while (iter.hasNext()) {
|
||||
final BasicPoolEntry entry = iter.next();
|
||||
if (!entry.getConnection().isOpen()) {
|
||||
iter.remove();
|
||||
deleteEntry(entry);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes idle connections.
|
||||
*
|
||||
* @param idletime the time the connections should have been idle
|
||||
* in order to be closed now
|
||||
* @param tunit the unit for the {@code idletime}
|
||||
*/
|
||||
@Override
|
||||
public void closeIdleConnections(final long idletime, final TimeUnit tunit) {
|
||||
Args.notNull(tunit, "Time unit");
|
||||
final long t = idletime > 0 ? idletime : 0;
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Closing connections idle longer than " + t + " " + tunit);
|
||||
}
|
||||
// the latest time for which connections will be closed
|
||||
final long deadline = System.currentTimeMillis() - tunit.toMillis(t);
|
||||
poolLock.lock();
|
||||
try {
|
||||
final Iterator<BasicPoolEntry> iter = freeConnections.iterator();
|
||||
while (iter.hasNext()) {
|
||||
final BasicPoolEntry entry = iter.next();
|
||||
if (entry.getUpdated() <= deadline) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Closing connection last used @ " + new Date(entry.getUpdated()));
|
||||
}
|
||||
iter.remove();
|
||||
deleteEntry(entry);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void closeExpiredConnections() {
|
||||
log.debug("Closing expired connections");
|
||||
final long now = System.currentTimeMillis();
|
||||
|
||||
poolLock.lock();
|
||||
try {
|
||||
final Iterator<BasicPoolEntry> iter = freeConnections.iterator();
|
||||
while (iter.hasNext()) {
|
||||
final BasicPoolEntry entry = iter.next();
|
||||
if (entry.isExpired(now)) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Closing connection expired @ " + new Date(entry.getExpiry()));
|
||||
}
|
||||
iter.remove();
|
||||
deleteEntry(entry);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
poolLock.lock();
|
||||
try {
|
||||
if (shutdown) {
|
||||
return;
|
||||
}
|
||||
shutdown = true;
|
||||
|
||||
// close all connections that are issued to an application
|
||||
final Iterator<BasicPoolEntry> iter1 = leasedConnections.iterator();
|
||||
while (iter1.hasNext()) {
|
||||
final BasicPoolEntry entry = iter1.next();
|
||||
iter1.remove();
|
||||
closeConnection(entry);
|
||||
}
|
||||
|
||||
// close all free connections
|
||||
final Iterator<BasicPoolEntry> iter2 = freeConnections.iterator();
|
||||
while (iter2.hasNext()) {
|
||||
final BasicPoolEntry entry = iter2.next();
|
||||
iter2.remove();
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Closing connection"
|
||||
+ " [" + entry.getPlannedRoute() + "][" + entry.getState() + "]");
|
||||
}
|
||||
closeConnection(entry);
|
||||
}
|
||||
|
||||
// wake up all waiting threads
|
||||
final Iterator<WaitingThread> iwth = waitingThreads.iterator();
|
||||
while (iwth.hasNext()) {
|
||||
final WaitingThread waiter = iwth.next();
|
||||
iwth.remove();
|
||||
waiter.wakeup();
|
||||
}
|
||||
|
||||
routeToPool.clear();
|
||||
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* since 4.1
|
||||
*/
|
||||
public void setMaxTotalConnections(final int max) {
|
||||
poolLock.lock();
|
||||
try {
|
||||
maxTotalConnections = max;
|
||||
} finally {
|
||||
poolLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* since 4.1
|
||||
*/
|
||||
public int getMaxTotalConnections() {
|
||||
return maxTotalConnections;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,69 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn.tsccm;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.http.conn.ConnectionPoolTimeoutException;
|
||||
|
||||
/**
|
||||
* Encapsulates a request for a {@link BasicPoolEntry}.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.2) use {@link java.util.concurrent.Future}
|
||||
*/
|
||||
@Deprecated
|
||||
public interface PoolEntryRequest {
|
||||
|
||||
/**
|
||||
* Obtains a pool entry with a connection within the given timeout.
|
||||
* If {@link #abortRequest()} is called before this completes
|
||||
* an {@link InterruptedException} is thrown.
|
||||
*
|
||||
* @param timeout the timeout, 0 or negative for no timeout
|
||||
* @param tunit the unit for the {@code timeout},
|
||||
* may be {@code null} only if there is no timeout
|
||||
*
|
||||
* @return pool entry holding a connection for the route
|
||||
*
|
||||
* @throws ConnectionPoolTimeoutException
|
||||
* if the timeout expired
|
||||
* @throws InterruptedException
|
||||
* if the calling thread was interrupted or the request was aborted
|
||||
*/
|
||||
BasicPoolEntry getPoolEntry(
|
||||
long timeout,
|
||||
TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException;
|
||||
|
||||
/**
|
||||
* Aborts the active or next call to
|
||||
* {@link #getPoolEntry(long, TimeUnit)}.
|
||||
*/
|
||||
void abortRequest();
|
||||
|
||||
}
|
|
@ -1,313 +0,0 @@
|
|||
/*
|
||||
* ====================================================================
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
* ====================================================================
|
||||
*
|
||||
* This software consists 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.http.impl.conn.tsccm;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.LinkedList;
|
||||
import java.util.ListIterator;
|
||||
import java.util.Queue;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.conn.OperatedClientConnection;
|
||||
import org.apache.http.conn.params.ConnPerRoute;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.util.Args;
|
||||
import org.apache.http.util.Asserts;
|
||||
import org.apache.http.util.LangUtils;
|
||||
|
||||
|
||||
/**
|
||||
* A connection sub-pool for a specific route, used by {@link ConnPoolByRoute}.
|
||||
* The methods in this class are unsynchronized. It is expected that the
|
||||
* containing pool takes care of synchronization.
|
||||
*
|
||||
* @since 4.0
|
||||
*
|
||||
* @deprecated (4.2) use {@link org.apache.http.pool.AbstractConnPool}
|
||||
*/
|
||||
@Deprecated
|
||||
public class RouteSpecificPool {
|
||||
|
||||
private final Log log = LogFactory.getLog(getClass());
|
||||
|
||||
/** The route this pool is for. */
|
||||
protected final HttpRoute route; //Immutable
|
||||
|
||||
protected final int maxEntries;
|
||||
|
||||
/** Connections per route */
|
||||
protected final ConnPerRoute connPerRoute;
|
||||
|
||||
/**
|
||||
* The list of free entries.
|
||||
* This list is managed LIFO, to increase idle times and
|
||||
* allow for closing connections that are not really needed.
|
||||
*/
|
||||
protected final LinkedList<BasicPoolEntry> freeEntries;
|
||||
|
||||
/** The list of threads waiting for this pool. */
|
||||
protected final Queue<WaitingThread> waitingThreads;
|
||||
|
||||
/** The number of created entries. */
|
||||
protected int numEntries;
|
||||
|
||||
/**
|
||||
* @deprecated (4.1) use {@link RouteSpecificPool#RouteSpecificPool(HttpRoute, ConnPerRoute)}
|
||||
*/
|
||||
@Deprecated
|
||||
public RouteSpecificPool(final HttpRoute route, final int maxEntries) {
|
||||
this.route = route;
|
||||
this.maxEntries = maxEntries;
|
||||
this.connPerRoute = new ConnPerRoute() {
|
||||
public int getMaxForRoute(final HttpRoute unused) {
|
||||
return RouteSpecificPool.this.maxEntries;
|
||||
}
|
||||
};
|
||||
this.freeEntries = new LinkedList<BasicPoolEntry>();
|
||||
this.waitingThreads = new LinkedList<WaitingThread>();
|
||||
this.numEntries = 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new route-specific pool.
|
||||
*
|
||||
* @param route the route for which to pool
|
||||
* @param connPerRoute the connections per route configuration
|
||||
*/
|
||||
public RouteSpecificPool(final HttpRoute route, final ConnPerRoute connPerRoute) {
|
||||
this.route = route;
|
||||
this.connPerRoute = connPerRoute;
|
||||
this.maxEntries = connPerRoute.getMaxForRoute(route);
|
||||
this.freeEntries = new LinkedList<BasicPoolEntry>();
|
||||
this.waitingThreads = new LinkedList<WaitingThread>();
|
||||
this.numEntries = 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Obtains the route for which this pool is specific.
|
||||
*
|
||||
* @return the route
|
||||
*/
|
||||
public final HttpRoute getRoute() {
|
||||
return route;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Obtains the maximum number of entries allowed for this pool.
|
||||
*
|
||||
* @return the max entry number
|
||||
*/
|
||||
public final int getMaxEntries() {
|
||||
return maxEntries;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Indicates whether this pool is unused.
|
||||
* A pool is unused if there is neither an entry nor a waiting thread.
|
||||
* All entries count, not only the free but also the allocated ones.
|
||||
*
|
||||
* @return {@code true} if this pool is unused,
|
||||
* {@code false} otherwise
|
||||
*/
|
||||
public boolean isUnused() {
|
||||
return (numEntries < 1) && waitingThreads.isEmpty();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Return remaining capacity of this pool
|
||||
*
|
||||
* @return capacity
|
||||
*/
|
||||
public int getCapacity() {
|
||||
return connPerRoute.getMaxForRoute(route) - numEntries;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Obtains the number of entries.
|
||||
* This includes not only the free entries, but also those that
|
||||
* have been created and are currently issued to an application.
|
||||
*
|
||||
* @return the number of entries for the route of this pool
|
||||
*/
|
||||
public final int getEntryCount() {
|
||||
return numEntries;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Obtains a free entry from this pool, if one is available.
|
||||
*
|
||||
* @return an available pool entry, or {@code null} if there is none
|
||||
*/
|
||||
public BasicPoolEntry allocEntry(final Object state) {
|
||||
if (!freeEntries.isEmpty()) {
|
||||
final ListIterator<BasicPoolEntry> it = freeEntries.listIterator(freeEntries.size());
|
||||
while (it.hasPrevious()) {
|
||||
final BasicPoolEntry entry = it.previous();
|
||||
if (entry.getState() == null || LangUtils.equals(state, entry.getState())) {
|
||||
it.remove();
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (getCapacity() == 0 && !freeEntries.isEmpty()) {
|
||||
final BasicPoolEntry entry = freeEntries.remove();
|
||||
entry.shutdownEntry();
|
||||
final OperatedClientConnection conn = entry.getConnection();
|
||||
try {
|
||||
conn.close();
|
||||
} catch (final IOException ex) {
|
||||
log.debug("I/O error closing connection", ex);
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns an allocated entry to this pool.
|
||||
*
|
||||
* @param entry the entry obtained from {@link #allocEntry allocEntry}
|
||||
* or presented to {@link #createdEntry createdEntry}
|
||||
*/
|
||||
public void freeEntry(final BasicPoolEntry entry) {
|
||||
if (numEntries < 1) {
|
||||
throw new IllegalStateException
|
||||
("No entry created for this pool. " + route);
|
||||
}
|
||||
if (numEntries <= freeEntries.size()) {
|
||||
throw new IllegalStateException
|
||||
("No entry allocated from this pool. " + route);
|
||||
}
|
||||
freeEntries.add(entry);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Indicates creation of an entry for this pool.
|
||||
* The entry will <i>not</i> be added to the list of free entries,
|
||||
* it is only recognized as belonging to this pool now. It can then
|
||||
* be passed to {@link #freeEntry freeEntry}.
|
||||
*
|
||||
* @param entry the entry that was created for this pool
|
||||
*/
|
||||
public void createdEntry(final BasicPoolEntry entry) {
|
||||
Args.check(route.equals(entry.getPlannedRoute()), "Entry not planned for this pool");
|
||||
numEntries++;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Deletes an entry from this pool.
|
||||
* Only entries that are currently free in this pool can be deleted.
|
||||
* Allocated entries can not be deleted.
|
||||
*
|
||||
* @param entry the entry to delete from this pool
|
||||
*
|
||||
* @return {@code true} if the entry was found and deleted, or
|
||||
* {@code false} if the entry was not found
|
||||
*/
|
||||
public boolean deleteEntry(final BasicPoolEntry entry) {
|
||||
|
||||
final boolean found = freeEntries.remove(entry);
|
||||
if (found) {
|
||||
numEntries--;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Forgets about an entry from this pool.
|
||||
* This method is used to indicate that an entry
|
||||
* {@link #allocEntry allocated}
|
||||
* from this pool has been lost and will not be returned.
|
||||
*/
|
||||
public void dropEntry() {
|
||||
Asserts.check(numEntries > 0, "There is no entry that could be dropped");
|
||||
numEntries--;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Adds a waiting thread.
|
||||
* This pool makes no attempt to match waiting threads with pool entries.
|
||||
* It is the caller's responsibility to check that there is no entry
|
||||
* before adding a waiting thread.
|
||||
*
|
||||
* @param wt the waiting thread
|
||||
*/
|
||||
public void queueThread(final WaitingThread wt) {
|
||||
Args.notNull(wt, "Waiting thread");
|
||||
this.waitingThreads.add(wt);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Checks whether there is a waiting thread in this pool.
|
||||
*
|
||||
* @return {@code true} if there is a waiting thread,
|
||||
* {@code false} otherwise
|
||||
*/
|
||||
public boolean hasThread() {
|
||||
return !this.waitingThreads.isEmpty();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the next thread in the queue.
|
||||
*
|
||||
* @return a waiting thread, or {@code null} if there is none
|
||||
*/
|
||||
public WaitingThread nextThread() {
|
||||
return this.waitingThreads.peek();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Removes a waiting thread, if it is queued.
|
||||
*
|
||||
* @param wt the waiting thread
|
||||
*/
|
||||
public void removeThread(final WaitingThread wt) {
|
||||
if (wt == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.waitingThreads.remove(wt);
|
||||
}
|
||||
|
||||
|
||||
} // class RouteSpecificPool
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue