You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hc.apache.org by ol...@apache.org on 2011/09/22 22:03:37 UTC
svn commit: r1174357 [2/2] - in /httpcomponents/httpasyncclient/trunk: ./
httpasyncclient/src/examples/org/apache/http/examples/nio/client/
httpasyncclient/src/main/java/org/apache/http/impl/nio/client/
httpasyncclient/src/main/java/org/apache/http/imp...
Modified: httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/impl/nio/client/TestHttpsAsync.java
URL: http://svn.apache.org/viewvc/httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/impl/nio/client/TestHttpsAsync.java?rev=1174357&r1=1174356&r2=1174357&view=diff
==============================================================================
--- httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/impl/nio/client/TestHttpsAsync.java (original)
+++ httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/impl/nio/client/TestHttpsAsync.java Thu Sep 22 20:03:35 2011
@@ -26,230 +26,32 @@
*/
package org.apache.http.impl.nio.client;
-import java.io.IOException;
-import java.net.URL;
-import java.security.KeyStore;
-import java.security.NoSuchAlgorithmException;
-import java.util.LinkedList;
-import java.util.Queue;
-import java.util.Random;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-
-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 org.apache.http.HttpEntity;
-import org.apache.http.HttpHost;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.impl.nio.conn.PoolingClientConnectionManager;
-import org.apache.http.localserver.AsyncHttpTestBase;
-import org.apache.http.localserver.LocalTestServer;
-import org.apache.http.nio.ContentDecoder;
-import org.apache.http.nio.IOControl;
-import org.apache.http.nio.client.HttpAsyncRequestProducer;
-import org.apache.http.nio.client.methods.BasicHttpAsyncResponseConsumer;
-import org.apache.http.nio.client.methods.HttpAsyncMethods;
+import org.apache.http.SSLTestContexts;
+import org.apache.http.impl.nio.SSLNHttpServerConnectionFactory;
+import org.apache.http.nio.NHttpConnectionFactory;
+import org.apache.http.nio.NHttpServerIOTarget;
import org.apache.http.nio.conn.scheme.Scheme;
-import org.apache.http.nio.conn.scheme.SchemeRegistry;
import org.apache.http.nio.conn.ssl.SSLLayeringStrategy;
-import org.apache.http.nio.entity.NByteArrayEntity;
-import org.apache.http.nio.reactor.ConnectingIOReactor;
-import org.apache.http.util.EntityUtils;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class TestHttpsAsync extends AsyncHttpTestBase {
-
- private KeyManagerFactory createKeyManagerFactory() throws NoSuchAlgorithmException {
- String algo = KeyManagerFactory.getDefaultAlgorithm();
- try {
- return KeyManagerFactory.getInstance(algo);
- } catch (NoSuchAlgorithmException ex) {
- return KeyManagerFactory.getInstance("SunX509");
- }
- }
+import org.apache.http.params.HttpParams;
- private TrustManagerFactory createTrustManagerFactory() throws NoSuchAlgorithmException {
- String algo = TrustManagerFactory.getDefaultAlgorithm();
- try {
- return TrustManagerFactory.getInstance(algo);
- } catch (NoSuchAlgorithmException ex) {
- return TrustManagerFactory.getInstance("SunX509");
- }
- }
+public class TestHttpsAsync extends TestHttpAsync {
@Override
- protected LocalTestServer createServer() throws Exception {
- ClassLoader cl = getClass().getClassLoader();
- URL url = cl.getResource("test.keystore");
- KeyStore keystore = KeyStore.getInstance("jks");
- char[] pwd = "nopassword".toCharArray();
- keystore.load(url.openStream(), pwd);
-
- TrustManagerFactory tmf = createTrustManagerFactory();
- tmf.init(keystore);
- TrustManager[] tm = tmf.getTrustManagers();
-
- KeyManagerFactory kmfactory = createKeyManagerFactory();
- kmfactory.init(keystore, pwd);
- KeyManager[] km = kmfactory.getKeyManagers();
-
- SSLContext serverSSLContext = SSLContext.getInstance("TLS");
- serverSSLContext.init(km, tm, null);
-
- LocalTestServer localServer = new LocalTestServer(serverSSLContext);
- localServer.registerDefaultHandlers();
- return localServer;
+ protected NHttpConnectionFactory<NHttpServerIOTarget> createServerConnectionFactory(
+ final HttpParams params) throws Exception {
+ return new SSLNHttpServerConnectionFactory(SSLTestContexts.createServerSSLContext(), null, params);
}
@Override
- protected PoolingClientConnectionManager createConnectionManager(
- final ConnectingIOReactor ioreactor) throws Exception {
- ClassLoader cl = getClass().getClassLoader();
- URL url = cl.getResource("test.keystore");
- KeyStore keystore = KeyStore.getInstance("jks");
- char[] pwd = "nopassword".toCharArray();
- keystore.load(url.openStream(), pwd);
-
- TrustManagerFactory tmf = createTrustManagerFactory();
- tmf.init(keystore);
- TrustManager[] tm = tmf.getTrustManagers();
-
- SSLContext clientSSLContext = SSLContext.getInstance("TLS");
- clientSSLContext.init(null, tm, null);
-
- SchemeRegistry schemeRegistry = new SchemeRegistry();
- schemeRegistry.register(new Scheme("http", 80, null));
- schemeRegistry.register(new Scheme("https", 443, new SSLLayeringStrategy(clientSSLContext)));
- return new PoolingClientConnectionManager(ioreactor, schemeRegistry);
+ protected String getSchemeName() {
+ return "https";
}
@Override
- public void startServer() throws Exception {
- super.startServer();
- int port = this.localServer.getServiceAddress().getPort();
- this.target = new HttpHost("localhost", port, "https");
- }
-
- @Test
- public void testSingleGet() throws Exception {
- HttpGet httpget = new HttpGet("/random/2048");
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, null);
- HttpResponse response = future.get();
- Assert.assertNotNull(response);
- Assert.assertEquals(200, response.getStatusLine().getStatusCode());
- }
-
- @Test
- public void testSinglePost() throws Exception {
- byte[] b1 = new byte[1024];
- Random rnd = new Random(System.currentTimeMillis());
- rnd.nextBytes(b1);
-
- HttpPost httppost = new HttpPost("/echo/stuff");
- httppost.setEntity(new NByteArrayEntity(b1));
-
- Future<HttpResponse> future = this.httpclient.execute(this.target, httppost, null);
- HttpResponse response = future.get();
- Assert.assertNotNull(response);
- Assert.assertEquals(200, response.getStatusLine().getStatusCode());
- HttpEntity entity = response.getEntity();
- Assert.assertNotNull(entity);
- byte[] b2 = EntityUtils.toByteArray(entity);
- Assert.assertArrayEquals(b1, b2);
- }
-
- @Test
- public void testMultiplePostsOverMultipleConnections() throws Exception {
- byte[] b1 = new byte[1024];
- Random rnd = new Random(System.currentTimeMillis());
- rnd.nextBytes(b1);
-
- int reqCount = 20;
-
- this.sessionManager.setDefaultMaxPerRoute(reqCount);
- this.sessionManager.setMaxTotal(100);
-
- Queue<Future<HttpResponse>> queue = new LinkedList<Future<HttpResponse>>();
-
- for (int i = 0; i < reqCount; i++) {
- HttpPost httppost = new HttpPost("/echo/stuff");
- httppost.setEntity(new NByteArrayEntity(b1));
- queue.add(this.httpclient.execute(this.target, httppost, null));
- }
-
- while (!queue.isEmpty()) {
- Future<HttpResponse> future = queue.remove();
- HttpResponse response = future.get();
- Assert.assertNotNull(response);
- Assert.assertEquals(200, response.getStatusLine().getStatusCode());
- HttpEntity entity = response.getEntity();
- Assert.assertNotNull(entity);
- byte[] b2 = EntityUtils.toByteArray(entity);
- Assert.assertArrayEquals(b1, b2);
- }
- }
-
- @Test
- public void testMultiplePostsOverSingleConnection() throws Exception {
- byte[] b1 = new byte[1024];
- Random rnd = new Random(System.currentTimeMillis());
- rnd.nextBytes(b1);
-
- int reqCount = 20;
-
- this.sessionManager.setDefaultMaxPerRoute(1);
- this.sessionManager.setMaxTotal(100);
-
- Queue<Future<HttpResponse>> queue = new LinkedList<Future<HttpResponse>>();
-
- for (int i = 0; i < reqCount; i++) {
- HttpPost httppost = new HttpPost("/echo/stuff");
- httppost.setEntity(new NByteArrayEntity(b1));
- queue.add(this.httpclient.execute(this.target, httppost, null));
- }
-
- while (!queue.isEmpty()) {
- Future<HttpResponse> future = queue.remove();
- HttpResponse response = future.get();
- Assert.assertNotNull(response);
- Assert.assertEquals(200, response.getStatusLine().getStatusCode());
- HttpEntity entity = response.getEntity();
- Assert.assertNotNull(entity);
- byte[] b2 = EntityUtils.toByteArray(entity);
- Assert.assertArrayEquals(b1, b2);
- }
- }
-
- @Test
- public void testRequestFailure() throws Exception {
- HttpGet httpget = new HttpGet("/random/2048");
- HttpAsyncRequestProducer requestProducer = HttpAsyncMethods.create(this.target, httpget) ;
- BasicHttpAsyncResponseConsumer responseConsumer = new BasicHttpAsyncResponseConsumer() {
-
- @Override
- public void consumeContent(final ContentDecoder decoder, final IOControl ioctrl)
- throws IOException {
- throw new IOException("Kaboom");
- }
-
- };
- Future<HttpResponse> future = this.httpclient.execute(requestProducer, responseConsumer, null);
- try {
- future.get();
- Assert.fail("ExecutionException expected");
- } catch (ExecutionException ex) {
- Throwable t = ex.getCause();
- Assert.assertNotNull(t);
- Assert.assertTrue(t instanceof IOException);
- Assert.assertEquals("Kaboom", t.getMessage());
- }
+ public void initClient() throws Exception {
+ super.initClient();
+ this.connMgr.getSchemeRegistry().register(new Scheme("https", 443,
+ new SSLLayeringStrategy(SSLTestContexts.createClientSSLContext())));
}
}
Modified: httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/impl/nio/client/TestRedirects.java
URL: http://svn.apache.org/viewvc/httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/impl/nio/client/TestRedirects.java?rev=1174357&r1=1174356&r2=1174357&view=diff
==============================================================================
--- httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/impl/nio/client/TestRedirects.java (original)
+++ httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/impl/nio/client/TestRedirects.java Thu Sep 22 20:03:35 2011
@@ -34,8 +34,10 @@ import java.util.concurrent.ExecutionExc
import java.util.concurrent.Future;
import org.apache.http.Header;
+import org.apache.http.HttpAsyncTestBase;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
+import org.apache.http.HttpInetConnection;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
@@ -49,53 +51,104 @@ import org.apache.http.client.methods.Ht
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.SM;
import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;
-import org.apache.http.localserver.AsyncHttpTestBase;
+import org.apache.http.impl.nio.DefaultNHttpServerConnectionFactory;
import org.apache.http.message.BasicHeader;
+import org.apache.http.nio.NHttpConnectionFactory;
+import org.apache.http.nio.NHttpServerIOTarget;
import org.apache.http.nio.entity.NStringEntity;
+import org.apache.http.nio.protocol.BufferingAsyncRequestHandler;
+import org.apache.http.nio.protocol.HttpAsyncExpectationVerifier;
+import org.apache.http.nio.protocol.HttpAsyncRequestHandlerRegistry;
+import org.apache.http.nio.protocol.HttpAsyncRequestHandlerResolver;
+import org.apache.http.nio.protocol.HttpAsyncServiceHandler;
+import org.apache.http.nio.reactor.IOReactorStatus;
+import org.apache.http.nio.reactor.ListenerEndpoint;
+import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
+import org.junit.After;
import org.junit.Assert;
+import org.junit.Before;
import org.junit.Test;
/**
* Redirection test cases.
*/
-public class TestRedirects extends AsyncHttpTestBase {
+public class TestRedirects extends HttpAsyncTestBase {
- private static class BasicRedirectService implements HttpRequestHandler {
+ @Before
+ public void setUp() throws Exception {
+ initServer();
+ initClient();
+ }
- private int statuscode = HttpStatus.SC_MOVED_TEMPORARILY;
- private String host = null;
- private int port;
+ @After
+ public void tearDown() throws Exception {
+ shutDownClient();
+ shutDownServer();
+ }
- public BasicRedirectService(final String host, int port, int statuscode) {
- super();
- this.host = host;
- this.port = port;
- if (statuscode > 0) {
- this.statuscode = statuscode;
- }
- }
+ @Override
+ protected NHttpConnectionFactory<NHttpServerIOTarget> createServerConnectionFactory(
+ final HttpParams params) throws Exception {
+ return new DefaultNHttpServerConnectionFactory(params);
+ }
+
+ @Override
+ protected String getSchemeName() {
+ return "http";
+ }
+
+ private HttpHost start(
+ final HttpAsyncRequestHandlerResolver requestHandlerResolver,
+ final HttpAsyncExpectationVerifier expectationVerifier) throws Exception {
+ HttpAsyncServiceHandler serviceHandler = new HttpAsyncServiceHandler(
+ requestHandlerResolver,
+ expectationVerifier,
+ this.serverHttpProc,
+ new DefaultConnectionReuseStrategy(),
+ this.serverParams);
+ this.server.start(serviceHandler);
+ this.httpclient.start();
- public BasicRedirectService(final String host, int port) {
- this(host, port, -1);
+ ListenerEndpoint endpoint = this.server.getListenerEndpoint();
+ endpoint.waitFor();
+
+ Assert.assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
+ InetSocketAddress address = (InetSocketAddress) endpoint.getAddress();
+ HttpHost target = new HttpHost("localhost", address.getPort(), getSchemeName());
+ return target;
+ }
+
+ static class BasicRedirectService implements HttpRequestHandler {
+
+ private final String schemeName;
+ private final int statuscode;
+
+ public BasicRedirectService(final String schemeName, int statuscode) {
+ super();
+ this.schemeName = schemeName;
+ this.statuscode = statuscode;
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
+ HttpInetConnection conn = (HttpInetConnection) context.getAttribute(
+ ExecutionContext.HTTP_CONNECTION);
ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
String uri = request.getRequestLine().getUri();
if (uri.equals("/oldlocation/")) {
+ String redirectUrl = this.schemeName + "://localhost:" + conn.getLocalPort() + "/newlocation/";
response.setStatusLine(ver, this.statuscode);
- response.addHeader(new BasicHeader("Location",
- "http://" + this.host + ":" + this.port + "/newlocation/"));
+ response.addHeader(new BasicHeader("Location", redirectUrl));
response.addHeader(new BasicHeader("Connection", "close"));
} else if (uri.equals("/newlocation/")) {
response.setStatusLine(ver, HttpStatus.SC_OK);
@@ -107,7 +160,7 @@ public class TestRedirects extends Async
}
}
- private static class CircularRedirectService implements HttpRequestHandler {
+ static class CircularRedirectService implements HttpRequestHandler {
public CircularRedirectService() {
super();
@@ -131,7 +184,7 @@ public class TestRedirects extends Async
}
}
- private static class RelativeRedirectService implements HttpRequestHandler {
+ static class RelativeRedirectService implements HttpRequestHandler {
public RelativeRedirectService() {
super();
@@ -156,7 +209,7 @@ public class TestRedirects extends Async
}
}
- private static class RelativeRedirectService2 implements HttpRequestHandler {
+ static class RelativeRedirectService2 implements HttpRequestHandler {
public RelativeRedirectService2() {
super();
@@ -181,23 +234,35 @@ public class TestRedirects extends Async
}
}
- private static class BogusRedirectService implements HttpRequestHandler {
- private String url;
+ static class BogusRedirectService implements HttpRequestHandler {
+
+ private final String schemeName;
+ private final String url;
+ private final boolean absolute;
- public BogusRedirectService(String redirectUrl) {
+ public BogusRedirectService(final String schemeName, final String url, final boolean absolute) {
super();
- this.url = redirectUrl;
+ this.schemeName = schemeName;
+ this.url = url;
+ this.absolute = absolute;
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
+ HttpInetConnection conn = (HttpInetConnection) context.getAttribute(
+ ExecutionContext.HTTP_CONNECTION);
+ String redirectUrl = this.url;
+ if (!this.absolute) {
+ redirectUrl = this.schemeName + "://localhost:" + conn.getLocalPort() + redirectUrl;
+ }
+
ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
String uri = request.getRequestLine().getUri();
if (uri.equals("/oldlocation/")) {
response.setStatusLine(ver, HttpStatus.SC_MOVED_TEMPORARILY);
- response.addHeader(new BasicHeader("Location", url));
+ response.addHeader(new BasicHeader("Location", redirectUrl));
} else if (uri.equals("/relativelocation/")) {
response.setStatusLine(ver, HttpStatus.SC_OK);
StringEntity entity = new StringEntity("Successful redirect");
@@ -210,16 +275,16 @@ public class TestRedirects extends Async
@Test
public void testBasicRedirect300() throws Exception {
- String host = this.target.getHostName();
- int port = this.target.getPort();
- this.localServer.register("*",
- new BasicRedirectService(host, port, HttpStatus.SC_MULTIPLE_CHOICES));
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(
+ new BasicRedirectService(getSchemeName(), HttpStatus.SC_MULTIPLE_CHOICES)));
+ HttpHost target = start(registry, null);
HttpContext context = new BasicHttpContext();
HttpGet httpget = new HttpGet("/oldlocation/");
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, context, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, context, null);
HttpResponse response = future.get();
Assert.assertNotNull(response);
@@ -232,61 +297,58 @@ public class TestRedirects extends Async
@Test
public void testBasicRedirect301() throws Exception {
- String host = this.target.getHostName();
- int port = this.target.getPort();
- this.localServer.register("*",
- new BasicRedirectService(host, port, HttpStatus.SC_MOVED_PERMANENTLY));
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(
+ new BasicRedirectService(getSchemeName(), HttpStatus.SC_MOVED_PERMANENTLY)));
+ HttpHost target = start(registry, null);
HttpContext context = new BasicHttpContext();
HttpGet httpget = new HttpGet("/oldlocation/");
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, context, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, context, null);
HttpResponse response = future.get();
Assert.assertNotNull(response);
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
- HttpHost targetHost = (HttpHost) context.getAttribute(
+ HttpHost host = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
- Assert.assertEquals(host, targetHost.getHostName());
- Assert.assertEquals(port, targetHost.getPort());
+ Assert.assertEquals(target, host);
}
@Test
public void testBasicRedirect302() throws Exception {
- String host = this.target.getHostName();
- int port = this.target.getPort();
- this.localServer.register("*",
- new BasicRedirectService(host, port, HttpStatus.SC_MOVED_TEMPORARILY));
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(
+ new BasicRedirectService(getSchemeName(), HttpStatus.SC_MOVED_TEMPORARILY)));
+ HttpHost target = start(registry, null);
HttpContext context = new BasicHttpContext();
HttpGet httpget = new HttpGet("/oldlocation/");
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, context, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, context, null);
HttpResponse response = future.get();
Assert.assertNotNull(response);
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
- HttpHost targetHost = (HttpHost) context.getAttribute(
+ HttpHost host = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
- Assert.assertEquals(host, targetHost.getHostName());
- Assert.assertEquals(port, targetHost.getPort());
+ Assert.assertEquals(target, host);
}
@Test
public void testBasicRedirect302NoLocation() throws Exception {
- String host = this.target.getHostName();
- int port = this.target.getPort();
- this.localServer.register("*", new HttpRequestHandler() {
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(new HttpRequestHandler() {
public void handle(
final HttpRequest request,
@@ -295,65 +357,64 @@ public class TestRedirects extends Async
response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY);
}
- });
+ }));
+ HttpHost target = start(registry, null);
HttpContext context = new BasicHttpContext();
HttpGet httpget = new HttpGet("/oldlocation/");
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, context, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, context, null);
HttpResponse response = future.get();
Assert.assertNotNull(response);
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
- HttpHost targetHost = (HttpHost) context.getAttribute(
+ HttpHost host = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
Assert.assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getStatusLine().getStatusCode());
Assert.assertEquals("/oldlocation/", reqWrapper.getRequestLine().getUri());
- Assert.assertEquals(host, targetHost.getHostName());
- Assert.assertEquals(port, targetHost.getPort());
+ Assert.assertEquals(target, host);
}
@Test
public void testBasicRedirect303() throws Exception {
- String host = this.target.getHostName();
- int port = this.target.getPort();
- this.localServer.register("*",
- new BasicRedirectService(host, port, HttpStatus.SC_SEE_OTHER));
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(
+ new BasicRedirectService(getSchemeName(), HttpStatus.SC_SEE_OTHER)));
+ HttpHost target = start(registry, null);
HttpContext context = new BasicHttpContext();
HttpGet httpget = new HttpGet("/oldlocation/");
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, context, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, context, null);
HttpResponse response = future.get();
Assert.assertNotNull(response);
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
- HttpHost targetHost = (HttpHost) context.getAttribute(
+ HttpHost host = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
- Assert.assertEquals(host, targetHost.getHostName());
- Assert.assertEquals(port, targetHost.getPort());
+ Assert.assertEquals(target, host);
}
@Test
public void testBasicRedirect304() throws Exception {
- String host = this.target.getHostName();
- int port = this.target.getPort();
- this.localServer.register("*",
- new BasicRedirectService(host, port, HttpStatus.SC_NOT_MODIFIED));
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(
+ new BasicRedirectService(getSchemeName(), HttpStatus.SC_NOT_MODIFIED)));
+ HttpHost target = start(registry, null);
HttpContext context = new BasicHttpContext();
HttpGet httpget = new HttpGet("/oldlocation/");
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, context, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, context, null);
HttpResponse response = future.get();
Assert.assertNotNull(response);
@@ -366,16 +427,16 @@ public class TestRedirects extends Async
@Test
public void testBasicRedirect305() throws Exception {
- String host = this.target.getHostName();
- int port = this.target.getPort();
- this.localServer.register("*",
- new BasicRedirectService(host, port, HttpStatus.SC_USE_PROXY));
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(
+ new BasicRedirectService(getSchemeName(), HttpStatus.SC_USE_PROXY)));
+ HttpHost target = start(registry, null);
HttpContext context = new BasicHttpContext();
HttpGet httpget = new HttpGet("/oldlocation/");
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, context, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, context, null);
HttpResponse response = future.get();
Assert.assertNotNull(response);
@@ -388,40 +449,41 @@ public class TestRedirects extends Async
@Test
public void testBasicRedirect307() throws Exception {
- String host = this.target.getHostName();
- int port = this.target.getPort();
- this.localServer.register("*",
- new BasicRedirectService(host, port, HttpStatus.SC_TEMPORARY_REDIRECT));
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(
+ new BasicRedirectService(getSchemeName(), HttpStatus.SC_TEMPORARY_REDIRECT)));
+ HttpHost target = start(registry, null);
HttpContext context = new BasicHttpContext();
HttpGet httpget = new HttpGet("/oldlocation/");
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, context, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, context, null);
HttpResponse response = future.get();
Assert.assertNotNull(response);
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
- HttpHost targetHost = (HttpHost) context.getAttribute(
+ HttpHost host = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
- Assert.assertEquals(host, targetHost.getHostName());
- Assert.assertEquals(port, targetHost.getPort());
+ Assert.assertEquals(target, host);
}
@Test(expected=ExecutionException.class)
public void testMaxRedirectCheck() throws Exception {
- this.localServer.register("*", new CircularRedirectService());
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(new CircularRedirectService()));
+ HttpHost target = start(registry, null);
this.httpclient.getParams().setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
this.httpclient.getParams().setIntParameter(ClientPNames.MAX_REDIRECTS, 5);
HttpGet httpget = new HttpGet("/circular-oldlocation/");
try {
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, null);
future.get();
} catch (ExecutionException e) {
Assert.assertTrue(e.getCause() instanceof RedirectException);
@@ -431,14 +493,16 @@ public class TestRedirects extends Async
@Test(expected=ExecutionException.class)
public void testCircularRedirect() throws Exception {
- this.localServer.register("*", new CircularRedirectService());
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(new CircularRedirectService()));
+ HttpHost target = start(registry, null);
this.httpclient.getParams().setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, false);
HttpGet httpget = new HttpGet("/circular-oldlocation/");
try {
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, null);
future.get();
} catch (ExecutionException e) {
Assert.assertTrue(e.getCause() instanceof CircularRedirectException);
@@ -448,16 +512,17 @@ public class TestRedirects extends Async
@Test
public void testPostNoRedirect() throws Exception {
- String host = this.target.getHostName();
- int port = this.target.getPort();
- this.localServer.register("*", new BasicRedirectService(host, port));
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(
+ new BasicRedirectService(getSchemeName(), HttpStatus.SC_MOVED_TEMPORARILY)));
+ HttpHost target = start(registry, null);
HttpContext context = new BasicHttpContext();
HttpPost httppost = new HttpPost("/oldlocation/");
httppost.setEntity(new NStringEntity("stuff"));
- Future<HttpResponse> future = this.httpclient.execute(this.target, httppost, context, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httppost, context, null);
HttpResponse response = future.get();
Assert.assertNotNull(response);
@@ -471,17 +536,17 @@ public class TestRedirects extends Async
@Test
public void testPostRedirectSeeOther() throws Exception {
- String host = this.target.getHostName();
- int port = this.target.getPort();
- this.localServer.register("*", new BasicRedirectService(host, port,
- HttpStatus.SC_SEE_OTHER));
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(
+ new BasicRedirectService(getSchemeName(), HttpStatus.SC_SEE_OTHER)));
+ HttpHost target = start(registry, null);
HttpContext context = new BasicHttpContext();
HttpPost httppost = new HttpPost("/oldlocation/");
httppost.setEntity(new NStringEntity("stuff"));
- Future<HttpResponse> future = this.httpclient.execute(this.target, httppost, context, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httppost, context, null);
HttpResponse response = future.get();
Assert.assertNotNull(response);
@@ -495,9 +560,9 @@ public class TestRedirects extends Async
@Test
public void testRelativeRedirect() throws Exception {
- String host = this.target.getHostName();
- int port = this.target.getPort();
- this.localServer.register("*", new RelativeRedirectService());
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(new RelativeRedirectService()));
+ HttpHost target = start(registry, null);
HttpContext context = new BasicHttpContext();
@@ -505,26 +570,25 @@ public class TestRedirects extends Async
ClientPNames.REJECT_RELATIVE_REDIRECT, false);
HttpGet httpget = new HttpGet("/oldlocation/");
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, context, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, context, null);
HttpResponse response = future.get();
Assert.assertNotNull(response);
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
- HttpHost targetHost = (HttpHost) context.getAttribute(
+ HttpHost host = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("/relativelocation/", reqWrapper.getRequestLine().getUri());
- Assert.assertEquals(host, targetHost.getHostName());
- Assert.assertEquals(port, targetHost.getPort());
+ Assert.assertEquals(target, host);
}
@Test
public void testRelativeRedirect2() throws Exception {
- String host = this.target.getHostName();
- int port = this.target.getPort();
- this.localServer.register("*", new RelativeRedirectService2());
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(new RelativeRedirectService2()));
+ HttpHost target = start(registry, null);
HttpContext context = new BasicHttpContext();
@@ -532,31 +596,32 @@ public class TestRedirects extends Async
ClientPNames.REJECT_RELATIVE_REDIRECT, false);
HttpGet httpget = new HttpGet("/test/oldlocation");
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, context, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, context, null);
HttpResponse response = future.get();
Assert.assertNotNull(response);
HttpRequest reqWrapper = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
- HttpHost targetHost = (HttpHost) context.getAttribute(
+ HttpHost host = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Assert.assertEquals("/test/relativelocation", reqWrapper.getRequestLine().getUri());
- Assert.assertEquals(host, targetHost.getHostName());
- Assert.assertEquals(port, targetHost.getPort());
+ Assert.assertEquals(target, host);
}
@Test(expected=ExecutionException.class)
public void testRejectRelativeRedirect() throws Exception {
- this.localServer.register("*", new RelativeRedirectService());
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(new RelativeRedirectService()));
+ HttpHost target = start(registry, null);
this.httpclient.getParams().setBooleanParameter(
ClientPNames.REJECT_RELATIVE_REDIRECT, true);
HttpGet httpget = new HttpGet("/oldlocation/");
try {
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, null);
future.get();
} catch (ExecutionException e) {
Assert.assertTrue(e.getCause() instanceof ProtocolException);
@@ -566,12 +631,15 @@ public class TestRedirects extends Async
@Test(expected=ExecutionException.class)
public void testRejectBogusRedirectLocation() throws Exception {
- this.localServer.register("*", new BogusRedirectService("xxx://bogus"));
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(
+ new BogusRedirectService(getSchemeName(), "xxx://bogus", true)));
+ HttpHost target = start(registry, null);
HttpGet httpget = new HttpGet("/oldlocation/");
try {
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, null);
future.get();
} catch (ExecutionException e) {
Assert.assertTrue(e.getCause() instanceof HttpException);
@@ -581,15 +649,14 @@ public class TestRedirects extends Async
@Test(expected=ExecutionException.class)
public void testRejectInvalidRedirectLocation() throws Exception {
- InetSocketAddress address = this.localServer.getServiceAddress();
- int port = address.getPort();
- String host = address.getHostName();
- this.localServer.register("*",
- new BogusRedirectService("http://"+ host +":"+ port +"/newlocation/?p=I have spaces"));
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(
+ new BogusRedirectService(getSchemeName(), "/newlocation/?p=I have spaces", false)));
+ HttpHost target = start(registry, null);
HttpGet httpget = new HttpGet("/oldlocation/");
try {
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, null);
future.get();
} catch (ExecutionException e) {
Assert.assertTrue(e.getCause() instanceof ProtocolException);
@@ -599,16 +666,16 @@ public class TestRedirects extends Async
@Test
public void testRedirectWithCookie() throws Exception {
- String host = this.target.getHostName();
- int port = this.target.getPort();
- this.localServer.register("*",
- new BasicRedirectService(host, port));
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(
+ new BasicRedirectService(getSchemeName(), HttpStatus.SC_MOVED_TEMPORARILY)));
+ HttpHost target = start(registry, null);
CookieStore cookieStore = new BasicCookieStore();
this.httpclient.setCookieStore(cookieStore);
BasicClientCookie cookie = new BasicClientCookie("name", "value");
- cookie.setDomain(host);
+ cookie.setDomain(target.getHostName());
cookie.setPath("/");
cookieStore.addCookie(cookie);
@@ -616,7 +683,7 @@ public class TestRedirects extends Async
HttpContext context = new BasicHttpContext();
HttpGet httpget = new HttpGet("/oldlocation/");
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, context, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, context, null);
HttpResponse response = future.get();
Assert.assertNotNull(response);
@@ -632,10 +699,10 @@ public class TestRedirects extends Async
@Test
public void testDefaultHeadersRedirect() throws Exception {
- String host = this.target.getHostName();
- int port = this.target.getPort();
- this.localServer.register("*",
- new BasicRedirectService(host, port));
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(
+ new BasicRedirectService(getSchemeName(), HttpStatus.SC_MOVED_TEMPORARILY)));
+ HttpHost target = start(registry, null);
HttpContext context = new BasicHttpContext();
@@ -646,7 +713,7 @@ public class TestRedirects extends Async
HttpGet httpget = new HttpGet("/oldlocation/");
- Future<HttpResponse> future = this.httpclient.execute(this.target, httpget, context, null);
+ Future<HttpResponse> future = this.httpclient.execute(target, httpget, context, null);
HttpResponse response = future.get();
Assert.assertNotNull(response);
Propchange: httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/localserver/
------------------------------------------------------------------------------
--- svn:mergeinfo (original)
+++ svn:mergeinfo Thu Sep 22 20:03:35 2011
@@ -1,4 +1,5 @@
/httpcomponents/httpasyncclient/branches/conn-mgmt-redesign/httpasyncclient/src/test/java/org/apache/http/localserver:1155312-1159070
+/httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/localserver:1167093-1174316
/httpcomponents/httpclient/branches/4.0.x/httpclient/src/test/java/org/apache/http/localserver:950681-950688
/httpcomponents/httpclient/branches/4.1.x/httpclient/src/test/java/org/apache/http/localserver:1079518-1080165
/httpcomponents/httpclient/branches/branch_4_1/httpclient/src/test/java/org/apache/http/localserver:755593-811107
Modified: httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/localserver/EchoHandler.java
URL: http://svn.apache.org/viewvc/httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/localserver/EchoHandler.java?rev=1174357&r1=1174356&r2=1174357&view=diff
==============================================================================
--- httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/localserver/EchoHandler.java (original)
+++ httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/localserver/EchoHandler.java Thu Sep 22 20:03:35 2011
@@ -35,21 +35,14 @@ import org.apache.http.HttpEntityEnclosi
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
-import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
-import org.apache.http.entity.ByteArrayEntity;
+import org.apache.http.nio.entity.NByteArrayEntity;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;
-
-
/**
* A handler that echos the incoming request entity.
- *
- *
- *
- * <!-- empty lines to avoid 'svn diff' problems -->
*/
public class EchoHandler
implements HttpRequestHandler {
@@ -94,16 +87,11 @@ public class EchoHandler
data = EntityUtils.toByteArray(entity);
}
- ByteArrayEntity bae = new ByteArrayEntity(data);
+ NByteArrayEntity bae = new NByteArrayEntity(data);
if (entity != null) {
bae.setContentType(entity.getContentType());
}
- entity = bae;
-
- response.setStatusCode(HttpStatus.SC_OK);
- response.setEntity(entity);
-
- } // handle
-
+ response.setEntity(bae);
+ }
-} // class EchoHandler
+}
Modified: httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/localserver/RandomHandler.java
URL: http://svn.apache.org/viewvc/httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/localserver/RandomHandler.java?rev=1174357&r1=1174356&r2=1174357&view=diff
==============================================================================
--- httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/localserver/RandomHandler.java (original)
+++ httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/localserver/RandomHandler.java Thu Sep 22 20:03:35 2011
@@ -28,8 +28,6 @@
package org.apache.http.localserver;
import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
@@ -38,23 +36,28 @@ import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
-import org.apache.http.entity.AbstractHttpEntity;
+import org.apache.http.entity.ContentType;
+import org.apache.http.nio.entity.NByteArrayEntity;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
-
-
/**
* A handler that generates random data.
- *
- *
- *
- * <!-- empty lines to avoid 'svn diff' problems -->
*/
-public class RandomHandler
- implements HttpRequestHandler {
+public class RandomHandler implements HttpRequestHandler {
- // public default constructor
+ private final static byte[] RANGE;
+ static {
+ byte[] range = null;
+ try {
+ range = ("abcdefghijklmnopqrstuvwxyz" +
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789"
+ ).getBytes("US-ASCII");
+ } catch (UnsupportedEncodingException uex) {
+ // never, US-ASCII is guaranteed
+ }
+ RANGE = range;
+ }
/**
* Handles a request by generating random data.
@@ -104,143 +107,21 @@ public class RandomHandler
}
if (length >= 0) {
-
- response.setStatusCode(HttpStatus.SC_OK);
-
- if (!"HEAD".equals(method)) {
- RandomEntity entity = new RandomEntity(length);
- entity.setContentType("text/plain; charset=US-ASCII");
- response.setEntity(entity);
- } else {
- response.setHeader("Content-Type",
- "text/plain; charset=US-ASCII");
- response.setHeader("Content-Length",
- String.valueOf(length));
- }
- }
-
- } // handle
-
-
- /**
- * An entity that generates random data.
- * This is an outgoing entity, it supports {@link #writeTo writeTo}
- * but not {@link #getContent getContent}.
- */
- public static class RandomEntity extends AbstractHttpEntity {
-
- /** The range from which to generate random data. */
- private final static byte[] RANGE;
- static {
- byte[] range = null;
- try {
- range = ("abcdefghijklmnopqrstuvwxyz" +
- "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789"
- ).getBytes("US-ASCII");
- } catch (UnsupportedEncodingException uex) {
- // never, US-ASCII is guaranteed
- }
- RANGE = range;
- }
-
-
- /** The length of the random data to generate. */
- protected final long length;
-
-
- /**
- * Creates a new entity generating the given amount of data.
- *
- * @param len the number of random bytes to generate,
- * 0 to maxint
- */
- public RandomEntity(long len) {
- if (len < 0L)
- throw new IllegalArgumentException
- ("Length must not be negative");
- if (len > Integer.MAX_VALUE)
- throw new IllegalArgumentException
- ("Length must not exceed Integer.MAX_VALUE");
-
- length = len;
- }
-
- /**
- * Tells that this entity is not streaming.
- *
- * @return false
- */
- public final boolean isStreaming() {
- return false;
- }
-
- /**
- * Tells that this entity is repeatable, in a way.
- * Repetitions will generate different random data,
- * unless perchance the same random data is generated twice.
- *
- * @return <code>true</code>
- */
- public boolean isRepeatable() {
- return true;
- }
-
- /**
- * Obtains the size of the random data.
- *
- * @return the number of random bytes to generate
- */
- public long getContentLength() {
- return length;
- }
-
-
- /**
- * Not supported.
- * This method throws an exception.
- *
- * @return never anything
- */
- public InputStream getContent() {
- throw new UnsupportedOperationException();
- }
-
-
- /**
- * Generates the random content.
- *
- * @param out where to write the content to
- */
- public void writeTo(OutputStream out) throws IOException {
-
- final int blocksize = 2048;
- int remaining = (int) length; // range checked in constructor
- byte[] data = new byte[Math.min(remaining, blocksize)];
-
- while (remaining > 0) {
- final int end = Math.min(remaining, data.length);
-
+ byte[] data = new byte[length];
+ for (int i = 0; i < length; i++) {
double value = 0.0;
- for (int i = 0; i < end; i++) {
- // we get 5 random characters out of one random value
- if (i%5 == 0) {
- value = Math.random();
- }
- value = value * RANGE.length;
- int d = (int) value;
- value = value - d;
- data[i] = RANGE[d];
+ // we get 5 random characters out of one random value
+ if (i%5 == 0) {
+ value = Math.random();
}
- out.write(data, 0, end);
- out.flush();
-
- remaining = remaining - end;
+ value = value * RANGE.length;
+ int d = (int) value;
+ value = value - d;
+ data[i] = RANGE[d];
}
- out.close();
-
- } // writeTo
-
- } // class RandomEntity
-
+ NByteArrayEntity bae = new NByteArrayEntity(data, ContentType.DEFAULT_TEXT);
+ response.setEntity(bae);
+ }
+ }
-} // class RandomHandler
+}
Modified: httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/nio/client/methods/TestAsyncConsumers.java
URL: http://svn.apache.org/viewvc/httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/nio/client/methods/TestAsyncConsumers.java?rev=1174357&r1=1174356&r2=1174357&view=diff
==============================================================================
--- httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/nio/client/methods/TestAsyncConsumers.java (original)
+++ httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/nio/client/methods/TestAsyncConsumers.java Thu Sep 22 20:03:35 2011
@@ -27,25 +27,95 @@
package org.apache.http.nio.client.methods;
import java.io.IOException;
+import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
+import org.apache.http.HttpAsyncTestBase;
import org.apache.http.HttpException;
+import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.entity.ContentType;
-import org.apache.http.localserver.AsyncHttpTestBase;
+import org.apache.http.impl.DefaultConnectionReuseStrategy;
+import org.apache.http.impl.nio.DefaultNHttpServerConnectionFactory;
+import org.apache.http.localserver.EchoHandler;
+import org.apache.http.localserver.RandomHandler;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
-import org.apache.http.nio.client.HttpAsyncRequestProducer;
+import org.apache.http.nio.NHttpConnectionFactory;
+import org.apache.http.nio.NHttpServerIOTarget;
+import org.apache.http.nio.protocol.BufferingAsyncRequestHandler;
+import org.apache.http.nio.protocol.HttpAsyncExpectationVerifier;
+import org.apache.http.nio.protocol.HttpAsyncRequestHandlerRegistry;
+import org.apache.http.nio.protocol.HttpAsyncRequestHandlerResolver;
+import org.apache.http.nio.protocol.HttpAsyncRequestProducer;
+import org.apache.http.nio.protocol.HttpAsyncServiceHandler;
+import org.apache.http.nio.reactor.IOReactorStatus;
+import org.apache.http.nio.reactor.ListenerEndpoint;
+import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
+import org.apache.http.protocol.HttpContext;
+import org.junit.After;
import org.junit.Assert;
+import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
-public class TestAsyncConsumers extends AsyncHttpTestBase {
+public class TestAsyncConsumers extends HttpAsyncTestBase {
+
+ @Before
+ public void setUp() throws Exception {
+ initServer();
+ initClient();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ shutDownClient();
+ shutDownServer();
+ }
+
+ @Override
+ protected NHttpConnectionFactory<NHttpServerIOTarget> createServerConnectionFactory(
+ final HttpParams params) throws Exception {
+ return new DefaultNHttpServerConnectionFactory(params);
+ }
+
+ @Override
+ protected String getSchemeName() {
+ return "http";
+ }
+
+ private HttpHost start(
+ final HttpAsyncRequestHandlerResolver requestHandlerResolver,
+ final HttpAsyncExpectationVerifier expectationVerifier) throws Exception {
+ HttpAsyncServiceHandler serviceHandler = new HttpAsyncServiceHandler(
+ requestHandlerResolver,
+ expectationVerifier,
+ this.serverHttpProc,
+ new DefaultConnectionReuseStrategy(),
+ this.serverParams);
+ this.server.start(serviceHandler);
+ this.httpclient.start();
+
+ ListenerEndpoint endpoint = this.server.getListenerEndpoint();
+ endpoint.waitFor();
+
+ Assert.assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
+ InetSocketAddress address = (InetSocketAddress) endpoint.getAddress();
+ HttpHost target = new HttpHost("localhost", address.getPort(), getSchemeName());
+ return target;
+ }
+
+ private HttpHost start() throws Exception {
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("/echo/*", new BufferingAsyncRequestHandler(new EchoHandler()));
+ registry.register("/random/*", new BufferingAsyncRequestHandler(new RandomHandler()));
+ return start(registry, null);
+ }
static class ByteCountingConsumer extends AsyncByteConsumer<Long> {
@@ -69,11 +139,7 @@ public class TestAsyncConsumers extends
}
@Override
- protected void onCleanup() {
- }
-
- @Override
- protected Long buildResult() throws Exception {
+ protected Long buildResult(final HttpContext context) throws Exception {
return count.get();
}
@@ -81,8 +147,9 @@ public class TestAsyncConsumers extends
@Test
public void testByteConsumer() throws Exception {
+ HttpHost target = start();
for (int i = 0; i < 5; i++) {
- HttpAsyncRequestProducer httpget = HttpAsyncMethods.createGet(this.target.toURI() + "/random/20480");
+ HttpAsyncRequestProducer httpget = HttpAsyncMethods.createGet(target.toURI() + "/random/20480");
AsyncByteConsumer<Long> consumer = new ByteCountingConsumer();
Future<Long> future = this.httpclient.execute(httpget, consumer, null);
Long count = future.get();
@@ -92,8 +159,9 @@ public class TestAsyncConsumers extends
@Test
public void testByteConsumerSmallBufffer() throws Exception {
+ HttpHost target = start();
for (int i = 0; i < 5; i++) {
- HttpAsyncRequestProducer httpget = HttpAsyncMethods.createGet(this.target.toURI() + "/random/20480");
+ HttpAsyncRequestProducer httpget = HttpAsyncMethods.createGet(target.toURI() + "/random/20480");
AsyncByteConsumer<Long> consumer = new ByteCountingConsumer(512);
Future<Long> future = this.httpclient.execute(httpget, consumer, null);
Long count = future.get();
@@ -125,12 +193,13 @@ public class TestAsyncConsumers extends
}
@Override
- protected void onCleanup() {
+ protected void releaseResources() {
+ super.releaseResources();
this.sb.setLength(0);
}
@Override
- protected String buildResult() throws Exception {
+ protected String buildResult(final HttpContext context) throws Exception {
return this.sb.toString();
}
@@ -138,6 +207,7 @@ public class TestAsyncConsumers extends
@Test
public void testCharConsumer() throws Exception {
+ HttpHost target = start();
StringBuilder sb = new StringBuilder();
for (int i= 0; i < 25; i++) {
sb.append("blah blah blah blah\r\n");
@@ -147,7 +217,7 @@ public class TestAsyncConsumers extends
for (int i = 0; i < 5; i++) {
HttpAsyncRequestProducer httppost = HttpAsyncMethods.createPost(
- this.target.toURI() + "/echo/stuff", s,
+ target.toURI() + "/echo/stuff", s,
ContentType.create("text/plain", HTTP.ASCII));
AsyncCharConsumer<String> consumer = new BufferingCharConsumer();
Future<String> future = this.httpclient.execute(httppost, consumer, null);
@@ -158,6 +228,7 @@ public class TestAsyncConsumers extends
@Test
public void testCharConsumerSmallBufffer() throws Exception {
+ HttpHost target = start();
StringBuilder sb = new StringBuilder();
for (int i= 0; i < 25; i++) {
sb.append("blah blah blah blah\r\n");
@@ -167,7 +238,7 @@ public class TestAsyncConsumers extends
for (int i = 0; i < 5; i++) {
HttpAsyncRequestProducer httppost = HttpAsyncMethods.createPost(
- this.target.toURI() + "/echo/stuff", s,
+ target.toURI() + "/echo/stuff", s,
ContentType.create("text/plain", HTTP.ASCII));
AsyncCharConsumer<String> consumer = new BufferingCharConsumer(512);
Future<String> future = this.httpclient.execute(httppost, consumer, null);
@@ -178,6 +249,7 @@ public class TestAsyncConsumers extends
@Test
public void testResourceReleaseOnSuccess() throws Exception {
+ HttpHost target = start();
StringBuilder sb = new StringBuilder();
for (int i= 0; i < 25; i++) {
sb.append("blah blah blah blah\r\n");
@@ -186,22 +258,22 @@ public class TestAsyncConsumers extends
String s = sb.toString();
HttpAsyncRequestProducer httppost = HttpAsyncMethods.createPost(
- this.target.toURI() + "/echo/stuff", s,
+ target.toURI() + "/echo/stuff", s,
ContentType.create("text/plain", HTTP.ASCII));
- AsyncCharConsumer<String> consumer = Mockito.spy(new BufferingCharConsumer());
+ BufferingCharConsumer consumer = Mockito.spy(new BufferingCharConsumer());
Future<String> future = this.httpclient.execute(httppost, consumer, null);
String result = future.get();
Assert.assertEquals(s, result);
- Mockito.verify(consumer).responseCompleted();
- Mockito.verify(consumer).buildResult();
+ Mockito.verify(consumer).responseCompleted(Mockito.any(HttpContext.class));
+ Mockito.verify(consumer).buildResult(Mockito.any(HttpContext.class));
Mockito.verify(consumer).releaseResources();
- Mockito.verify(consumer).onCleanup();
}
@Test
public void testResourceReleaseOnException() throws Exception {
+ HttpHost target = start();
HttpAsyncRequestProducer httppost = HttpAsyncMethods.createPost(
- this.target.toURI() + "/echo/stuff", "stuff",
+ target.toURI() + "/echo/stuff", "stuff",
ContentType.create("text/plain", HTTP.ASCII));
AsyncCharConsumer<String> consumer = Mockito.spy(new BufferingCharConsumer());
Mockito.doThrow(new IOException("Kaboom")).when(consumer).consumeContent(
@@ -219,16 +291,16 @@ public class TestAsyncConsumers extends
}
Mockito.verify(consumer).failed(Mockito.any(IOException.class));
Mockito.verify(consumer).releaseResources();
- Mockito.verify(consumer).onCleanup();
}
@Test
public void testResourceReleaseOnBuildFailure() throws Exception {
+ HttpHost target = start();
HttpAsyncRequestProducer httppost = HttpAsyncMethods.createPost(
- this.target.toURI() + "/echo/stuff", "stuff",
+ target.toURI() + "/echo/stuff", "stuff",
ContentType.create("text/plain", HTTP.ASCII));
- AsyncCharConsumer<String> consumer = Mockito.spy(new BufferingCharConsumer());
- Mockito.doThrow(new HttpException("Kaboom")).when(consumer).buildResult();
+ BufferingCharConsumer consumer = Mockito.spy(new BufferingCharConsumer());
+ Mockito.doThrow(new HttpException("Kaboom")).when(consumer).buildResult(Mockito.any(HttpContext.class));
Future<String> future = this.httpclient.execute(httppost, consumer, null);
try {
@@ -240,9 +312,8 @@ public class TestAsyncConsumers extends
Assert.assertTrue(t instanceof HttpException);
Assert.assertEquals("Kaboom", t.getMessage());
}
- Mockito.verify(consumer).responseCompleted();
+ Mockito.verify(consumer).responseCompleted(Mockito.any(HttpContext.class));
Mockito.verify(consumer).releaseResources();
- Mockito.verify(consumer).onCleanup();
}
}
Modified: httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/nio/client/methods/TestZeroCopy.java
URL: http://svn.apache.org/viewvc/httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/nio/client/methods/TestZeroCopy.java?rev=1174357&r1=1174356&r2=1174357&view=diff
==============================================================================
--- httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/nio/client/methods/TestZeroCopy.java (original)
+++ httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/java/org/apache/http/nio/client/methods/TestZeroCopy.java Thu Sep 22 20:03:35 2011
@@ -30,6 +30,7 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.concurrent.Future;
@@ -38,27 +39,85 @@ import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.io.output.FileWriterWithEncoding;
+import org.apache.http.HttpAsyncTestBase;
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.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.ContentType;
-import org.apache.http.entity.FileEntity;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.localserver.AsyncHttpTestBase;
+import org.apache.http.impl.DefaultConnectionReuseStrategy;
+import org.apache.http.impl.nio.DefaultNHttpServerConnectionFactory;
+import org.apache.http.nio.NHttpConnectionFactory;
+import org.apache.http.nio.NHttpServerIOTarget;
+import org.apache.http.nio.entity.NFileEntity;
+import org.apache.http.nio.entity.NStringEntity;
+import org.apache.http.nio.protocol.BufferingAsyncRequestHandler;
+import org.apache.http.nio.protocol.HttpAsyncExpectationVerifier;
+import org.apache.http.nio.protocol.HttpAsyncRequestHandlerRegistry;
+import org.apache.http.nio.protocol.HttpAsyncRequestHandlerResolver;
+import org.apache.http.nio.protocol.HttpAsyncServiceHandler;
+import org.apache.http.nio.reactor.IOReactorStatus;
+import org.apache.http.nio.reactor.ListenerEndpoint;
+import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
+import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-public class TestZeroCopy extends AsyncHttpTestBase {
+public class TestZeroCopy extends HttpAsyncTestBase {
+
+ @Before
+ public void setUp() throws Exception {
+ initServer();
+ initClient();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ shutDownClient();
+ shutDownServer();
+ }
+
+ @Override
+ protected NHttpConnectionFactory<NHttpServerIOTarget> createServerConnectionFactory(
+ final HttpParams params) throws Exception {
+ return new DefaultNHttpServerConnectionFactory(params);
+ }
+
+ @Override
+ protected String getSchemeName() {
+ return "http";
+ }
+
+ private HttpHost start(
+ final HttpAsyncRequestHandlerResolver requestHandlerResolver,
+ final HttpAsyncExpectationVerifier expectationVerifier) throws Exception {
+ HttpAsyncServiceHandler serviceHandler = new HttpAsyncServiceHandler(
+ requestHandlerResolver,
+ expectationVerifier,
+ this.serverHttpProc,
+ new DefaultConnectionReuseStrategy(),
+ this.serverParams);
+ this.server.start(serviceHandler);
+ this.httpclient.start();
+
+ ListenerEndpoint endpoint = this.server.getListenerEndpoint();
+ endpoint.waitFor();
+
+ Assert.assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
+ InetSocketAddress address = (InetSocketAddress) endpoint.getAddress();
+ HttpHost target = new HttpHost("localhost", address.getPort(), getSchemeName());
+ return target;
+ }
private static final String[] TEXT = {
"blah blah blah blah blah blah blah blah blah blah blah blah blah blah",
@@ -158,7 +217,7 @@ public class TestZeroCopy extends AsyncH
requestEntity = ((HttpEntityEnclosingRequest) request).getEntity();
}
if (requestEntity == null) {
- response.setEntity(new StringEntity("Empty content"));
+ response.setEntity(new NStringEntity("Empty content"));
return;
}
@@ -183,24 +242,27 @@ public class TestZeroCopy extends AsyncH
instream.close();
}
if (ok) {
- FileEntity responseEntity = new FileEntity(TEST_FILE,
+ NFileEntity responseEntity = new NFileEntity(TEST_FILE,
ContentType.create("text/plian", null));
if (this.forceChunking) {
responseEntity.setChunked(true);
}
response.setEntity(responseEntity);
} else {
- response.setEntity(new StringEntity("Invalid content"));
+ response.setEntity(new NStringEntity("Invalid content"));
}
}
}
@Test
public void testTwoWayZeroCopy() throws Exception {
- this.localServer.register("/bounce", new TestHandler(false));
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(new TestHandler(false)));
+ HttpHost target = start(registry, null);
+
File tmpdir = FileUtils.getTempDirectory();
this.tmpfile = new File(tmpdir, "dst.test");
- TestZeroCopyPost httppost = new TestZeroCopyPost(this.target.toURI() + "/bounce", false);
+ TestZeroCopyPost httppost = new TestZeroCopyPost(target.toURI() + "/bounce", false);
TestZeroCopyConsumer consumer = new TestZeroCopyConsumer(this.tmpfile);
Future<Integer> future = this.httpclient.execute(httppost, consumer, null);
Integer status = future.get();
@@ -224,10 +286,12 @@ public class TestZeroCopy extends AsyncH
@Test
public void testZeroCopyFallback() throws Exception {
- this.localServer.register("/bounce", new TestHandler(true));
+ HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();
+ registry.register("*", new BufferingAsyncRequestHandler(new TestHandler(true)));
+ HttpHost target = start(registry, null);
File tmpdir = FileUtils.getTempDirectory();
this.tmpfile = new File(tmpdir, "dst.test");
- TestZeroCopyPost httppost = new TestZeroCopyPost(this.target.toURI() + "/bounce", true);
+ TestZeroCopyPost httppost = new TestZeroCopyPost(target.toURI() + "/bounce", true);
TestZeroCopyConsumer consumer = new TestZeroCopyConsumer(this.tmpfile);
Future<Integer> future = this.httpclient.execute(httppost, consumer, null);
Integer status = future.get();
Propchange: httpcomponents/httpasyncclient/trunk/httpasyncclient/src/test/resources/test.keystore
------------------------------------------------------------------------------
--- svn:mergeinfo (original)
+++ svn:mergeinfo Thu Sep 22 20:03:35 2011
@@ -1,2 +1,3 @@
/httpcomponents/httpasyncclient/branches/conn-mgmt-redesign/httpasyncclient/src/test/resources/test.keystore:1155312-1159070
+/httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/resources/test.keystore:1167093-1174316
/httpcomponents/httpcore/branches/ibm_compat_branch/httpcore-nio/src/test/resources/test.keystore:755687-758898
Modified: httpcomponents/httpasyncclient/trunk/pom.xml
URL: http://svn.apache.org/viewvc/httpcomponents/httpasyncclient/trunk/pom.xml?rev=1174357&r1=1174356&r2=1174357&view=diff
==============================================================================
--- httpcomponents/httpasyncclient/trunk/pom.xml (original)
+++ httpcomponents/httpasyncclient/trunk/pom.xml Thu Sep 22 20:03:35 2011
@@ -32,7 +32,6 @@
<relativePath>../project/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
- <groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcomponents-asyncclient</artifactId>
<name>HttpComponents AsyncClient</name>
<version>4.0-alpha3-SNAPSHOT</version>
@@ -72,7 +71,7 @@
<maven.compile.target>1.5</maven.compile.target>
<maven.compile.optimize>true</maven.compile.optimize>
<maven.compile.deprecation>true</maven.compile.deprecation>
- <httpcore.version>4.2-alpha1</httpcore.version>
+ <httpcore.version>4.2-alpha2</httpcore.version>
<httpclient.version>4.1.1</httpclient.version>
<commons-logging.version>1.1.1</commons-logging.version>
<commons-io.version>2.0.1</commons-io.version>