Redesign of connection management classes based on new pooling components from HttpCore

git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/branches/conn-mgmt-redesign@1154914 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Oleg Kalnichevski 2011-08-08 10:51:10 +00:00
parent c8e15484d3
commit 9b97410b84
41 changed files with 176 additions and 659 deletions

View File

@ -34,7 +34,7 @@ import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.util.EntityUtils;
/**
@ -44,7 +44,7 @@ import org.apache.http.util.EntityUtils;
public class ClientEvictExpiredConnections {
public static void main(String[] args) throws Exception {
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
cm.setMaxTotal(100);
HttpClient httpclient = new DefaultHttpClient(cm);

View File

@ -31,7 +31,7 @@ import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
@ -46,7 +46,7 @@ public class ClientMultiThreadedExecution {
// Create an HttpClient with the ThreadSafeClientConnManager.
// This connection manager must be used if more than one thread will
// be using the HttpClient.
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
cm.setMaxTotal(100);
HttpClient httpclient = new DefaultHttpClient(cm);

View File

@ -1,140 +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.examples.conn;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
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.scheme.SchemeSocketFactory;
import org.apache.http.conn.ClientConnectionRequest;
import org.apache.http.conn.ManagedClientConnection;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.BasicHttpContext;
/**
* How to open a direct connection using
* {@link ClientConnectionManager ClientConnectionManager}.
* This exemplifies the <i>opening</i> of the connection only.
* The subsequent message exchange in this example should not
* be used as a template.
*
* @since 4.0
*/
public class ManagerConnectDirect {
/**
* Main entry point to this example.
*
* @param args ignored
*/
public final static void main(String[] args) throws Exception {
HttpHost target = new HttpHost("www.apache.org", 80, "http");
// Register the "http" protocol scheme, it is required
// by the default operator to look up socket factories.
SchemeRegistry supportedSchemes = new SchemeRegistry();
SchemeSocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", 80, sf));
// Prepare parameters.
// Since this example doesn't use the full core framework,
// only few parameters are actually required.
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUseExpectContinue(params, false);
ClientConnectionManager clcm = new ThreadSafeClientConnManager(supportedSchemes);
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
req.addHeader("Host", target.getHostName());
HttpContext ctx = new BasicHttpContext();
System.out.println("preparing route to " + target);
HttpRoute route = new HttpRoute
(target, null, supportedSchemes.getScheme(target).isLayered());
System.out.println("requesting connection for " + route);
ClientConnectionRequest connRequest = clcm.requestConnection(route, null);
ManagedClientConnection conn = connRequest.getConnection(0, null);
try {
System.out.println("opening connection");
conn.open(route, ctx, params);
System.out.println("sending request");
conn.sendRequestHeader(req);
// there is no request entity
conn.flush();
System.out.println("receiving response header");
HttpResponse rsp = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i=0; i<headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
System.out.println("closing connection");
conn.close();
} finally {
if (conn.isOpen()) {
System.out.println("shutting down connection");
try {
conn.shutdown();
} catch (Exception ex) {
System.out.println("problem during shutdown");
ex.printStackTrace();
}
}
System.out.println("releasing connection");
clcm.releaseConnection(conn, -1, null);
}
}
}

View File

@ -1,176 +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.examples.conn;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.ClientConnectionRequest;
import org.apache.http.conn.ManagedClientConnection;
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;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.BasicHttpContext;
/**
* How to open a secure connection through a proxy using
* {@link ClientConnectionManager ClientConnectionManager}.
* This exemplifies the <i>opening</i> of the connection only.
* The message exchange, both subsequently and for tunnelling,
* should not be used as a template.
*
* @since 4.0
*/
public class ManagerConnectProxy {
/**
* Main entry point to this example.
*
* @param args ignored
*/
public final static void main(String[] args) throws Exception {
// make sure to use a proxy that supports CONNECT
HttpHost target = new HttpHost("issues.apache.org", 443, "https");
HttpHost proxy = new HttpHost("127.0.0.1", 8666, "http");
// Register the "http" and "https" protocol schemes, they are
// required by the default operator to look up socket factories.
SchemeRegistry supportedSchemes = new SchemeRegistry();
supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
supportedSchemes.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
// Prepare parameters.
// Since this example doesn't use the full core framework,
// only few parameters are actually required.
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUseExpectContinue(params, false);
ClientConnectionManager clcm = new ThreadSafeClientConnManager(supportedSchemes);
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
req.addHeader("Host", target.getHostName());
HttpContext ctx = new BasicHttpContext();
System.out.println("preparing route to " + target + " via " + proxy);
HttpRoute route = new HttpRoute
(target, null, proxy,
supportedSchemes.getScheme(target).isLayered());
System.out.println("requesting connection for " + route);
ClientConnectionRequest connRequest = clcm.requestConnection(route, null);
ManagedClientConnection conn = connRequest.getConnection(0, null);
try {
System.out.println("opening connection");
conn.open(route, ctx, params);
String authority = target.getHostName() + ":" + target.getPort();
HttpRequest connect = new BasicHttpRequest("CONNECT", authority, HttpVersion.HTTP_1_1);
connect.addHeader("Host", authority);
System.out.println("opening tunnel to " + target);
conn.sendRequestHeader(connect);
// there is no request entity
conn.flush();
System.out.println("receiving confirmation for tunnel");
HttpResponse connected = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
System.out.println(connected.getStatusLine());
Header[] headers = connected.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
int status = connected.getStatusLine().getStatusCode();
if ((status < 200) || (status > 299)) {
System.out.println("unexpected status code " + status);
System.exit(1);
}
System.out.println("receiving response body (ignored)");
conn.receiveResponseEntity(connected);
conn.tunnelTarget(false, params);
System.out.println("layering secure connection");
conn.layerProtocol(ctx, params);
// finally we have the secure connection and can send the request
System.out.println("sending request");
conn.sendRequestHeader(req);
// there is no request entity
conn.flush();
System.out.println("receiving response header");
HttpResponse rsp = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
headers = rsp.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
System.out.println("closing connection");
conn.close();
} finally {
if (conn.isOpen()) {
System.out.println("shutting down connection");
try {
conn.shutdown();
} catch (Exception ex) {
System.out.println("problem during shutdown");
ex.printStackTrace();
}
}
System.out.println("releasing connection");
clcm.releaseConnection(conn, -1, null);
}
}
}

View File

@ -34,7 +34,6 @@ import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ClientConnectionRequest;
import org.apache.http.conn.ConnectionReleaseTrigger;
import org.apache.http.conn.ManagedClientConnection;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
/**
* Interface representing an HTTP request that can be aborted by shutting
@ -52,7 +51,6 @@ public interface AbortableHttpRequest {
* If the request is already aborted, throws an {@link IOException}.
*
* @see ClientConnectionManager
* @see ThreadSafeClientConnManager
*/
void setConnectionRequest(ClientConnectionRequest connRequest) throws IOException;

View File

@ -334,7 +334,7 @@ public final class HttpRoute implements RouteInfo, Cloneable {
if (this == obj) return true;
if (obj instanceof HttpRoute) {
HttpRoute that = (HttpRoute) obj;
return
return
// Do the cheapest tests first
(this.secure == that.secure) &&
(this.tunnelled == that.tunnelled) &&
@ -376,8 +376,6 @@ public final class HttpRoute implements RouteInfo, Cloneable {
@Override
public final String toString() {
StringBuilder cab = new StringBuilder(50 + getHopCount()*30);
cab.append("HttpRoute[");
if (this.localAddress != null) {
cab.append(this.localAddress);
cab.append("->");
@ -395,8 +393,6 @@ public final class HttpRoute implements RouteInfo, Cloneable {
cab.append("->");
}
cab.append(this.targetHost);
cab.append(']');
return cab.toString();
}

View File

@ -40,6 +40,7 @@ import org.apache.http.HttpRequest;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpConnectionMetrics;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.conn.OperatedClientConnection;
import org.apache.http.conn.ManagedClientConnection;
import org.apache.http.conn.ClientConnectionManager;
@ -66,8 +67,8 @@ import org.apache.http.protocol.HttpContext;
*
* @since 4.0
*/
public abstract class AbstractClientConnAdapter
implements ManagedClientConnection, HttpContext {
@NotThreadSafe
public abstract class AbstractClientConnAdapter implements ManagedClientConnection, HttpContext {
/**
* The connection manager, if any.

View File

@ -31,7 +31,6 @@ import java.io.IOException;
import org.apache.http.HttpHost;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.routing.RouteTracker;
import org.apache.http.conn.ClientConnectionOperator;
@ -52,8 +51,10 @@ import org.apache.http.conn.OperatedClientConnection;
* underlying connection and the established route.
*
* @since 4.0
*
* @deprecated do not use
*/
@NotThreadSafe
@Deprecated
public abstract class AbstractPoolEntry {
/** The connection operator. */

View File

@ -46,7 +46,10 @@ import org.apache.http.conn.OperatedClientConnection;
* respective method of the wrapped connection.
*
* @since 4.0
*
* @deprecated do not use
*/
@Deprecated
public abstract class AbstractPooledConnAdapter extends AbstractClientConnAdapter {
/** The wrapped pool entry. */

View File

@ -149,7 +149,9 @@ public class DefaultClientConnection extends SocketHttpClientConnection
shutdown = true;
try {
super.shutdown();
log.debug("Connection shut down");
if (log.isDebugEnabled()) {
log.debug("Connection " + this + " shut down");
}
Socket sock = this.socket; // copy volatile attribute
if (sock != null)
sock.close();
@ -162,7 +164,9 @@ public class DefaultClientConnection extends SocketHttpClientConnection
public void close() throws IOException {
try {
super.close();
log.debug("Connection closed");
if (log.isDebugEnabled()) {
log.debug("Connection " + this + " closed");
}
} catch (IOException ex) {
log.debug("I/O error closing connection", ex);
}
@ -211,7 +215,7 @@ public class DefaultClientConnection extends SocketHttpClientConnection
}
@Override
protected HttpMessageParser createResponseParser(
protected HttpMessageParser<HttpResponse> createResponseParser(
final SessionInputBuffer buffer,
final HttpResponseFactory responseFactory,
final HttpParams params) {

View File

@ -34,7 +34,7 @@ import org.apache.http.annotation.ThreadSafe;
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.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.NoHttpResponseException;
import org.apache.http.ProtocolException;
@ -60,7 +60,7 @@ import org.apache.http.util.CharArrayBuffer;
* @since 4.0
*/
@ThreadSafe // no public methods
public class DefaultResponseParser extends AbstractMessageParser {
public class DefaultResponseParser extends AbstractMessageParser<HttpResponse> {
private final Log log = LogFactory.getLog(getClass());
@ -94,7 +94,7 @@ public class DefaultResponseParser extends AbstractMessageParser {
}
@Override
protected HttpMessage parseHead(
protected HttpResponse parseHead(
final SessionInputBuffer sessionBuffer) throws IOException, HttpException {
//read out the HTTP status string
int count = 0;

View File

@ -57,8 +57,11 @@ import org.apache.http.params.HttpParams;
* already been allocated {@link IllegalStateException} is thrown.
*
* @since 4.0
*
* @deprecated use {@link SingleConnectionManager}
*/
@ThreadSafe
@Deprecated
public class SingleClientConnManager implements ClientConnectionManager {
private final Log log = LogFactory.getLog(getClass());

View File

@ -53,6 +53,8 @@ import org.apache.http.impl.conn.IdleConnectionHandler;
* Don't use <code>synchronized</code> for that purpose!
*
* @since 4.0
*
* @deprecated use {@link org.apache.http.pool.AbstractConnPool}
*/
@Deprecated

View File

@ -29,7 +29,6 @@ package org.apache.http.impl.conn.tsccm;
import java.lang.ref.ReferenceQueue;
import java.util.concurrent.TimeUnit;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.conn.OperatedClientConnection;
import org.apache.http.conn.ClientConnectionOperator;
import org.apache.http.conn.routing.HttpRoute;
@ -39,8 +38,10 @@ import org.apache.http.impl.conn.AbstractPoolEntry;
* Basic implementation of a connection pool entry.
*
* @since 4.0
*
* @deprecated use {@link org.apache.http.pool.PoolEntry}
*/
@NotThreadSafe
@Deprecated
public class BasicPoolEntry extends AbstractPoolEntry {
private final long created;

View File

@ -26,24 +26,21 @@
package org.apache.http.impl.conn.tsccm;
import java.lang.ref.WeakReference;
import java.lang.ref.ReferenceQueue;
import org.apache.http.annotation.Immutable;
import org.apache.http.conn.routing.HttpRoute;
/**
* 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 do not use
*/
@Immutable
@Deprecated
public class BasicPoolEntryRef extends WeakReference<BasicPoolEntry> {
/** The planned route of the entry. */

View File

@ -36,7 +36,10 @@ import org.apache.http.impl.conn.AbstractPooledConnAdapter;
* can be {@link #detach detach}ed to prevent further use on release.
*
* @since 4.0
*
* @deprecated do not use
*/
@Deprecated
public class BasicPooledConnAdapter extends AbstractPooledConnAdapter {
/**

View File

@ -40,7 +40,6 @@ import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.annotation.ThreadSafe;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.ClientConnectionOperator;
import org.apache.http.conn.ConnectionPoolTimeoutException;
@ -63,10 +62,11 @@ import org.apache.http.params.HttpParams;
* not via <code>synchronized</code> methods.
*
* @since 4.0
*
* @deprecated use {@link org.apache.http.pool.AbstractConnPool}
*/
@ThreadSafe
@SuppressWarnings("deprecation")
public class ConnPoolByRoute extends AbstractConnPool { //TODO: remove dependency on AbstractConnPool
@Deprecated
public class ConnPoolByRoute extends AbstractConnPool {
private final Log log = LogFactory.getLog(getClass());

View File

@ -26,6 +26,7 @@
package org.apache.http.impl.conn.tsccm;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.ConnectionPoolTimeoutException;
@ -34,7 +35,10 @@ import org.apache.http.conn.ConnectionPoolTimeoutException;
* Encapsulates a request for a {@link BasicPoolEntry}.
*
* @since 4.0
*
* @deprecated use {@link Future}
*/
@Deprecated
public interface PoolEntryRequest {
/**

View File

@ -31,8 +31,6 @@ import java.util.ListIterator;
import java.util.Queue;
import java.util.LinkedList;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.conn.OperatedClientConnection;
@ -47,8 +45,10 @@ import org.apache.http.util.LangUtils;
* containing pool takes care of synchronization.
*
* @since 4.0
*
* @deprecated use {@link org.apache.http.pool.AbstractConnPool}
*/
@NotThreadSafe // e.g. numEntries, freeEntries,
@Deprecated
public class RouteSpecificPool {
private final Log log = LogFactory.getLog(getClass());

View File

@ -43,6 +43,7 @@ import org.apache.http.conn.ManagedClientConnection;
import org.apache.http.conn.OperatedClientConnection;
import org.apache.http.params.HttpParams;
import org.apache.http.impl.conn.DefaultClientConnectionOperator;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.impl.conn.SchemeRegistryFactory;
/**
@ -62,8 +63,11 @@ import org.apache.http.impl.conn.SchemeRegistryFactory;
* can be adjusted using HTTP parameters.
*
* @since 4.0
*
* @deprecated use {@link PoolingClientConnectionManager}
*/
@ThreadSafe
@Deprecated
public class ThreadSafeClientConnManager implements ClientConnectionManager {
private final Log log;
@ -135,7 +139,7 @@ public class ThreadSafeClientConnManager implements ClientConnectionManager {
this.connPerRoute = connPerRoute;
this.connOperator = createConnectionOperator(schreg);
this.pool = createConnectionPool(connTTL, connTTLTimeUnit) ;
this.connectionPool = this.pool;
this.connectionPool = this.pool;
}
/**

View File

@ -30,8 +30,6 @@ package org.apache.http.impl.conn.tsccm;
import java.util.Date;
import java.util.concurrent.locks.Condition;
import org.apache.http.annotation.NotThreadSafe;
/**
* Represents a thread waiting for a connection.
* This class implements throwaway objects. It is instantiated whenever
@ -44,8 +42,10 @@ import org.apache.http.annotation.NotThreadSafe;
*
*
* @since 4.0
*
* @deprecated do not use
*/
@NotThreadSafe
@Deprecated
public class WaitingThread {
/** The condition on which the thread is waiting. */

View File

@ -26,17 +26,16 @@
package org.apache.http.impl.conn.tsccm;
import org.apache.http.annotation.NotThreadSafe;
// TODO - only called from ConnPoolByRoute currently; consider adding it as nested class
/**
* A simple class that can interrupt a {@link WaitingThread}.
*
* Must be called with the pool lock held.
*
* @since 4.0
*
* @deprecated do not use
*/
@NotThreadSafe
@Deprecated
public class WaitingThreadAborter {
private WaitingThread waitingThread;

View File

@ -89,7 +89,7 @@ public class TestURLEncodedUtils {
@Test
public void testParseEntity () throws Exception {
final StringEntity entity = new StringEntity("Name1=Value1", null);
final StringEntity entity = new StringEntity("Name1=Value1");
entity.setContentType(URLEncodedUtils.CONTENT_TYPE);
final List <NameValuePair> result = URLEncodedUtils.parse(entity);
@ -142,7 +142,7 @@ public class TestURLEncodedUtils {
@Test
public void testIsEncoded () throws Exception {
final StringEntity entity = new StringEntity("...", null);
final StringEntity entity = new StringEntity("...");
entity.setContentType(URLEncodedUtils.CONTENT_TYPE);
Assert.assertTrue(URLEncodedUtils.isEncoded(entity));

View File

@ -40,12 +40,12 @@ import org.apache.http.HttpResponse;
import org.apache.http.MalformedChunkCodingException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.DefaultHttpServerConnection;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.localserver.ServerTestBase;
import org.apache.http.pool.PoolStats;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
@ -55,20 +55,15 @@ import org.junit.Test;
public class TestConnectionAutoRelease extends ServerTestBase {
private ThreadSafeClientConnManager createTSCCM(SchemeRegistry schreg) {
if (schreg == null)
schreg = supportedSchemes;
return new ThreadSafeClientConnManager(schreg);
}
@Test
public void testReleaseOnEntityConsumeContent() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setDefaultMaxPerRoute(1);
mgr.setMaxTotal(1);
// Zero connections in the pool
Assert.assertEquals(0, mgr.getConnectionsInPool());
PoolStats stats = mgr.getTotalStats();
Assert.assertEquals(0, stats.getAvailable());
DefaultHttpClient client = new DefaultHttpClient(mgr);
@ -90,7 +85,8 @@ public class TestConnectionAutoRelease extends ServerTestBase {
EntityUtils.consume(e);
// Expect one connection in the pool
Assert.assertEquals(1, mgr.getConnectionsInPool());
stats = mgr.getTotalStats();
Assert.assertEquals(1, stats.getAvailable());
// Make sure one connection is available
connreq = mgr.requestConnection(new HttpRoute(target), null);
@ -103,12 +99,13 @@ public class TestConnectionAutoRelease extends ServerTestBase {
@Test
public void testReleaseOnEntityWriteTo() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setDefaultMaxPerRoute(1);
mgr.setMaxTotal(1);
// Zero connections in the pool
Assert.assertEquals(0, mgr.getConnectionsInPool());
PoolStats stats = mgr.getTotalStats();
Assert.assertEquals(0, stats.getAvailable());
DefaultHttpClient client = new DefaultHttpClient(mgr);
@ -131,7 +128,8 @@ public class TestConnectionAutoRelease extends ServerTestBase {
e.writeTo(outsteam);
// Expect one connection in the pool
Assert.assertEquals(1, mgr.getConnectionsInPool());
stats = mgr.getTotalStats();
Assert.assertEquals(1, stats.getAvailable());
// Make sure one connection is available
connreq = mgr.requestConnection(new HttpRoute(target), null);
@ -144,12 +142,13 @@ public class TestConnectionAutoRelease extends ServerTestBase {
@Test
public void testReleaseOnAbort() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setDefaultMaxPerRoute(1);
mgr.setMaxTotal(1);
// Zero connections in the pool
Assert.assertEquals(0, mgr.getConnectionsInPool());
PoolStats stats = mgr.getTotalStats();
Assert.assertEquals(0, stats.getAvailable());
DefaultHttpClient client = new DefaultHttpClient(mgr);
@ -171,7 +170,7 @@ public class TestConnectionAutoRelease extends ServerTestBase {
httpget.abort();
// Expect zero connections in the pool
Assert.assertEquals(0, mgr.getConnectionsInPool());
Assert.assertEquals(0, mgr.getTotalStats().getAvailable());
// Make sure one connection is available
connreq = mgr.requestConnection(new HttpRoute(target), null);
@ -217,12 +216,12 @@ public class TestConnectionAutoRelease extends ServerTestBase {
});
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setDefaultMaxPerRoute(1);
mgr.setMaxTotal(1);
// Zero connections in the pool
Assert.assertEquals(0, mgr.getConnectionsInPool());
Assert.assertEquals(0, mgr.getTotalStats().getAvailable());
DefaultHttpClient client = new DefaultHttpClient(mgr);
@ -250,7 +249,7 @@ public class TestConnectionAutoRelease extends ServerTestBase {
}
// Expect zero connections in the pool
Assert.assertEquals(0, mgr.getConnectionsInPool());
Assert.assertEquals(0, mgr.getTotalStats().getAvailable());
// Make sure one connection is available
connreq = mgr.requestConnection(new HttpRoute(target), null);

View File

@ -44,7 +44,7 @@ import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SchemeSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.localserver.LocalTestServer;
import org.apache.http.localserver.RandomHandler;
import org.apache.http.params.BasicHttpParams;
@ -99,7 +99,7 @@ public class TestConnectionReuse {
SchemeSocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", 80, sf));
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(supportedSchemes);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(supportedSchemes);
mgr.setMaxTotal(5);
mgr.setDefaultMaxPerRoute(5);
@ -130,7 +130,7 @@ public class TestConnectionReuse {
}
// Expect some connection in the pool
Assert.assertTrue(mgr.getConnectionsInPool() > 0);
Assert.assertTrue(mgr.getTotalStats().getAvailable() > 0);
mgr.shutdown();
}
@ -170,7 +170,7 @@ public class TestConnectionReuse {
SchemeSocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", 80, sf));
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(supportedSchemes);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(supportedSchemes);
mgr.setMaxTotal(5);
mgr.setDefaultMaxPerRoute(5);
@ -201,7 +201,7 @@ public class TestConnectionReuse {
}
// Expect zero connections in the pool
Assert.assertEquals(0, mgr.getConnectionsInPool());
Assert.assertEquals(0, mgr.getTotalStats().getAvailable());
mgr.shutdown();
}
@ -231,7 +231,7 @@ public class TestConnectionReuse {
SchemeSocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", 80, sf));
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(supportedSchemes);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(supportedSchemes);
mgr.setMaxTotal(5);
mgr.setDefaultMaxPerRoute(5);
@ -262,7 +262,7 @@ public class TestConnectionReuse {
}
// Expect zero connections in the pool
Assert.assertEquals(0, mgr.getConnectionsInPool());
Assert.assertEquals(0, mgr.getTotalStats().getAvailable());
mgr.shutdown();
}
@ -293,7 +293,7 @@ public class TestConnectionReuse {
SchemeSocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", 80, sf));
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(supportedSchemes);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(supportedSchemes);
mgr.setMaxTotal(1);
mgr.setDefaultMaxPerRoute(1);
@ -303,13 +303,13 @@ public class TestConnectionReuse {
HttpResponse response = client.execute(target, new HttpGet("/random/2000"));
EntityUtils.consume(response.getEntity());
Assert.assertEquals(1, mgr.getConnectionsInPool());
Assert.assertEquals(1, mgr.getTotalStats().getAvailable());
Assert.assertEquals(1, localServer.getAcceptedConnectionCount());
response = client.execute(target, new HttpGet("/random/2000"));
EntityUtils.consume(response.getEntity());
Assert.assertEquals(1, mgr.getConnectionsInPool());
Assert.assertEquals(1, mgr.getTotalStats().getAvailable());
Assert.assertEquals(1, localServer.getAcceptedConnectionCount());
// Now sleep for 1.1 seconds and let the timeout do its work
@ -317,7 +317,7 @@ public class TestConnectionReuse {
response = client.execute(target, new HttpGet("/random/2000"));
EntityUtils.consume(response.getEntity());
Assert.assertEquals(1, mgr.getConnectionsInPool());
Assert.assertEquals(1, mgr.getTotalStats().getAvailable());
Assert.assertEquals(2, localServer.getAcceptedConnectionCount());
// Do another request just under the 1 second limit & make
@ -326,7 +326,7 @@ public class TestConnectionReuse {
response = client.execute(target, new HttpGet("/random/2000"));
EntityUtils.consume(response.getEntity());
Assert.assertEquals(1, mgr.getConnectionsInPool());
Assert.assertEquals(1, mgr.getTotalStats().getAvailable());
Assert.assertEquals(2, localServer.getAcceptedConnectionCount());

View File

@ -55,7 +55,7 @@ import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.localserver.ServerTestBase;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
@ -188,7 +188,7 @@ public class TestContentCodings extends ServerTestBase {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
cm.setMaxTotal(clients);
final HttpClient httpClient = new DefaultHttpClient(cm);

View File

@ -60,8 +60,7 @@ import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.conn.ClientConnAdapterMockup;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.localserver.BasicServerTestBase;
import org.apache.http.localserver.LocalTestServer;
import org.apache.http.message.BasicHeader;
@ -141,7 +140,7 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
SingleClientConnManager conMan = new SingleClientConnManager(registry);
PoolingClientConnectionManager conMan = new PoolingClientConnectionManager(registry);
final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>();
final CountDownLatch getLatch = new CountDownLatch(1);
final DefaultHttpClient client = new DefaultHttpClient(conMan, new BasicHttpParams());
@ -182,7 +181,7 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
SingleClientConnManager conMan = new SingleClientConnManager(registry);
PoolingClientConnectionManager conMan = new PoolingClientConnectionManager(registry);
final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>();
final CountDownLatch getLatch = new CountDownLatch(1);
final CountDownLatch startLatch = new CountDownLatch(1);
@ -283,35 +282,6 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
Assert.assertSame(conMan.allocatedConnection, conMan.releasedConnection);
}
@Test
public void testRequestFailureReleasesConnection() throws Exception {
this.localServer.register("*", new ThrowingService());
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
ConnMan3 conMan = new ConnMan3(registry);
DefaultHttpClient client = new DefaultHttpClient(conMan, new BasicHttpParams());
HttpGet httpget = new HttpGet("/a");
try {
client.execute(getServerHttp(), httpget);
Assert.fail("expected IOException");
} catch (IOException expected) {}
Assert.assertNotNull(conMan.allocatedConnection);
Assert.assertSame(conMan.allocatedConnection, conMan.releasedConnection);
}
private static class ThrowingService implements HttpRequestHandler {
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
throw new IOException();
}
}
private static class BasicService implements HttpRequestHandler {
public void handle(final HttpRequest request,
final HttpResponse response,
@ -340,7 +310,7 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
}
}
private static class ConnMan4 extends ThreadSafeClientConnManager {
private static class ConnMan4 extends PoolingClientConnectionManager {
private final CountDownLatch connLatch;
private final CountDownLatch awaitLatch;
@ -387,29 +357,6 @@ public class TestDefaultClientRequestDirector extends BasicServerTestBase {
}
private static class ConnMan3 extends SingleClientConnManager {
private ManagedClientConnection allocatedConnection;
private ManagedClientConnection releasedConnection;
public ConnMan3(SchemeRegistry schreg) {
super(schreg);
}
@Override
public ManagedClientConnection getConnection(HttpRoute route, Object state) {
allocatedConnection = super.getConnection(route, state);
return allocatedConnection;
}
@Override
public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) {
releasedConnection = conn;
super.releaseConnection(conn, validDuration, timeUnit);
}
}
static class ConnMan2 implements ClientConnectionManager {
private ManagedClientConnection allocatedConnection;

View File

@ -38,8 +38,7 @@ import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SchemeSocketFactory;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
@ -49,26 +48,16 @@ import org.junit.Test;
public class TestRequestRetryHandler {
@Test(expected=UnknownHostException.class)
public void testUseRetryHandlerInConnectionTimeOutWithThreadSafeClientConnManager()
public void testUseRetryHandlerInConnectionTimeOut()
throws Exception {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, new OppsieSchemeSocketFactory()));
ClientConnectionManager connManager = new ThreadSafeClientConnManager(schemeRegistry);
ClientConnectionManager connManager = new PoolingClientConnectionManager(schemeRegistry);
assertOnRetry(connManager);
}
@Test(expected=UnknownHostException.class)
public void testUseRetryHandlerInConnectionTimeOutWithSingleClientConnManager()
throws Exception {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, new OppsieSchemeSocketFactory()));
ClientConnectionManager connManager = new SingleClientConnManager(schemeRegistry);
assertOnRetry(connManager);
}
protected void assertOnRetry(ClientConnectionManager connManager) throws Exception {
DefaultHttpClient client = new DefaultHttpClient(connManager);
TestHttpRequestRetryHandler testRetryHandler = new TestHttpRequestRetryHandler();

View File

@ -37,7 +37,7 @@ import org.apache.http.client.UserTokenHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ManagedClientConnection;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.localserver.ServerTestBase;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
@ -85,7 +85,7 @@ public class TestStatefulConnManagement extends ServerTestBase {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 10);
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(supportedSchemes);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(supportedSchemes);
mgr.setMaxTotal(workerCount);
mgr.setDefaultMaxPerRoute(workerCount);
@ -207,7 +207,7 @@ public class TestStatefulConnManagement extends ServerTestBase {
this.localServer.register("*", new SimpleService());
// We build a client with 2 max active // connections, and 2 max per route.
ThreadSafeClientConnManager connMngr = new ThreadSafeClientConnManager(supportedSchemes);
PoolingClientConnectionManager connMngr = new PoolingClientConnectionManager(supportedSchemes);
connMngr.setMaxTotal(maxConn);
connMngr.setDefaultMaxPerRoute(maxConn);

View File

@ -111,10 +111,9 @@ public class ExecReqThread extends GetConnThread {
doConsumeResponse();
} catch (Throwable dart) {
dart.printStackTrace(System.out);
} catch (Exception ex) {
if (exception != null)
exception = dart;
exception = ex;
} finally {
conn_manager.releaseConnection(connection, -1, null);

View File

@ -47,7 +47,7 @@ public class GetConnThread extends Thread {
protected final ClientConnectionRequest conn_request;
protected volatile ManagedClientConnection connection;
protected volatile Throwable exception;
protected volatile Exception exception;
/**
* Creates a new thread for requesting a connection from the given manager.
@ -81,8 +81,8 @@ public class GetConnThread extends Thread {
try {
connection = conn_request.getConnection
(conn_timeout, TimeUnit.MILLISECONDS);
} catch (Throwable dart) {
exception = dart;
} catch (Exception ex) {
exception = ex;
}
// terminate
}

View File

@ -60,7 +60,7 @@ public class TestDefaultResponseParser {
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuffer = new SessionInputBufferMockup(s, "US-ASCII", params);
HttpMessageParser parser = new DefaultResponseParser(
HttpMessageParser<HttpResponse> parser = new DefaultResponseParser(
inbuffer,
BasicLineParser.DEFAULT,
new DefaultHttpResponseFactory(),
@ -91,7 +91,7 @@ public class TestDefaultResponseParser {
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuffer = new SessionInputBufferMockup(s, "US-ASCII", params);
HttpMessageParser parser = new DefaultResponseParser(
HttpMessageParser<HttpResponse> parser = new DefaultResponseParser(
inbuffer,
BasicLineParser.DEFAULT,
new DefaultHttpResponseFactory(),
@ -110,7 +110,7 @@ public class TestDefaultResponseParser {
public void testResponseParsingNoResponse() throws Exception {
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuffer = new SessionInputBufferMockup("", "US-ASCII", params);
HttpMessageParser parser = new DefaultResponseParser(
HttpMessageParser<HttpResponse> parser = new DefaultResponseParser(
inbuffer,
BasicLineParser.DEFAULT,
new DefaultHttpResponseFactory(),
@ -127,7 +127,7 @@ public class TestDefaultResponseParser {
"a lot more garbage\r\n";
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuffer = new SessionInputBufferMockup(s, "US-ASCII", params);
HttpMessageParser parser = new DefaultResponseParser(
HttpMessageParser<HttpResponse> parser = new DefaultResponseParser(
inbuffer,
BasicLineParser.DEFAULT,
new DefaultHttpResponseFactory(),

View File

@ -41,7 +41,6 @@ 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.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.localserver.LocalTestServer;
import org.apache.http.localserver.ServerTestBase;
import org.apache.http.params.BasicHttpParams;
@ -69,7 +68,7 @@ public class TestIdleConnectionEviction extends ServerTestBase {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
cm.setDefaultMaxPerRoute(10);
cm.setMaxTotal(50);

View File

@ -44,6 +44,7 @@ import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.junit.Test;
@Deprecated
public class TestSCMWithServer extends ServerTestBase {
/**

View File

@ -36,10 +36,6 @@ import org.apache.http.conn.ClientConnectionRequest;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ManagedClientConnection;
import org.apache.http.conn.routing.HttpRoute;
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.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
@ -68,21 +64,6 @@ public class TestTSCCMNoServer {
return connRequest.getConnection(0, null);
}
/**
* Helper to instantiate a <code>ThreadSafeClientConnManager</code>.
*
* @param schreg the scheme registry, or
* <code>null</code> to use defaults
*
* @return a connection manager to test
*/
public ThreadSafeClientConnManager createTSCCM(SchemeRegistry schreg) {
if (schreg == null)
schreg = createSchemeRegistry();
return new ThreadSafeClientConnManager(schreg);
}
/**
* Instantiates default parameters.
*
@ -97,37 +78,15 @@ public class TestTSCCMNoServer {
return params;
}
/**
* Instantiates a default scheme registry.
*
* @return the default scheme registry
*/
public SchemeRegistry createSchemeRegistry() {
SchemeRegistry schreg = new SchemeRegistry();
schreg.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
return schreg;
}
@Test
public void testConstructor() {
SchemeRegistry schreg = createSchemeRegistry();
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(schreg);
Assert.assertNotNull(mgr);
mgr.shutdown();
}
@Test(expected=IllegalArgumentException.class)
public void testIllegalConstructor() {
new ThreadSafeClientConnManager(null);
new PoolingClientConnectionManager(null);
}
@Test(expected=IllegalArgumentException.class)
public void testGetConnection()
throws InterruptedException, ConnectionPoolTimeoutException {
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
HttpHost target = new HttpHost("www.test.invalid", 80, "http");
HttpRoute route = new HttpRoute(target, null, false);
@ -152,7 +111,7 @@ public class TestTSCCMNoServer {
public void testMaxConnTotal()
throws InterruptedException, ConnectionPoolTimeoutException {
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setMaxTotal(2);
mgr.setDefaultMaxPerRoute(1);
@ -198,11 +157,11 @@ public class TestTSCCMNoServer {
HttpHost target3 = new HttpHost("www.test3.invalid", 80, "http");
HttpRoute route3 = new HttpRoute(target3, null, false);
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setMaxTotal(100);
mgr.setDefaultMaxPerRoute(1);
mgr.setMaxForRoute(route2, 2);
mgr.setMaxForRoute(route3, 3);
mgr.setMaxPerRoute(route2, 2);
mgr.setMaxPerRoute(route3, 3);
// route 3, limit 3
ManagedClientConnection conn1 =
@ -264,7 +223,7 @@ public class TestTSCCMNoServer {
@Test
public void testReleaseConnection() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setMaxTotal(3);
mgr.setDefaultMaxPerRoute(1);
@ -333,31 +292,26 @@ public class TestTSCCMNoServer {
public void testDeleteClosedConnections()
throws InterruptedException, ConnectionPoolTimeoutException {
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
HttpHost target = new HttpHost("www.test.invalid", 80, "http");
HttpRoute route = new HttpRoute(target, null, false);
ManagedClientConnection conn = getConnection(mgr, route);
Assert.assertEquals("connectionsInPool",
mgr.getConnectionsInPool(), 1);
Assert.assertEquals("connectionsInPool(host)",
mgr.getConnectionsInPool(route), 1);
Assert.assertEquals(1, mgr.getTotalStats().getLeased());
Assert.assertEquals(1, mgr.getStats(route).getLeased());
conn.markReusable();
mgr.releaseConnection(conn, -1, null);
Assert.assertEquals("connectionsInPool",
mgr.getConnectionsInPool(), 1);
Assert.assertEquals("connectionsInPool(host)",
mgr.getConnectionsInPool(route), 1);
Assert.assertEquals(1, mgr.getTotalStats().getAvailable());
Assert.assertEquals(1, mgr.getStats(route).getAvailable());
// this implicitly deletes them
mgr.closeIdleConnections(0L, TimeUnit.MILLISECONDS);
Assert.assertEquals("connectionsInPool",
mgr.getConnectionsInPool(), 0);
Assert.assertEquals("connectionsInPool(host)",
mgr.getConnectionsInPool(route), 0);
Assert.assertEquals(0, mgr.getTotalStats().getAvailable());
Assert.assertEquals(0, mgr.getStats(route).getAvailable());
mgr.shutdown();
}
@ -366,7 +320,7 @@ public class TestTSCCMNoServer {
public void testShutdown() throws Exception {
// 3.x: TestHttpConnectionManager.testShutdown
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setMaxTotal(1);
mgr.setDefaultMaxPerRoute(1);
@ -397,7 +351,7 @@ public class TestTSCCMNoServer {
Assert.assertNotNull("thread should have gotten an exception",
gct.getException());
Assert.assertSame("thread got wrong exception",
IllegalStateException.class, gct.getException().getClass());
InterruptedException.class, gct.getException().getClass());
// the manager is down, we should not be able to get a connection
try {
@ -412,7 +366,7 @@ public class TestTSCCMNoServer {
public void testInterruptThread() throws Exception {
// 3.x: TestHttpConnectionManager.testWaitingThreadInterrupted
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setMaxTotal(1);
HttpHost target = new HttpHost("www.test.invalid", 80, "http");
@ -457,7 +411,7 @@ public class TestTSCCMNoServer {
public void testReusePreference() throws Exception {
// 3.x: TestHttpConnectionManager.testHostReusePreference
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setMaxTotal(1);
HttpHost target1 = new HttpHost("www.test1.invalid", 80, "http");
@ -496,7 +450,7 @@ public class TestTSCCMNoServer {
@Test
public void testAbortAfterRequestStarts() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setMaxTotal(1);
HttpHost target = new HttpHost("www.test.invalid", 80, "http");
@ -536,7 +490,7 @@ public class TestTSCCMNoServer {
@Test
public void testAbortBeforeRequestStarts() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setMaxTotal(1);
HttpHost target = new HttpHost("www.test.invalid", 80, "http");

View File

@ -28,7 +28,6 @@
package org.apache.http.impl.conn;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
@ -55,7 +54,6 @@ 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.scheme.SchemeSocketFactory;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.localserver.ServerTestBase;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.params.HttpParams;
@ -72,25 +70,6 @@ import org.junit.Test;
*/
public class TestTSCCMWithServer extends ServerTestBase {
/**
* Helper to instantiate a <code>ThreadSafeClientConnManager</code>.
*
* @param schreg the scheme registry, or
* <code>null</code> to use defaults
*
* @return a connection manager to test
*/
public ThreadSafeClientConnManager createTSCCM(SchemeRegistry schreg) {
return createTSCCM(schreg, -1, TimeUnit.MILLISECONDS);
}
public ThreadSafeClientConnManager createTSCCM(SchemeRegistry schreg,
long connTTL, TimeUnit connTTLTimeUnit) {
if (schreg == null)
schreg = supportedSchemes;
return new ThreadSafeClientConnManager(schreg, connTTL, connTTLTimeUnit);
}
/**
* Tests executing several requests in parallel.
*/
@ -100,7 +79,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
final int COUNT = 8; // adjust to execute more requests
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setMaxTotal(COUNT/2);
mgr.setDefaultMaxPerRoute(COUNT/2);
@ -173,7 +152,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
@Test
public void testReleaseConnection() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setMaxTotal(1);
final HttpHost target = getServerHttp();
@ -259,7 +238,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
@Test
public void testReleaseConnectionWithTimeLimits() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setMaxTotal(1);
final HttpHost target = getServerHttp();
@ -361,7 +340,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
@Test
public void testCloseExpiredIdleConnections() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setMaxTotal(1);
final HttpHost target = getServerHttp();
@ -370,27 +349,28 @@ public class TestTSCCMWithServer extends ServerTestBase {
ManagedClientConnection conn = getConnection(mgr, route);
conn.open(route, httpContext, defaultParams);
Assert.assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
Assert.assertEquals("connectionsInPool(host)", 1, mgr.getConnectionsInPool(route));
Assert.assertEquals(1, mgr.getTotalStats().getLeased());
Assert.assertEquals(1, mgr.getStats(route).getLeased());
conn.markReusable();
mgr.releaseConnection(conn, 100, TimeUnit.MILLISECONDS);
// Released, still active.
Assert.assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
Assert.assertEquals("connectionsInPool(host)", 1, mgr.getConnectionsInPool(route));
Assert.assertEquals(1, mgr.getTotalStats().getAvailable());
Assert.assertEquals(1, mgr.getStats(route).getAvailable());
mgr.closeExpiredConnections();
// Time has not expired yet.
Assert.assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
Assert.assertEquals("connectionsInPool(host)", 1, mgr.getConnectionsInPool(route));
Assert.assertEquals(1, mgr.getTotalStats().getAvailable());
Assert.assertEquals(1, mgr.getStats(route).getAvailable());
Thread.sleep(150);
mgr.closeExpiredConnections();
// Time expired now, connections are destroyed.
Assert.assertEquals("connectionsInPool", 0, mgr.getConnectionsInPool());
Assert.assertEquals("connectionsInPool(host)", 0, mgr.getConnectionsInPool(route));
Assert.assertEquals(0, mgr.getTotalStats().getAvailable());
Assert.assertEquals(0, mgr.getStats(route).getAvailable());
mgr.shutdown();
}
@ -398,7 +378,8 @@ public class TestTSCCMWithServer extends ServerTestBase {
@Test
public void testCloseExpiredTTLConnections() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null, 100, TimeUnit.MILLISECONDS);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(
SchemeRegistryFactory.createDefault(), 100, TimeUnit.MILLISECONDS);
mgr.setMaxTotal(1);
final HttpHost target = getServerHttp();
@ -407,28 +388,29 @@ public class TestTSCCMWithServer extends ServerTestBase {
ManagedClientConnection conn = getConnection(mgr, route);
conn.open(route, httpContext, defaultParams);
Assert.assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
Assert.assertEquals("connectionsInPool(host)", 1, mgr.getConnectionsInPool(route));
Assert.assertEquals(1, mgr.getTotalStats().getLeased());
Assert.assertEquals(1, mgr.getStats(route).getLeased());
// Release, let remain idle for forever
conn.markReusable();
mgr.releaseConnection(conn, -1, TimeUnit.MILLISECONDS);
// Released, still active.
Assert.assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
Assert.assertEquals("connectionsInPool(host)", 1, mgr.getConnectionsInPool(route));
Assert.assertEquals(1, mgr.getTotalStats().getAvailable());
Assert.assertEquals(1, mgr.getStats(route).getAvailable());
mgr.closeExpiredConnections();
// Time has not expired yet.
Assert.assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
Assert.assertEquals("connectionsInPool(host)", 1, mgr.getConnectionsInPool(route));
Assert.assertEquals(1, mgr.getTotalStats().getAvailable());
Assert.assertEquals(1, mgr.getStats(route).getAvailable());
Thread.sleep(150);
mgr.closeExpiredConnections();
// TTL expired now, connections are destroyed.
Assert.assertEquals("connectionsInPool", 0, mgr.getConnectionsInPool());
Assert.assertEquals("connectionsInPool(host)", 0, mgr.getConnectionsInPool(route));
Assert.assertEquals(0, mgr.getTotalStats().getAvailable());
Assert.assertEquals(0, mgr.getStats(route).getAvailable());
mgr.shutdown();
}
@ -440,7 +422,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
@Test
public void testReleaseConnectionOnAbort() throws Exception {
ThreadSafeClientConnManager mgr = createTSCCM(null);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setMaxTotal(1);
final HttpHost target = getServerHttp();
@ -473,8 +455,8 @@ public class TestTSCCMWithServer extends ServerTestBase {
}
// abort the connection
Assert.assertTrue(conn instanceof AbstractClientConnAdapter);
((AbstractClientConnAdapter) conn).abortConnection();
Assert.assertTrue(conn instanceof ManagedClientConnection);
((ManagedClientConnection) conn).abortConnection();
// the connection is expected to be released back to the manager
conn = getConnection(mgr, route, 5L, TimeUnit.SECONDS);
@ -484,56 +466,6 @@ public class TestTSCCMWithServer extends ServerTestBase {
mgr.shutdown();
}
/**
* Tests GC of an unreferenced connection manager.
*/
@Test
public void testConnectionManagerGC() throws Exception {
// 3.x: TestHttpConnectionManager.testDroppedThread
ThreadSafeClientConnManager mgr = createTSCCM(null);
final HttpHost target = getServerHttp();
final HttpRoute route = new HttpRoute(target, null, false);
final int rsplen = 8;
final String uri = "/random/" + rsplen;
HttpRequest request =
new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1);
ManagedClientConnection conn = getConnection(mgr, route);
conn.open(route, httpContext, defaultParams);
// a new context is created for each testcase, no need to reset
HttpResponse response = Helper.execute(request, conn, target,
httpExecutor, httpProcessor, defaultParams, httpContext);
EntityUtils.toByteArray(response.getEntity());
// release connection after marking it for re-use
conn.markReusable();
mgr.releaseConnection(conn, -1, null);
// We now have a manager with an open connection in its pool.
// We drop all potential hard reference to the manager and check
// whether it is GCed. Internal references might prevent that
// if set up incorrectly.
// Note that we still keep references to the connection wrapper
// we got from the manager, directly as well as in the request
// and in the context. The manager will be GCed only if the
// connection wrapper is truly detached.
WeakReference<ThreadSafeClientConnManager> wref =
new WeakReference<ThreadSafeClientConnManager>(mgr);
mgr = null;
// Java does not guarantee that this will trigger the GC, but
// it does in the test environment. GC is asynchronous, so we
// need to give the garbage collector some time afterwards.
System.gc();
Thread.sleep(1000);
Assert.assertNull("TSCCM not garbage collected", wref.get());
}
@Test
public void testAbortDuringConnecting() throws Exception {
final CountDownLatch connectLatch = new CountDownLatch(1);
@ -543,14 +475,13 @@ public class TestTSCCMWithServer extends ServerTestBase {
SchemeRegistry registry = new SchemeRegistry();
registry.register(scheme);
ThreadSafeClientConnManager mgr = createTSCCM(registry);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(registry);
mgr.setMaxTotal(1);
final HttpHost target = getServerHttp();
final HttpRoute route = new HttpRoute(target, null, false);
final ManagedClientConnection conn = getConnection(mgr, route);
Assert.assertTrue(conn instanceof AbstractClientConnAdapter);
final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>();
Thread abortingThread = new Thread(new Runnable() {
@ -595,14 +526,13 @@ public class TestTSCCMWithServer extends ServerTestBase {
SchemeRegistry registry = new SchemeRegistry();
registry.register(scheme);
ThreadSafeClientConnManager mgr = createTSCCM(registry);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(registry);
mgr.setMaxTotal(1);
final HttpHost target = getServerHttp();
final HttpRoute route = new HttpRoute(target, null, false);
final ManagedClientConnection conn = getConnection(mgr, route);
Assert.assertTrue(conn instanceof AbstractClientConnAdapter);
final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>();
Thread abortingThread = new Thread(new Runnable() {
@ -649,14 +579,13 @@ public class TestTSCCMWithServer extends ServerTestBase {
SchemeRegistry registry = new SchemeRegistry();
registry.register(scheme);
ThreadSafeClientConnManager mgr = createTSCCM(registry);
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(registry);
mgr.setMaxTotal(1);
final HttpHost target = getServerHttp();
final HttpRoute route = new HttpRoute(target, null, false);
final ManagedClientConnection conn = getConnection(mgr, route);
Assert.assertTrue(conn instanceof AbstractClientConnAdapter);
final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>();
Thread abortingThread = new Thread(new Runnable() {
@ -704,7 +633,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
final CountDownLatch connectLatch = new CountDownLatch(1);
final AtomicReference<StallingOperator> operatorRef = new AtomicReference<StallingOperator>();
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(supportedSchemes) {
PoolingClientConnectionManager mgr = new PoolingClientConnectionManager() {
@Override
protected ClientConnectionOperator createConnectionOperator(
SchemeRegistry schreg) {
@ -719,7 +648,6 @@ public class TestTSCCMWithServer extends ServerTestBase {
final HttpRoute route = new HttpRoute(target, null, false);
final ManagedClientConnection conn = getConnection(mgr, route);
Assert.assertTrue(conn instanceof AbstractClientConnAdapter);
final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>();
Thread abortingThread = new Thread(new Runnable() {
@ -739,7 +667,6 @@ public class TestTSCCMWithServer extends ServerTestBase {
conn.open(route, httpContext, defaultParams);
Assert.fail("expected exception");
} catch(IOException iox) {
Assert.assertEquals("Request aborted", iox.getMessage());
}
abortingThread.join(5000);
@ -782,7 +709,7 @@ public class TestTSCCMWithServer extends ServerTestBase {
void latch() {
waitLatch.countDown();
try {
if (!continueLatch.await(1, TimeUnit.SECONDS))
if (!continueLatch.await(60, TimeUnit.SECONDS))
throw new RuntimeException("waited too long!");
} catch (InterruptedException e) {
throw new RuntimeException(e);

View File

@ -35,6 +35,7 @@ import java.util.concurrent.locks.Lock;
/**
* Thread to await something.
*/
@Deprecated
public class AwaitThread extends Thread {
protected final WaitingThread wait_object;

View File

@ -50,6 +50,7 @@ import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
@Deprecated
public class TestConnPoolByRoute extends ServerTestBase {
private ConnPoolByRoute impl;
@ -201,7 +202,6 @@ public class TestConnPoolByRoute extends ServerTestBase {
}
@Test
@SuppressWarnings("deprecation")
public void deprecatedConstructorIsStillSupported() {
new ConnPoolByRoute(new DefaultClientConnectionOperator(supportedSchemes),
new BasicHttpParams());
@ -310,8 +310,7 @@ public class TestConnPoolByRoute extends ServerTestBase {
useMockOperator();
BasicPoolEntry entry = impl.requestPoolEntry(route, new Object()).getPoolEntry(-1, TimeUnit.MILLISECONDS);
impl.freeEntry(entry, true, Long.MAX_VALUE, TimeUnit.MILLISECONDS);
Thread.sleep(1);
impl.closeIdleConnections(3, TimeUnit.MILLISECONDS);
impl.closeIdleConnections(3, TimeUnit.SECONDS);
verify(mockConnection, never()).close();
}

View File

@ -52,6 +52,7 @@ import org.junit.Test;
* satisfying the condition.
*
*/
@Deprecated
public class TestSpuriousWakeup {
public final static

View File

@ -41,6 +41,7 @@ import org.junit.Test;
/**
* Tests for <code>WaitingThread</code>.
*/
@Deprecated
public class TestWaitingThread {
public final static

View File

@ -68,7 +68,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<httpcore.version>4.1.1</httpcore.version>
<httpcore.version>4.2-alpha1-SNAPSHOT</httpcore.version>
<commons-logging.version>1.1.1</commons-logging.version>
<commons-codec.version>1.4</commons-codec.version>
<ehcache.version>2.2.0</ehcache.version>
@ -91,7 +91,7 @@
</snapshots>
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<dependency>