You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hc.apache.org by ol...@apache.org on 2017/11/13 21:46:00 UTC
[5/6] httpcomponents-client git commit: * HTTP/2 multiplexing
HttpAsyncClient implementation * Restructured integration tests to reduce
test duplication
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/6228a736/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/LocalAsyncServerTestBase.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/LocalAsyncServerTestBase.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/LocalAsyncServerTestBase.java
deleted file mode 100644
index 5ae533c..0000000
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/LocalAsyncServerTestBase.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
-
-package org.apache.hc.client5.testing.async;
-
-import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
-import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
-import org.apache.hc.client5.http.ssl.H2TlsStrategy;
-import org.apache.hc.client5.testing.SSLTestContexts;
-import org.apache.hc.core5.function.Supplier;
-import org.apache.hc.core5.http.URIScheme;
-import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
-import org.apache.hc.core5.reactor.IOReactorConfig;
-import org.apache.hc.core5.testing.nio.Http2TestServer;
-import org.apache.hc.core5.util.TimeValue;
-import org.apache.hc.core5.util.Timeout;
-import org.junit.Rule;
-import org.junit.rules.ExternalResource;
-
-public abstract class LocalAsyncServerTestBase {
-
- public static final Timeout TIMEOUT = Timeout.ofSeconds(30);
- public static final Timeout LONG_TIMEOUT = Timeout.ofSeconds(60);
-
- protected final URIScheme scheme;
-
- public LocalAsyncServerTestBase(final URIScheme scheme) {
- this.scheme = scheme;
- }
-
- public LocalAsyncServerTestBase() {
- this(URIScheme.HTTP);
- }
-
- protected Http2TestServer server;
- protected PoolingAsyncClientConnectionManager connManager;
-
- @Rule
- public ExternalResource serverResource = new ExternalResource() {
-
- @Override
- protected void before() throws Throwable {
- server = new Http2TestServer(
- IOReactorConfig.custom()
- .setSoTimeout(TIMEOUT)
- .build(),
- scheme == URIScheme.HTTPS ? SSLTestContexts.createServerSSLContext() : null);
- server.register("/echo/*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncEchoHandler();
- }
-
- });
- server.register("/random/*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncRandomHandler();
- }
-
- });
- }
-
- @Override
- protected void after() {
- if (server != null) {
- server.shutdown(TimeValue.ofSeconds(5));
- server = null;
- }
- }
-
- };
-
- @Rule
- public ExternalResource connManagerResource = new ExternalResource() {
-
- @Override
- protected void before() throws Throwable {
- connManager = PoolingAsyncClientConnectionManagerBuilder.create()
- .setTlsStrategy(new H2TlsStrategy(SSLTestContexts.createClientSSLContext()))
- .build();
- }
-
- @Override
- protected void after() {
- if (connManager != null) {
- connManager.close();
- connManager = null;
- }
- }
-
- };
-
-}
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/6228a736/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestAsyncRedirects.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestAsyncRedirects.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestAsyncRedirects.java
deleted file mode 100644
index 83c429e..0000000
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestAsyncRedirects.java
+++ /dev/null
@@ -1,910 +0,0 @@
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
-package org.apache.hc.client5.testing.async;
-
-import java.net.InetSocketAddress;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Queue;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-
-import org.apache.hc.client5.http.CircularRedirectException;
-import org.apache.hc.client5.http.RedirectException;
-import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
-import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
-import org.apache.hc.client5.http.config.RequestConfig;
-import org.apache.hc.client5.http.cookie.BasicCookieStore;
-import org.apache.hc.client5.http.cookie.CookieStore;
-import org.apache.hc.client5.http.impl.cookie.BasicClientCookie;
-import org.apache.hc.client5.http.protocol.HttpClientContext;
-import org.apache.hc.client5.testing.SSLTestContexts;
-import org.apache.hc.core5.function.Supplier;
-import org.apache.hc.core5.http.ContentType;
-import org.apache.hc.core5.http.Header;
-import org.apache.hc.core5.http.HttpException;
-import org.apache.hc.core5.http.HttpHeaders;
-import org.apache.hc.core5.http.HttpHost;
-import org.apache.hc.core5.http.HttpRequest;
-import org.apache.hc.core5.http.HttpResponse;
-import org.apache.hc.core5.http.HttpStatus;
-import org.apache.hc.core5.http.ProtocolException;
-import org.apache.hc.core5.http.URIScheme;
-import org.apache.hc.core5.http.message.BasicHeader;
-import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
-import org.apache.hc.core5.http.protocol.HttpCoreContext;
-import org.apache.hc.core5.net.URIBuilder;
-import org.apache.hc.core5.reactor.IOReactorConfig;
-import org.apache.hc.core5.reactor.ListenerEndpoint;
-import org.apache.hc.core5.testing.nio.Http2TestServer;
-import org.apache.hc.core5.util.TimeValue;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-
-/**
- * Redirection test cases.
- */
-@RunWith(Parameterized.class)
-public class TestAsyncRedirects extends IntegrationTestBase {
-
- @Parameterized.Parameters(name = "{0}")
- public static Collection<Object[]> protocols() {
- return Arrays.asList(new Object[][]{
- {URIScheme.HTTP},
- {URIScheme.HTTPS},
- });
- }
-
- public TestAsyncRedirects(final URIScheme scheme) {
- super(scheme);
- }
-
- static class BasicRedirectService extends AbstractSimpleServerExchangeHandler {
-
- private final int statuscode;
- private final boolean keepAlive;
-
- public BasicRedirectService(final int statuscode, final boolean keepAlive) {
- super();
- this.statuscode = statuscode;
- this.keepAlive = keepAlive;
- }
-
- public BasicRedirectService(final int statuscode) {
- this(statuscode, true);
- }
-
- @Override
- protected SimpleHttpResponse handle(
- final SimpleHttpRequest request, final HttpCoreContext context) throws HttpException {
- try {
- final URI requestURI = request.getUri();
- final String path = requestURI.getPath();
- if (path.equals("/oldlocation/")) {
- final SimpleHttpResponse response = new SimpleHttpResponse(statuscode);
- response.addHeader(new BasicHeader("Location",
- new URIBuilder(requestURI).setPath("/newlocation/").build()));
- if (!keepAlive) {
- response.addHeader(new BasicHeader("Connection", "close"));
- }
- return response;
- } else if (path.equals("/newlocation/")) {
- final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_OK);
- response.setBodyText("Successful redirect", ContentType.TEXT_PLAIN);
- return response;
- } else {
- return new SimpleHttpResponse(HttpStatus.SC_NOT_FOUND);
- }
- } catch (final URISyntaxException ex) {
- throw new ProtocolException(ex.getMessage(), ex);
- }
- }
-
- }
-
- static class CircularRedirectService extends AbstractSimpleServerExchangeHandler {
-
- public CircularRedirectService() {
- super();
- }
-
- @Override
- protected SimpleHttpResponse handle(
- final SimpleHttpRequest request, final HttpCoreContext context) throws HttpException {
- try {
- final URI requestURI = request.getUri();
- final String path = requestURI.getPath();
- if (path.startsWith("/circular-oldlocation")) {
- final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY);
- response.addHeader(new BasicHeader("Location", "/circular-location2"));
- return response;
- } else if (path.startsWith("/circular-location2")) {
- final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY);
- response.addHeader(new BasicHeader("Location", "/circular-oldlocation"));
- return response;
- } else {
- return new SimpleHttpResponse(HttpStatus.SC_NOT_FOUND);
- }
- } catch (final URISyntaxException ex) {
- throw new ProtocolException(ex.getMessage(), ex);
- }
- }
-
- }
-
- static class RelativeRedirectService extends AbstractSimpleServerExchangeHandler {
-
- @Override
- protected SimpleHttpResponse handle(
- final SimpleHttpRequest request, final HttpCoreContext context) throws HttpException {
- try {
- final URI requestURI = request.getUri();
- final String path = requestURI.getPath();
- if (path.equals("/oldlocation/")) {
- final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY);
- response.addHeader(new BasicHeader("Location", "/relativelocation/"));
- return response;
- } else if (path.equals("/relativelocation/")) {
- final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_OK);
- response.setBodyText("Successful redirect", ContentType.TEXT_PLAIN);
- return response;
- } else {
- return new SimpleHttpResponse(HttpStatus.SC_NOT_FOUND);
- }
- } catch (final URISyntaxException ex) {
- throw new ProtocolException(ex.getMessage(), ex);
- }
- }
- }
-
- static class RelativeRedirectService2 extends AbstractSimpleServerExchangeHandler {
-
- @Override
- protected SimpleHttpResponse handle(
- final SimpleHttpRequest request, final HttpCoreContext context) throws HttpException {
- try {
- final URI requestURI = request.getUri();
- final String path = requestURI.getPath();
- if (path.equals("/test/oldlocation")) {
- final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY);
- response.addHeader(new BasicHeader("Location", "relativelocation"));
- return response;
- } else if (path.equals("/test/relativelocation")) {
- final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_OK);
- response.setBodyText("Successful redirect", ContentType.TEXT_PLAIN);
- return response;
- } else {
- return new SimpleHttpResponse(HttpStatus.SC_NOT_FOUND);
- }
- } catch (final URISyntaxException ex) {
- throw new ProtocolException(ex.getMessage(), ex);
- }
- }
-
- }
-
- @Test
- public void testBasicRedirect300() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new BasicRedirectService(HttpStatus.SC_MULTIPLE_CHOICES, false);
- }
-
- });
- final HttpHost target = start();
-
- final HttpClientContext context = HttpClientContext.create();
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/oldlocation/"), context, null);
- final HttpResponse response = future.get();
- Assert.assertNotNull(response);
-
- final HttpRequest request = context.getRequest();
-
- Assert.assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getCode());
- Assert.assertEquals("/oldlocation/", request.getRequestUri());
- }
-
- @Test
- public void testBasicRedirect301KeepAlive() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new BasicRedirectService(HttpStatus.SC_MOVED_PERMANENTLY, true);
- }
-
- });
-
- final HttpHost target = start();
- final HttpClientContext context = HttpClientContext.create();
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/oldlocation/"), context, null);
- final HttpResponse response = future.get();
- Assert.assertNotNull(response);
-
- final HttpRequest request = context.getRequest();
-
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- Assert.assertEquals("/newlocation/", request.getRequestUri());
- Assert.assertEquals(target, new HttpHost(request.getAuthority(), request.getScheme()));
- }
-
- @Test
- public void testBasicRedirect301NoKeepAlive() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new BasicRedirectService(HttpStatus.SC_MOVED_PERMANENTLY, false);
- }
-
- });
-
- final HttpHost target = start();
- final HttpClientContext context = HttpClientContext.create();
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/oldlocation/"), context, null);
- final HttpResponse response = future.get();
- Assert.assertNotNull(response);
-
- final HttpRequest request = context.getRequest();
-
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- Assert.assertEquals("/newlocation/", request.getRequestUri());
- Assert.assertEquals(target, new HttpHost(request.getAuthority(), request.getScheme()));
- }
-
- @Test
- public void testBasicRedirect302() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new BasicRedirectService(HttpStatus.SC_MOVED_TEMPORARILY);
- }
-
- });
- final HttpHost target = start();
- final HttpClientContext context = HttpClientContext.create();
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/oldlocation/"), context, null);
- final HttpResponse response = future.get();
- Assert.assertNotNull(response);
-
- final HttpRequest request = context.getRequest();
-
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- Assert.assertEquals("/newlocation/", request.getRequestUri());
- Assert.assertEquals(target, new HttpHost(request.getAuthority(), request.getScheme()));
- }
-
- @Test
- public void testBasicRedirect302NoLocation() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AbstractSimpleServerExchangeHandler() {
-
- @Override
- protected SimpleHttpResponse handle(
- final SimpleHttpRequest request, final HttpCoreContext context) throws HttpException {
- return new SimpleHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY);
- }
-
- };
- }
-
- });
- final HttpHost target = start();
- final HttpClientContext context = HttpClientContext.create();
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/oldlocation/"), context, null);
- final HttpResponse response = future.get();
- Assert.assertNotNull(response);
-
- final HttpRequest request = context.getRequest();
- Assert.assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getCode());
- Assert.assertEquals("/oldlocation/", request.getRequestUri());
- Assert.assertEquals(target, new HttpHost(request.getAuthority(), request.getScheme()));
- }
-
- @Test
- public void testBasicRedirect303() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new BasicRedirectService(HttpStatus.SC_SEE_OTHER);
- }
-
- });
- final HttpHost target = start();
- final HttpClientContext context = HttpClientContext.create();
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/oldlocation/"), context, null);
- final HttpResponse response = future.get();
- Assert.assertNotNull(response);
-
- final HttpRequest request = context.getRequest();
-
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- Assert.assertEquals("/newlocation/", request.getRequestUri());
- Assert.assertEquals(target, new HttpHost(request.getAuthority(), request.getScheme()));
- }
-
- @Test
- public void testBasicRedirect304() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new BasicRedirectService(HttpStatus.SC_NOT_MODIFIED);
- }
-
- });
- final HttpHost target = start();
- final HttpClientContext context = HttpClientContext.create();
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/oldlocation/"), context, null);
- final HttpResponse response = future.get();
- Assert.assertNotNull(response);
-
- final HttpRequest request = context.getRequest();
-
- Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, response.getCode());
- Assert.assertEquals("/oldlocation/", request.getRequestUri());
- }
-
- @Test
- public void testBasicRedirect305() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new BasicRedirectService(HttpStatus.SC_USE_PROXY);
- }
-
- });
- final HttpHost target = start();
- final HttpClientContext context = HttpClientContext.create();
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/oldlocation/"), context, null);
- final HttpResponse response = future.get();
- Assert.assertNotNull(response);
-
- final HttpRequest request = context.getRequest();
-
- Assert.assertEquals(HttpStatus.SC_USE_PROXY, response.getCode());
- Assert.assertEquals("/oldlocation/", request.getRequestUri());
- }
-
- @Test
- public void testBasicRedirect307() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new BasicRedirectService(HttpStatus.SC_TEMPORARY_REDIRECT);
- }
-
- });
- final HttpHost target = start();
- final HttpClientContext context = HttpClientContext.create();
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/oldlocation/"), context, null);
- final HttpResponse response = future.get();
- Assert.assertNotNull(response);
-
- final HttpRequest request = context.getRequest();
-
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- Assert.assertEquals("/newlocation/", request.getRequestUri());
- Assert.assertEquals(target, new HttpHost(request.getAuthority(), request.getScheme()));
- }
-
- @Test(expected=ExecutionException.class)
- public void testMaxRedirectCheck() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new CircularRedirectService();
- }
-
- });
- final HttpHost target = start();
-
- final RequestConfig config = RequestConfig.custom()
- .setCircularRedirectsAllowed(true)
- .setMaxRedirects(5).build();
- try {
- final SimpleHttpRequest request = SimpleHttpRequest.get(target, "/circular-oldlocation/");
- request.setConfig(config);
- final Future<SimpleHttpResponse> future = httpclient.execute(request, null);
- future.get();
- } catch (final ExecutionException e) {
- Assert.assertTrue(e.getCause() instanceof RedirectException);
- throw e;
- }
- }
-
- @Test(expected=ExecutionException.class)
- public void testCircularRedirect() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new CircularRedirectService();
- }
-
- });
- final HttpHost target = start();
-
- final RequestConfig config = RequestConfig.custom()
- .setCircularRedirectsAllowed(false)
- .build();
- try {
- final SimpleHttpRequest request = SimpleHttpRequest.get(target, "/circular-oldlocation/");
- request.setConfig(config);
- final Future<SimpleHttpResponse> future = httpclient.execute(request, null);
- future.get();
- } catch (final ExecutionException e) {
- Assert.assertTrue(e.getCause() instanceof CircularRedirectException);
- throw e;
- }
- }
-
- @Test
- public void testPostRedirectSeeOther() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new BasicRedirectService(HttpStatus.SC_SEE_OTHER);
- }
-
- });
- final HttpHost target = start();
-
- final HttpClientContext context = HttpClientContext.create();
-
- final SimpleHttpRequest post = SimpleHttpRequest.post(target, "/oldlocation/");
- post.setBodyText("stuff", ContentType.TEXT_PLAIN);
- final Future<SimpleHttpResponse> future = httpclient.execute(post, context, null);
- final HttpResponse response = future.get();
- Assert.assertNotNull(response);
-
- final HttpRequest request = context.getRequest();
-
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- Assert.assertEquals("/newlocation/", request.getRequestUri());
- Assert.assertEquals("GET", request.getMethod());
- }
-
- @Test
- public void testRelativeRedirect() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new RelativeRedirectService();
- }
-
- });
- final HttpHost target = start();
-
- final HttpClientContext context = HttpClientContext.create();
-
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/oldlocation/"), context, null);
- final HttpResponse response = future.get();
- Assert.assertNotNull(response);
-
- final HttpRequest request = context.getRequest();
-
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- Assert.assertEquals("/relativelocation/", request.getRequestUri());
- Assert.assertEquals(target, new HttpHost(request.getAuthority(), request.getScheme()));
- }
-
- @Test
- public void testRelativeRedirect2() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new RelativeRedirectService2();
- }
-
- });
- final HttpHost target = start();
-
- final HttpClientContext context = HttpClientContext.create();
-
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/test/oldlocation"), context, null);
- final HttpResponse response = future.get();
- Assert.assertNotNull(response);
-
- final HttpRequest request = context.getRequest();
-
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- Assert.assertEquals("/test/relativelocation", request.getRequestUri());
- Assert.assertEquals(target, new HttpHost(request.getAuthority(), request.getScheme()));
- }
-
- static class BogusRedirectService extends AbstractSimpleServerExchangeHandler {
-
- private final String url;
-
- public BogusRedirectService(final String url) {
- super();
- this.url = url;
- }
-
- @Override
- protected SimpleHttpResponse handle(
- final SimpleHttpRequest request, final HttpCoreContext context) throws HttpException {
- try {
- final URI requestURI = request.getUri();
- final String path = requestURI.getPath();
- if (path.equals("/oldlocation/")) {
- final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY);
- response.addHeader(new BasicHeader("Location", url));
- return response;
- } else if (path.equals("/relativelocation/")) {
- final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_OK);
- response.setBodyText("Successful redirect", ContentType.TEXT_PLAIN);
- return response;
- } else {
- return new SimpleHttpResponse(HttpStatus.SC_NOT_FOUND);
- }
- } catch (final URISyntaxException ex) {
- throw new ProtocolException(ex.getMessage(), ex);
- }
- }
-
- }
-
- @Test(expected=ExecutionException.class)
- public void testRejectBogusRedirectLocation() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new BogusRedirectService("xxx://bogus");
- }
-
- });
- final HttpHost target = start();
-
- try {
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/oldlocation/"), null);
- future.get();
- } catch (final ExecutionException ex) {
- Assert.assertTrue(ex.getCause() instanceof HttpException);
- throw ex;
- }
- }
-
- @Test(expected=ExecutionException.class)
- public void testRejectInvalidRedirectLocation() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new BogusRedirectService("/newlocation/?p=I have spaces");
- }
-
- });
- final HttpHost target = start();
-
- try {
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/oldlocation/"), null);
- future.get();
- } catch (final ExecutionException e) {
- Assert.assertTrue(e.getCause() instanceof ProtocolException);
- throw e;
- }
- }
-
- @Test
- public void testRedirectWithCookie() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new BasicRedirectService(HttpStatus.SC_MOVED_TEMPORARILY);
- }
-
- });
- final HttpHost target = start();
-
- final CookieStore cookieStore = new BasicCookieStore();
- final HttpClientContext context = HttpClientContext.create();
- context.setCookieStore(cookieStore);
-
- final BasicClientCookie cookie = new BasicClientCookie("name", "value");
- cookie.setDomain(target.getHostName());
- cookie.setPath("/");
-
- cookieStore.addCookie(cookie);
-
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/oldlocation/"), context, null);
- final HttpResponse response = future.get();
- Assert.assertNotNull(response);
-
- final HttpRequest request = context.getRequest();
-
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- Assert.assertEquals("/newlocation/", request.getRequestUri());
-
- final Header[] headers = request.getHeaders("Cookie");
- Assert.assertEquals("There can only be one (cookie)", 1, headers.length);
- }
-
- @Test
- public void testDefaultHeadersRedirect() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new BasicRedirectService(HttpStatus.SC_MOVED_TEMPORARILY);
- }
-
- });
-
- final List<Header> defaultHeaders = new ArrayList<>(1);
- defaultHeaders.add(new BasicHeader(HttpHeaders.USER_AGENT, "my-test-client"));
- clientBuilder.setDefaultHeaders(defaultHeaders);
-
- final HttpHost target = start();
-
- final HttpClientContext context = HttpClientContext.create();
-
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/oldlocation/"), context, null);
- final HttpResponse response = future.get();
- Assert.assertNotNull(response);
-
- final HttpRequest request = context.getRequest();
-
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- Assert.assertEquals("/newlocation/", request.getRequestUri());
-
- final Header header = request.getFirstHeader(HttpHeaders.USER_AGENT);
- Assert.assertEquals("my-test-client", header.getValue());
- }
-
- static class CrossSiteRedirectService extends AbstractSimpleServerExchangeHandler {
-
- private final HttpHost host;
-
- public CrossSiteRedirectService(final HttpHost host) {
- super();
- this.host = host;
- }
-
- @Override
- protected SimpleHttpResponse handle(
- final SimpleHttpRequest request, final HttpCoreContext context) throws HttpException {
- final String location;
- try {
- final URIBuilder uribuilder = new URIBuilder(request.getUri());
- uribuilder.setScheme(host.getSchemeName());
- uribuilder.setHost(host.getHostName());
- uribuilder.setPort(host.getPort());
- uribuilder.setPath("/random/1024");
- location = uribuilder.build().toASCIIString();
- } catch (final URISyntaxException ex) {
- throw new ProtocolException("Invalid request URI", ex);
- }
- final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_TEMPORARY_REDIRECT);
- response.addHeader(new BasicHeader("Location", location));
- return response;
- }
- }
-
- @Test
- public void testCrossSiteRedirect() throws Exception {
- server.register("/random/*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncRandomHandler();
- }
-
- });
- final HttpHost redirectTarget = start();
-
- final Http2TestServer secondServer = new Http2TestServer(IOReactorConfig.DEFAULT,
- scheme == URIScheme.HTTPS ? SSLTestContexts.createServerSSLContext() : null);
- try {
- secondServer.register("/redirect/*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new CrossSiteRedirectService(redirectTarget);
- }
-
- });
-
- secondServer.start();
- final Future<ListenerEndpoint> endpointFuture = secondServer.listen(new InetSocketAddress(0));
- final ListenerEndpoint endpoint2 = endpointFuture.get();
-
- final InetSocketAddress address2 = (InetSocketAddress) endpoint2.getAddress();
- final HttpHost initialTarget = new HttpHost("localhost", address2.getPort(), scheme.name());
-
- final Queue<Future<SimpleHttpResponse>> queue = new ConcurrentLinkedQueue<>();
- for (int i = 0; i < 1; i++) {
- queue.add(httpclient.execute(SimpleHttpRequest.get(initialTarget, "/redirect/anywhere"), null));
- }
- while (!queue.isEmpty()) {
- final Future<SimpleHttpResponse> future = queue.remove();
- final HttpResponse response = future.get();
- Assert.assertNotNull(response);
- Assert.assertEquals(200, response.getCode());
- }
- } finally {
- server.shutdown(TimeValue.ofSeconds(5));
- }
- }
-
- private static class RomeRedirectService extends AbstractSimpleServerExchangeHandler {
-
- @Override
- protected SimpleHttpResponse handle(
- final SimpleHttpRequest request, final HttpCoreContext context) throws HttpException {
- try {
- final URI requestURI = request.getUri();
- final String path = requestURI.getPath();
- if (path.equals("/rome")) {
- final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_OK);
- response.setBodyText("Successful redirect", ContentType.TEXT_PLAIN);
- return response;
- } else {
- final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_MOVED_TEMPORARILY);
- response.addHeader(new BasicHeader("Location", "/rome"));
- return response;
- }
- } catch (final URISyntaxException ex) {
- throw new ProtocolException(ex.getMessage(), ex);
- }
- }
-
- }
-
- @Test
- public void testRepeatRequest() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new RomeRedirectService();
- }
-
- });
- final HttpHost target = start();
-
- final HttpClientContext context = HttpClientContext.create();
-
- final Future<SimpleHttpResponse> future1 = httpclient.execute(
- SimpleHttpRequest.get(target, "/rome"), context, null);
- final HttpResponse response1 = future1.get();
- Assert.assertNotNull(response1);
-
- final Future<SimpleHttpResponse> future2 = httpclient.execute(
- SimpleHttpRequest.get(target, "/rome"), context, null);
- final HttpResponse response2 = future2.get();
- Assert.assertNotNull(response2);
-
- final HttpRequest request = context.getRequest();
-
- Assert.assertEquals(HttpStatus.SC_OK, response2.getCode());
- Assert.assertEquals("/rome", request.getRequestUri());
- Assert.assertEquals(target, new HttpHost(request.getAuthority(), request.getScheme()));
- }
-
- @Test
- public void testRepeatRequestRedirect() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new RomeRedirectService();
- }
-
- });
- final HttpHost target = start();
-
- final HttpClientContext context = HttpClientContext.create();
-
- final Future<SimpleHttpResponse> future1 = httpclient.execute(
- SimpleHttpRequest.get(target, "/lille"), context, null);
- final HttpResponse response1 = future1.get();
- Assert.assertNotNull(response1);
-
- final Future<SimpleHttpResponse> future2 = httpclient.execute(
- SimpleHttpRequest.get(target, "/lille"), context, null);
- final HttpResponse response2 = future2.get();
- Assert.assertNotNull(response2);
-
- final HttpRequest request = context.getRequest();
-
- Assert.assertEquals(HttpStatus.SC_OK, response2.getCode());
- Assert.assertEquals("/rome", request.getRequestUri());
- Assert.assertEquals(target, new HttpHost(request.getAuthority(), request.getScheme()));
- }
-
- @Test
- public void testDifferentRequestSameRedirect() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new RomeRedirectService();
- }
-
- });
- final HttpHost target = start();
-
- final HttpClientContext context = HttpClientContext.create();
-
- final Future<SimpleHttpResponse> future1 = httpclient.execute(
- SimpleHttpRequest.get(target, "/alian"), context, null);
- final HttpResponse response1 = future1.get();
- Assert.assertNotNull(response1);
-
- final Future<SimpleHttpResponse> future2 = httpclient.execute(
- SimpleHttpRequest.get(target, "/lille"), context, null);
- final HttpResponse response2 = future2.get();
- Assert.assertNotNull(response2);
-
-
- final HttpRequest request = context.getRequest();
-
- Assert.assertEquals(HttpStatus.SC_OK, response2.getCode());
- Assert.assertEquals("/rome", request.getRequestUri());
- Assert.assertEquals(target, new HttpHost(request.getAuthority(), request.getScheme()));
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/6228a736/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestAsyncStatefulConnManagement.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestAsyncStatefulConnManagement.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestAsyncStatefulConnManagement.java
deleted file mode 100644
index bbede25..0000000
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestAsyncStatefulConnManagement.java
+++ /dev/null
@@ -1,261 +0,0 @@
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
-package org.apache.hc.client5.testing.async;
-
-import java.util.concurrent.Future;
-
-import org.apache.hc.client5.http.HttpRoute;
-import org.apache.hc.client5.http.UserTokenHandler;
-import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
-import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
-import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
-import org.apache.hc.client5.http.protocol.HttpClientContext;
-import org.apache.hc.core5.function.Supplier;
-import org.apache.hc.core5.http.ContentType;
-import org.apache.hc.core5.http.EndpointDetails;
-import org.apache.hc.core5.http.HttpException;
-import org.apache.hc.core5.http.HttpHost;
-import org.apache.hc.core5.http.HttpResponse;
-import org.apache.hc.core5.http.HttpStatus;
-import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
-import org.apache.hc.core5.http.protocol.BasicHttpContext;
-import org.apache.hc.core5.http.protocol.HttpContext;
-import org.apache.hc.core5.http.protocol.HttpCoreContext;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class TestAsyncStatefulConnManagement extends IntegrationTestBase {
-
- @Test
- public void testStatefulConnections() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AbstractSimpleServerExchangeHandler() {
-
- @Override
- protected SimpleHttpResponse handle(
- final SimpleHttpRequest request,
- final HttpCoreContext context) throws HttpException {
- final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_OK);
- response.setBodyText("Whatever", ContentType.TEXT_PLAIN);
- return response;
- }
- };
- }
-
- });
-
- final UserTokenHandler userTokenHandler = new UserTokenHandler() {
-
- @Override
- public Object getUserToken(final HttpRoute route, final HttpContext context) {
- return context.getAttribute("user");
- }
-
- };
- clientBuilder.setUserTokenHandler(userTokenHandler);
- final HttpHost target = start();
-
- final int workerCount = 2;
- final int requestCount = 5;
-
- final HttpContext[] contexts = new HttpContext[workerCount];
- final HttpWorker[] workers = new HttpWorker[workerCount];
- for (int i = 0; i < contexts.length; i++) {
- final HttpClientContext context = HttpClientContext.create();
- contexts[i] = context;
- workers[i] = new HttpWorker(
- "user" + i,
- context, requestCount, target, httpclient);
- }
-
- for (final HttpWorker worker : workers) {
- worker.start();
- }
- for (final HttpWorker worker : workers) {
- worker.join(LONG_TIMEOUT.toMillis());
- }
- for (final HttpWorker worker : workers) {
- final Exception ex = worker.getException();
- if (ex != null) {
- throw ex;
- }
- Assert.assertEquals(requestCount, worker.getCount());
- }
-
- for (final HttpContext context : contexts) {
- final String state0 = (String) context.getAttribute("r0");
- Assert.assertNotNull(state0);
- for (int r = 1; r < requestCount; r++) {
- Assert.assertEquals(state0, context.getAttribute("r" + r));
- }
- }
-
- }
-
- static class HttpWorker extends Thread {
-
- private final String uid;
- private final HttpClientContext context;
- private final int requestCount;
- private final HttpHost target;
- private final CloseableHttpAsyncClient httpclient;
-
- private volatile Exception exception;
- private volatile int count;
-
- public HttpWorker(
- final String uid,
- final HttpClientContext context,
- final int requestCount,
- final HttpHost target,
- final CloseableHttpAsyncClient httpclient) {
- super();
- this.uid = uid;
- this.context = context;
- this.requestCount = requestCount;
- this.target = target;
- this.httpclient = httpclient;
- this.count = 0;
- }
-
- public int getCount() {
- return count;
- }
-
- public Exception getException() {
- return exception;
- }
-
- @Override
- public void run() {
- try {
- context.setAttribute("user", uid);
- for (int r = 0; r < requestCount; r++) {
- final SimpleHttpRequest httpget = SimpleHttpRequest.get(target, "/");
- final Future<SimpleHttpResponse> future = httpclient.execute(httpget, null);
- future.get();
-
- count++;
- final EndpointDetails endpointDetails = context.getEndpointDetails();
- final String connuid = Integer.toHexString(System.identityHashCode(endpointDetails));
- context.setAttribute("r" + r, connuid);
- }
-
- } catch (final Exception ex) {
- exception = ex;
- }
- }
-
- }
-
- @Test
- public void testRouteSpecificPoolRecylcing() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AbstractSimpleServerExchangeHandler() {
-
- @Override
- protected SimpleHttpResponse handle(
- final SimpleHttpRequest request,
- final HttpCoreContext context) throws HttpException {
- final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_OK);
- response.setBodyText("Whatever", ContentType.TEXT_PLAIN);
- return response;
- }
- };
- }
-
- });
-
- // This tests what happens when a maxed connection pool needs
- // to kill the last idle connection to a route to build a new
- // one to the same route.
- final UserTokenHandler userTokenHandler = new UserTokenHandler() {
-
- @Override
- public Object getUserToken(final HttpRoute route, final HttpContext context) {
- return context.getAttribute("user");
- }
-
- };
- clientBuilder.setUserTokenHandler(userTokenHandler);
-
- final HttpHost target = start();
- final int maxConn = 2;
- // We build a client with 2 max active // connections, and 2 max per route.
- connManager.setMaxTotal(maxConn);
- connManager.setDefaultMaxPerRoute(maxConn);
-
- // Bottom of the pool : a *keep alive* connection to Route 1.
- final HttpContext context1 = new BasicHttpContext();
- context1.setAttribute("user", "stuff");
-
- final Future<SimpleHttpResponse> future1 = httpclient.execute(SimpleHttpRequest.get(target, "/"), context1, null);
- final HttpResponse response1 = future1.get();
- Assert.assertNotNull(response1);
- Assert.assertEquals(200, response1.getCode());
-
- // The ConnPoolByRoute now has 1 free connection, out of 2 max
- // The ConnPoolByRoute has one RouteSpcfcPool, that has one free connection
- // for [localhost][stuff]
-
- Thread.sleep(100);
-
- // Send a very simple HTTP get (it MUST be simple, no auth, no proxy, no 302, no 401, ...)
- // Send it to another route. Must be a keepalive.
- final HttpContext context2 = new BasicHttpContext();
-
- final Future<SimpleHttpResponse> future2 = httpclient.execute(SimpleHttpRequest.get(
- new HttpHost("127.0.0.1", target.getPort(), target.getSchemeName()),"/"), context2, null);
- final HttpResponse response2 = future2.get();
- Assert.assertNotNull(response2);
- Assert.assertEquals(200, response2.getCode());
-
- // ConnPoolByRoute now has 2 free connexions, out of its 2 max.
- // The [localhost][stuff] RouteSpcfcPool is the same as earlier
- // And there is a [127.0.0.1][null] pool with 1 free connection
-
- Thread.sleep(100);
-
- // This will put the ConnPoolByRoute to the targeted state :
- // [localhost][stuff] will not get reused because this call is [localhost][null]
- // So the ConnPoolByRoute will need to kill one connection (it is maxed out globally).
- // The killed conn is the oldest, which means the first HTTPGet ([localhost][stuff]).
- // When this happens, the RouteSpecificPool becomes empty.
- final HttpContext context3 = new BasicHttpContext();
- final Future<SimpleHttpResponse> future3 = httpclient.execute(SimpleHttpRequest.get(target, "/"), context3, null);
- final HttpResponse response3 = future3.get();
- Assert.assertNotNull(response3);
- Assert.assertEquals(200, response3.getCode());
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/6228a736/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestClientAuthentication.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestClientAuthentication.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestClientAuthentication.java
deleted file mode 100644
index 7841420..0000000
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestClientAuthentication.java
+++ /dev/null
@@ -1,598 +0,0 @@
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
-package org.apache.hc.client5.testing.async;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Future;
-import java.util.concurrent.atomic.AtomicLong;
-
-import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
-import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
-import org.apache.hc.client5.http.auth.AuthChallenge;
-import org.apache.hc.client5.http.auth.AuthScheme;
-import org.apache.hc.client5.http.auth.AuthSchemeProvider;
-import org.apache.hc.client5.http.auth.AuthScope;
-import org.apache.hc.client5.http.auth.ChallengeType;
-import org.apache.hc.client5.http.auth.Credentials;
-import org.apache.hc.client5.http.auth.CredentialsStore;
-import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
-import org.apache.hc.client5.http.config.RequestConfig;
-import org.apache.hc.client5.http.impl.DefaultAuthenticationStrategy;
-import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
-import org.apache.hc.client5.http.impl.auth.BasicScheme;
-import org.apache.hc.client5.http.protocol.HttpClientContext;
-import org.apache.hc.client5.testing.BasicTestAuthenticator;
-import org.apache.hc.client5.testing.auth.Authenticator;
-import org.apache.hc.core5.function.Decorator;
-import org.apache.hc.core5.function.Supplier;
-import org.apache.hc.core5.http.ContentType;
-import org.apache.hc.core5.http.HeaderElements;
-import org.apache.hc.core5.http.HttpException;
-import org.apache.hc.core5.http.HttpHeaders;
-import org.apache.hc.core5.http.HttpHost;
-import org.apache.hc.core5.http.HttpResponse;
-import org.apache.hc.core5.http.HttpStatus;
-import org.apache.hc.core5.http.URIScheme;
-import org.apache.hc.core5.http.config.H1Config;
-import org.apache.hc.core5.http.config.Registry;
-import org.apache.hc.core5.http.config.RegistryBuilder;
-import org.apache.hc.core5.http.impl.HttpProcessors;
-import org.apache.hc.core5.http.message.BasicHeader;
-import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
-import org.apache.hc.core5.http.protocol.HttpContext;
-import org.apache.hc.core5.http.protocol.HttpCoreContext;
-import org.apache.hc.core5.net.URIAuthority;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-
-@RunWith(Parameterized.class)
-public class TestClientAuthentication extends IntegrationTestBase {
-
- @Parameterized.Parameters(name = "{0}")
- public static Collection<Object[]> protocols() {
- return Arrays.asList(new Object[][]{
- {URIScheme.HTTP},
- {URIScheme.HTTPS},
- });
- }
-
- public TestClientAuthentication(final URIScheme scheme) {
- super(scheme);
- }
-
- @Override
- public HttpHost start() throws Exception {
- return super.start(
- HttpProcessors.server(),
- new Decorator<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler requestHandler) {
- return new AuthenticatingAsyncDecorator(requestHandler, new BasicTestAuthenticator("test:test", "test realm"));
- }
-
- },
- H1Config.DEFAULT);
- }
-
- static class TestCredentialsProvider implements CredentialsStore {
-
- private final Credentials creds;
- private AuthScope authscope;
-
- TestCredentialsProvider(final Credentials creds) {
- super();
- this.creds = creds;
- }
-
- @Override
- public void clear() {
- }
-
- @Override
- public Credentials getCredentials(final AuthScope authscope, final HttpContext context) {
- this.authscope = authscope;
- return this.creds;
- }
-
- @Override
- public void setCredentials(final AuthScope authscope, final Credentials credentials) {
- }
-
- public AuthScope getAuthScope() {
- return this.authscope;
- }
-
- }
-
- @Test
- public void testBasicAuthenticationNoCreds() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncEchoHandler();
- }
-
- });
- final HttpHost target = start();
-
- final TestCredentialsProvider credsProvider = new TestCredentialsProvider(null);
- final HttpClientContext context = HttpClientContext.create();
- context.setCredentialsProvider(credsProvider);
-
- final Future<SimpleHttpResponse> future = httpclient.execute(SimpleHttpRequest.get(target, "/"), context, null);
- final HttpResponse response = future.get();
-
- Assert.assertNotNull(response);
- Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
- final AuthScope authscope = credsProvider.getAuthScope();
- Assert.assertNotNull(authscope);
- Assert.assertEquals("test realm", authscope.getRealm());
- }
-
- @Test
- public void testBasicAuthenticationFailure() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncEchoHandler();
- }
-
- });
- final HttpHost target = start();
-
- final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
- new UsernamePasswordCredentials("test", "all-wrong".toCharArray()));
- final HttpClientContext context = HttpClientContext.create();
- context.setCredentialsProvider(credsProvider);
-
- final Future<SimpleHttpResponse> future = httpclient.execute(SimpleHttpRequest.get(target, "/"), context, null);
- final HttpResponse response = future.get();
-
- Assert.assertNotNull(response);
- Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
- final AuthScope authscope = credsProvider.getAuthScope();
- Assert.assertNotNull(authscope);
- Assert.assertEquals("test realm", authscope.getRealm());
- }
-
- @Test
- public void testBasicAuthenticationSuccess() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncEchoHandler();
- }
-
- });
- final HttpHost target = start();
-
- final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
- new UsernamePasswordCredentials("test", "test".toCharArray()));
- final HttpClientContext context = HttpClientContext.create();
- context.setCredentialsProvider(credsProvider);
-
- final Future<SimpleHttpResponse> future = httpclient.execute(SimpleHttpRequest.get(target, "/"), context, null);
- final HttpResponse response = future.get();
-
- Assert.assertNotNull(response);
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- final AuthScope authscope = credsProvider.getAuthScope();
- Assert.assertNotNull(authscope);
- Assert.assertEquals("test realm", authscope.getRealm());
- }
-
- @Test
- public void testBasicAuthenticationWithEntitySuccess() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncEchoHandler();
- }
-
- });
- final HttpHost target = start();
-
- final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
- new UsernamePasswordCredentials("test", "test".toCharArray()));
- final HttpClientContext context = HttpClientContext.create();
- context.setCredentialsProvider(credsProvider);
-
- final SimpleHttpRequest put = SimpleHttpRequest.put(target, "/");
- put.setBodyText("Some important stuff", ContentType.TEXT_PLAIN);
- final Future<SimpleHttpResponse> future = httpclient.execute(put, context, null);
- final HttpResponse response = future.get();
-
- Assert.assertNotNull(response);
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- final AuthScope authscope = credsProvider.getAuthScope();
- Assert.assertNotNull(authscope);
- Assert.assertEquals("test realm", authscope.getRealm());
- }
-
- @Test
- public void testBasicAuthenticationSuccessNonPersistentConnection() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncEchoHandler();
- }
-
- });
- final HttpHost target = start(
- HttpProcessors.server(),
- new Decorator<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
- return new AuthenticatingAsyncDecorator(exchangeHandler, new BasicTestAuthenticator("test:test", "test realm")) {
-
- @Override
- protected void customizeUnauthorizedResponse(final HttpResponse unauthorized) {
- unauthorized.addHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE);
- }
- };
- }
-
- },
- H1Config.DEFAULT);
-
- final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
- new UsernamePasswordCredentials("test", "test".toCharArray()));
- final HttpClientContext context = HttpClientContext.create();
- context.setCredentialsProvider(credsProvider);
-
- final Future<SimpleHttpResponse> future = httpclient.execute(SimpleHttpRequest.get(target, "/"), context, null);
- final HttpResponse response = future.get();
-
- Assert.assertNotNull(response);
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- final AuthScope authscope = credsProvider.getAuthScope();
- Assert.assertNotNull(authscope);
- Assert.assertEquals("test realm", authscope.getRealm());
- }
-
- @Test
- public void testBasicAuthenticationExpectationFailure() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncEchoHandler();
- }
-
- });
- final HttpHost target = start();
-
- final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
- new UsernamePasswordCredentials("test", "all-wrong".toCharArray()));
- final HttpClientContext context = HttpClientContext.create();
- context.setCredentialsProvider(credsProvider);
- context.setRequestConfig(RequestConfig.custom().setExpectContinueEnabled(true).build());
-
- final SimpleHttpRequest put = SimpleHttpRequest.put(target, "/");
- put.setBodyText("Some important stuff", ContentType.TEXT_PLAIN);
- final Future<SimpleHttpResponse> future = httpclient.execute(put, context, null);
- final HttpResponse response = future.get();
-
- Assert.assertNotNull(response);
- Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
- }
-
- @Test
- public void testBasicAuthenticationExpectationSuccess() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncEchoHandler();
- }
-
- });
- final HttpHost target = start();
-
- final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
- new UsernamePasswordCredentials("test", "test".toCharArray()));
- final HttpClientContext context = HttpClientContext.create();
- context.setCredentialsProvider(credsProvider);
- context.setRequestConfig(RequestConfig.custom().setExpectContinueEnabled(true).build());
-
- final SimpleHttpRequest put = SimpleHttpRequest.put(target, "/");
- put.setBodyText("Some important stuff", ContentType.TEXT_PLAIN);
- final Future<SimpleHttpResponse> future = httpclient.execute(put, context, null);
- final HttpResponse response = future.get();
-
- Assert.assertNotNull(response);
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- final AuthScope authscope = credsProvider.getAuthScope();
- Assert.assertNotNull(authscope);
- Assert.assertEquals("test realm", authscope.getRealm());
- }
-
- @Test
- public void testBasicAuthenticationCredentialsCaching() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncEchoHandler();
- }
-
- });
-
- final AtomicLong count = new AtomicLong(0);
- this.clientBuilder.setTargetAuthenticationStrategy(new DefaultAuthenticationStrategy() {
-
- @Override
- public List<AuthScheme> select(
- final ChallengeType challengeType,
- final Map<String, AuthChallenge> challenges,
- final HttpContext context) {
- count.incrementAndGet();
- return super.select(challengeType, challenges, context);
- }
- });
- final HttpHost target = start();
-
- final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
- credsProvider.setCredentials(AuthScope.ANY,
- new UsernamePasswordCredentials("test", "test".toCharArray()));
- final HttpClientContext context = HttpClientContext.create();
- context.setCredentialsProvider(credsProvider);
-
- final Future<SimpleHttpResponse> future1 = httpclient.execute(SimpleHttpRequest.get(target, "/"), context, null);
- final HttpResponse response1 = future1.get();
- Assert.assertNotNull(response1);
- Assert.assertEquals(HttpStatus.SC_OK, response1.getCode());
-
- final Future<SimpleHttpResponse> future2 = httpclient.execute(SimpleHttpRequest.get(target, "/"), context, null);
- final HttpResponse response2 = future2.get();
- Assert.assertNotNull(response2);
- Assert.assertEquals(HttpStatus.SC_OK, response2.getCode());
-
- Assert.assertEquals(1, count.get());
- }
-
- @Test
- public void testAuthenticationUserinfoInRequestSuccess() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncEchoHandler();
- }
-
- });
- final HttpHost target = start();
-
- final HttpClientContext context = HttpClientContext.create();
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target.getSchemeName() + "://test:test@" + target.toHostString() + "/"), context, null);
- final SimpleHttpResponse response = future.get();
-
- Assert.assertNotNull(response);
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- }
-
- @Test
- public void testAuthenticationUserinfoInRequestFailure() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncEchoHandler();
- }
-
- });
- final HttpHost target = start();
-
- final HttpClientContext context = HttpClientContext.create();
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target.getSchemeName() + "://test:all-worng@" + target.toHostString() + "/"), context, null);
- final SimpleHttpResponse response = future.get();
-
- Assert.assertNotNull(response);
- Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getCode());
- }
-
- @Test
- public void testAuthenticationUserinfoInRedirectSuccess() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncEchoHandler();
- }
-
- });
- final HttpHost target = start();
- server.register("/thatway", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AbstractSimpleServerExchangeHandler() {
-
- @Override
- protected SimpleHttpResponse handle(
- final SimpleHttpRequest request, final HttpCoreContext context) throws HttpException {
- final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_MOVED_PERMANENTLY);
- response.addHeader(new BasicHeader("Location", target.getSchemeName() + "://test:test@" + target.toHostString() + "/"));
- return response;
- }
- };
- }
-
- });
-
- final HttpClientContext context = HttpClientContext.create();
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target.getSchemeName() + "://test:test@" + target.toHostString() + "/thatway"), context, null);
- final SimpleHttpResponse response = future.get();
-
- Assert.assertNotNull(response);
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- }
-
- @Test
- public void testReauthentication() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncEchoHandler();
- }
-
- });
- final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
- new UsernamePasswordCredentials("test", "test".toCharArray()));
-
- final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
- .register("MyBasic", new AuthSchemeProvider() {
-
- @Override
- public AuthScheme create(final HttpContext context) {
- return new BasicScheme() {
-
- @Override
- public String getName() {
- return "MyBasic";
- }
-
- };
- }
-
- })
- .build();
- this.clientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
-
- final Authenticator authenticator = new BasicTestAuthenticator("test:test", "test realm") {
-
- private final AtomicLong count = new AtomicLong(0);
-
- @Override
- public boolean authenticate(final URIAuthority authority, final String requestUri, final String credentials) {
- final boolean authenticated = super.authenticate(authority, requestUri, credentials);
- if (authenticated) {
- if (this.count.incrementAndGet() % 4 != 0) {
- return true;
- } else {
- return false;
- }
- } else {
- return false;
- }
- }
- };
-
- final HttpHost target = start(
- HttpProcessors.server(),
- new Decorator<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
- return new AuthenticatingAsyncDecorator(exchangeHandler, authenticator) {
-
- @Override
- protected void customizeUnauthorizedResponse(final HttpResponse unauthorized) {
- unauthorized.removeHeaders(HttpHeaders.WWW_AUTHENTICATE);
- unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, "MyBasic realm=\"test realm\"");
- }
-
- };
- }
-
- }, H1Config.DEFAULT);
-
- final RequestConfig config = RequestConfig.custom()
- .setTargetPreferredAuthSchemes(Arrays.asList("MyBasic"))
- .build();
- final HttpClientContext context = HttpClientContext.create();
- context.setCredentialsProvider(credsProvider);
-
- for (int i = 0; i < 10; i++) {
- final SimpleHttpRequest request = SimpleHttpRequest.get(target, "/");
- request.setConfig(config);
- final Future<SimpleHttpResponse> future = httpclient.execute(request, context, null);
- final SimpleHttpResponse response = future.get();
- Assert.assertNotNull(response);
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- }
- }
-
- @Test
- public void testAuthenticationFallback() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncEchoHandler();
- }
-
- });
- final HttpHost target = start(
- HttpProcessors.server(),
- new Decorator<AsyncServerExchangeHandler>() {
-
- @Override
- public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
- return new AuthenticatingAsyncDecorator(exchangeHandler, new BasicTestAuthenticator("test:test", "test realm")) {
-
- @Override
- protected void customizeUnauthorizedResponse(final HttpResponse unauthorized) {
- unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"test realm\" invalid");
- }
-
- };
- }
-
- }, H1Config.DEFAULT);
-
- final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
- new UsernamePasswordCredentials("test", "test".toCharArray()));
- final HttpClientContext context = HttpClientContext.create();
- context.setCredentialsProvider(credsProvider);
-
- final Future<SimpleHttpResponse> future = httpclient.execute(SimpleHttpRequest.get(target, "/"), context, null);
- final SimpleHttpResponse response = future.get();
- Assert.assertNotNull(response);
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- final AuthScope authscope = credsProvider.getAuthScope();
- Assert.assertNotNull(authscope);
- Assert.assertEquals("test realm", authscope.getRealm());
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/6228a736/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1Async.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1Async.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1Async.java
new file mode 100644
index 0000000..506001f
--- /dev/null
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1Async.java
@@ -0,0 +1,198 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.client5.testing.async;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.concurrent.Future;
+
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.client5.http.config.RequestConfig;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder;
+import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
+import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
+import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
+import org.apache.hc.client5.http.ssl.H2TlsStrategy;
+import org.apache.hc.client5.testing.SSLTestContexts;
+import org.apache.hc.core5.http.HeaderElements;
+import org.apache.hc.core5.http.HttpHeaders;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.URIScheme;
+import org.apache.hc.core5.http.config.H1Config;
+import org.hamcrest.CoreMatchers;
+import org.junit.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExternalResource;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+@RunWith(Parameterized.class)
+public class TestHttp1Async extends AbstractHttpAsyncFundamentalsTest<CloseableHttpAsyncClient> {
+
+ @Parameterized.Parameters(name = "HTTP/1.1 {0}")
+ public static Collection<Object[]> protocols() {
+ return Arrays.asList(new Object[][]{
+ { URIScheme.HTTP },
+ { URIScheme.HTTPS },
+ });
+ }
+
+ protected HttpAsyncClientBuilder clientBuilder;
+ protected PoolingAsyncClientConnectionManager connManager;
+
+ @Rule
+ public ExternalResource connManagerResource = new ExternalResource() {
+
+ @Override
+ protected void before() throws Throwable {
+ connManager = PoolingAsyncClientConnectionManagerBuilder.create()
+ .setTlsStrategy(new H2TlsStrategy(SSLTestContexts.createClientSSLContext()))
+ .build();
+ }
+
+ @Override
+ protected void after() {
+ if (connManager != null) {
+ connManager.close();
+ connManager = null;
+ }
+ }
+
+ };
+
+ @Rule
+ public ExternalResource clientResource = new ExternalResource() {
+
+ @Override
+ protected void before() throws Throwable {
+ clientBuilder = HttpAsyncClientBuilder.create()
+ .setDefaultRequestConfig(RequestConfig.custom()
+ .setSocketTimeout(TIMEOUT)
+ .setConnectTimeout(TIMEOUT)
+ .setConnectionRequestTimeout(TIMEOUT)
+ .build())
+ .setConnectionManager(connManager);
+ }
+
+ };
+
+ public TestHttp1Async(final URIScheme scheme) {
+ super(scheme);
+ }
+
+ @Override
+ protected CloseableHttpAsyncClient createClient() {
+ return clientBuilder.build();
+ }
+
+ @Override
+ public HttpHost start() throws Exception {
+ return super.start(null, H1Config.DEFAULT);
+ }
+
+ @Test
+ public void testSequenctialGetRequestsCloseConnection() throws Exception {
+ final HttpHost target = start();
+ for (int i = 0; i < 3; i++) {
+ final SimpleHttpRequest get = SimpleHttpRequest.get(target, "/random/2048");
+ get.setHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE);
+ final Future<SimpleHttpResponse> future = httpclient.execute(get, null);
+ final SimpleHttpResponse response = future.get();
+ Assert.assertThat(response, CoreMatchers.notNullValue());
+ Assert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
+ final String body = response.getBodyText();
+ Assert.assertThat(body, CoreMatchers.notNullValue());
+ Assert.assertThat(body.length(), CoreMatchers.equalTo(2048));
+ }
+ }
+
+ @Test
+ public void testConcurrentPostsOverMultipleConnections() throws Exception {
+ connManager.setDefaultMaxPerRoute(20);
+ connManager.setMaxTotal(100);
+ super.testConcurrentPostRequests();
+ }
+
+ @Test
+ public void testConcurrentPostsOverSingleConnection() throws Exception {
+ connManager.setDefaultMaxPerRoute(1);
+ connManager.setMaxTotal(100);
+ super.testConcurrentPostRequests();
+ }
+
+ @Test
+ public void testSharedPool() throws Exception {
+ final HttpHost target = start();
+ final Future<SimpleHttpResponse> future1 = httpclient.execute(
+ SimpleHttpRequest.get(target, "/random/2048"), null);
+ final SimpleHttpResponse response1 = future1.get();
+ Assert.assertThat(response1, CoreMatchers.notNullValue());
+ Assert.assertThat(response1.getCode(), CoreMatchers.equalTo(200));
+ final String body1 = response1.getBodyText();
+ Assert.assertThat(body1, CoreMatchers.notNullValue());
+ Assert.assertThat(body1.length(), CoreMatchers.equalTo(2048));
+
+
+ try (final CloseableHttpAsyncClient httpclient2 = HttpAsyncClients.custom()
+ .setConnectionManager(connManager)
+ .setConnectionManagerShared(true)
+ .build()) {
+ httpclient2.start();
+ final Future<SimpleHttpResponse> future2 = httpclient2.execute(
+ SimpleHttpRequest.get(target, "/random/2048"), null);
+ final SimpleHttpResponse response2 = future2.get();
+ Assert.assertThat(response2, CoreMatchers.notNullValue());
+ Assert.assertThat(response2.getCode(), CoreMatchers.equalTo(200));
+ final String body2 = response2.getBodyText();
+ Assert.assertThat(body2, CoreMatchers.notNullValue());
+ Assert.assertThat(body2.length(), CoreMatchers.equalTo(2048));
+ }
+
+ final Future<SimpleHttpResponse> future3 = httpclient.execute(
+ SimpleHttpRequest.get(target, "/random/2048"), null);
+ final SimpleHttpResponse response3 = future3.get();
+ Assert.assertThat(response3, CoreMatchers.notNullValue());
+ Assert.assertThat(response3.getCode(), CoreMatchers.equalTo(200));
+ final String body3 = response3.getBodyText();
+ Assert.assertThat(body3, CoreMatchers.notNullValue());
+ Assert.assertThat(body3.length(), CoreMatchers.equalTo(2048));
+ }
+
+ @Test
+ public void testBadRequest() throws Exception {
+ final HttpHost target = start();
+ final Future<SimpleHttpResponse> future = httpclient.execute(
+ SimpleHttpRequest.get(target, "/random/boom"), null);
+ final SimpleHttpResponse response = future.get();
+ Assert.assertThat(response, CoreMatchers.notNullValue());
+ Assert.assertThat(response.getCode(), CoreMatchers.equalTo(400));
+ }
+
+}
\ No newline at end of file