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/12 14:28:11 UTC
svn commit: r1169710 [2/2] - in
/httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src:
examples/org/apache/http/examples/nio/client/ test/java/org/apache/http/
test/java/org/apache/http/impl/nio/client/ test/java/org...
Modified: httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/impl/nio/client/TestRedirects.java
URL: http://svn.apache.org/viewvc/httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/impl/nio/client/TestRedirects.java?rev=1169710&r1=1169709&r2=1169710&view=diff
==============================================================================
--- httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/impl/nio/client/TestRedirects.java (original)
+++ httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/impl/nio/client/TestRedirects.java Mon Sep 12 12:28:10 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);
Modified: httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/localserver/EchoHandler.java
URL: http://svn.apache.org/viewvc/httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/localserver/EchoHandler.java?rev=1169710&r1=1169709&r2=1169710&view=diff
==============================================================================
--- httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/localserver/EchoHandler.java (original)
+++ httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/localserver/EchoHandler.java Mon Sep 12 12:28:10 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
+}
Added: httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/localserver/HttpServerNio.java
URL: http://svn.apache.org/viewvc/httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/localserver/HttpServerNio.java?rev=1169710&view=auto
==============================================================================
--- httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/localserver/HttpServerNio.java (added)
+++ httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/localserver/HttpServerNio.java Mon Sep 12 12:28:10 2011
@@ -0,0 +1,144 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.http.localserver;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.List;
+
+import org.apache.http.impl.nio.DefaultServerIODispatch;
+import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
+import org.apache.http.impl.nio.reactor.ExceptionEvent;
+import org.apache.http.nio.NHttpConnectionFactory;
+import org.apache.http.nio.NHttpServerIOTarget;
+import org.apache.http.nio.NHttpServiceHandler;
+import org.apache.http.nio.reactor.IOEventDispatch;
+import org.apache.http.nio.reactor.IOReactorExceptionHandler;
+import org.apache.http.nio.reactor.IOReactorStatus;
+import org.apache.http.nio.reactor.ListenerEndpoint;
+import org.apache.http.nio.reactor.ListeningIOReactor;
+
+public class HttpServerNio {
+
+ private final DefaultListeningIOReactor ioReactor;
+ private final NHttpConnectionFactory<NHttpServerIOTarget> connFactory;
+
+ private volatile IOReactorThread thread;
+ private ListenerEndpoint endpoint;
+
+ public HttpServerNio(
+ final NHttpConnectionFactory<NHttpServerIOTarget> connFactory) throws IOException {
+ super();
+ this.ioReactor = new DefaultListeningIOReactor();
+ this.connFactory = connFactory;
+ }
+
+ public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) {
+ this.ioReactor.setExceptionHandler(exceptionHandler);
+ }
+
+ private void execute(final NHttpServiceHandler serviceHandler) throws IOException {
+ IOEventDispatch ioEventDispatch = new DefaultServerIODispatch(serviceHandler, this.connFactory);
+ this.ioReactor.execute(ioEventDispatch);
+ }
+
+ public ListenerEndpoint getListenerEndpoint() {
+ return this.endpoint;
+ }
+
+ public void setEndpoint(ListenerEndpoint endpoint) {
+ this.endpoint = endpoint;
+ }
+
+ public void start(final NHttpServiceHandler serviceHandler) {
+ this.endpoint = this.ioReactor.listen(new InetSocketAddress(0));
+ this.thread = new IOReactorThread(serviceHandler);
+ this.thread.start();
+ }
+
+ public ListeningIOReactor getIoReactor() {
+ return this.ioReactor;
+ }
+
+ public IOReactorStatus getStatus() {
+ return this.ioReactor.getStatus();
+ }
+
+ public List<ExceptionEvent> getAuditLog() {
+ return this.ioReactor.getAuditLog();
+ }
+
+ public void join(long timeout) throws InterruptedException {
+ if (this.thread != null) {
+ this.thread.join(timeout);
+ }
+ }
+
+ public Exception getException() {
+ if (this.thread != null) {
+ return this.thread.getException();
+ } else {
+ return null;
+ }
+ }
+
+ public void shutdown() throws IOException {
+ this.ioReactor.shutdown();
+ try {
+ join(500);
+ } catch (InterruptedException ignore) {
+ }
+ }
+
+ private class IOReactorThread extends Thread {
+
+ private final NHttpServiceHandler serviceHandler;
+
+ private volatile Exception ex;
+
+ public IOReactorThread(final NHttpServiceHandler serviceHandler) {
+ super();
+ this.serviceHandler = serviceHandler;
+ }
+
+ @Override
+ public void run() {
+ try {
+ execute(this.serviceHandler);
+ } catch (Exception ex) {
+ this.ex = ex;
+ }
+ }
+
+ public Exception getException() {
+ return this.ex;
+ }
+
+ }
+
+}
Propchange: httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/localserver/HttpServerNio.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/localserver/HttpServerNio.java
------------------------------------------------------------------------------
svn:keywords = Date Revision
Propchange: httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/localserver/HttpServerNio.java
------------------------------------------------------------------------------
svn:mime-type = text/plain
Modified: httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/localserver/RandomHandler.java
URL: http://svn.apache.org/viewvc/httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/localserver/RandomHandler.java?rev=1169710&r1=1169709&r2=1169710&view=diff
==============================================================================
--- httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/localserver/RandomHandler.java (original)
+++ httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/localserver/RandomHandler.java Mon Sep 12 12:28:10 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/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/nio/client/methods/TestAsyncConsumers.java
URL: http://svn.apache.org/viewvc/httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/nio/client/methods/TestAsyncConsumers.java?rev=1169710&r1=1169709&r2=1169710&view=diff
==============================================================================
--- httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/nio/client/methods/TestAsyncConsumers.java (original)
+++ httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/nio/client/methods/TestAsyncConsumers.java Mon Sep 12 12:28:10 2011
@@ -27,26 +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.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> {
@@ -78,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();
@@ -89,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();
@@ -136,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");
@@ -145,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);
@@ -156,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");
@@ -165,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);
@@ -176,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");
@@ -184,7 +258,7 @@ 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));
BufferingCharConsumer consumer = Mockito.spy(new BufferingCharConsumer());
Future<String> future = this.httpclient.execute(httppost, consumer, null);
@@ -197,8 +271,9 @@ public class TestAsyncConsumers extends
@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(
@@ -220,8 +295,9 @@ public class TestAsyncConsumers extends
@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));
BufferingCharConsumer consumer = Mockito.spy(new BufferingCharConsumer());
Mockito.doThrow(new HttpException("Kaboom")).when(consumer).buildResult();
Modified: httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/nio/client/methods/TestZeroCopy.java
URL: http://svn.apache.org/viewvc/httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/nio/client/methods/TestZeroCopy.java?rev=1169710&r1=1169709&r2=1169710&view=diff
==============================================================================
--- httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/nio/client/methods/TestZeroCopy.java (original)
+++ httpcomponents/httpasyncclient/branches/protocol-handler-refactoring/httpasyncclient/src/test/java/org/apache/http/nio/client/methods/TestZeroCopy.java Mon Sep 12 12:28:10 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();