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:45:59 UTC
[4/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/TestHttp1AsyncRedirects.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1AsyncRedirects.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1AsyncRedirects.java
new file mode 100644
index 0000000..48caa35
--- /dev/null
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1AsyncRedirects.java
@@ -0,0 +1,254 @@
+/*
+ * ====================================================================
+ * 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.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+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.nio.PoolingAsyncClientConnectionManager;
+import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
+import org.apache.hc.client5.http.protocol.HttpClientContext;
+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.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.config.H1Config;
+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.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;
+
+/**
+ * Redirection test cases.
+ */
+@RunWith(Parameterized.class)
+public class TestHttp1AsyncRedirects extends AbstractHttpAsyncRedirectsTest<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 TestHttp1AsyncRedirects(final URIScheme scheme) {
+ super(scheme);
+ }
+
+ @Override
+ protected CloseableHttpAsyncClient createClient() throws Exception {
+ return clientBuilder.build();
+ }
+
+ @Override
+ public final HttpHost start() throws Exception {
+ return super.start(null, H1Config.DEFAULT);
+ }
+
+ static class NoKeepAliveRedirectService extends AbstractSimpleServerExchangeHandler {
+
+ private final int statuscode;
+
+ public NoKeepAliveRedirectService(final int statuscode) {
+ super();
+ this.statuscode = statuscode;
+ }
+
+ @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()));
+ 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);
+ }
+ }
+
+ }
+
+ @Test
+ public void testBasicRedirect300() throws Exception {
+ server.register("*", new Supplier<AsyncServerExchangeHandler>() {
+
+ @Override
+ public AsyncServerExchangeHandler get() {
+ return new NoKeepAliveRedirectService(HttpStatus.SC_MULTIPLE_CHOICES);
+ }
+
+ });
+ 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 testBasicRedirect301NoKeepAlive() throws Exception {
+ server.register("*", new Supplier<AsyncServerExchangeHandler>() {
+
+ @Override
+ public AsyncServerExchangeHandler get() {
+ return new NoKeepAliveRedirectService(HttpStatus.SC_MOVED_PERMANENTLY);
+ }
+
+ });
+
+ 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 testDefaultHeadersRedirect() throws Exception {
+ server.register("*", new Supplier<AsyncServerExchangeHandler>() {
+
+ @Override
+ public AsyncServerExchangeHandler get() {
+ return new NoKeepAliveRedirectService(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());
+ }
+
+}
\ 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/TestHttp1AsyncStatefulConnManagement.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1AsyncStatefulConnManagement.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1AsyncStatefulConnManagement.java
new file mode 100644
index 0000000..7880f6c
--- /dev/null
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1AsyncStatefulConnManagement.java
@@ -0,0 +1,319 @@
+/*
+ * ====================================================================
+ * 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.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.nio.PoolingAsyncClientConnectionManager;
+import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
+import org.apache.hc.client5.http.protocol.HttpClientContext;
+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.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.config.H1Config;
+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.Rule;
+import org.junit.Test;
+import org.junit.rules.ExternalResource;
+
+public class TestHttp1AsyncStatefulConnManagement extends AbstractIntegrationTestBase<CloseableHttpAsyncClient> {
+
+ 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);
+ }
+
+ };
+
+ @Override
+ protected CloseableHttpAsyncClient createClient() throws Exception {
+ return clientBuilder.build();
+ }
+
+ @Override
+ public HttpHost start() throws Exception {
+ return super.start(null, H1Config.DEFAULT);
+ }
+
+ @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/TestHttp1ClientAuthentication.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1ClientAuthentication.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1ClientAuthentication.java
new file mode 100644
index 0000000..e998c43
--- /dev/null
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1ClientAuthentication.java
@@ -0,0 +1,180 @@
+/*
+ * ====================================================================
+ * 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.AuthenticationStrategy;
+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.AuthSchemeProvider;
+import org.apache.hc.client5.http.auth.AuthScope;
+import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
+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.nio.PoolingAsyncClientConnectionManager;
+import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
+import org.apache.hc.client5.http.protocol.HttpClientContext;
+import org.apache.hc.client5.http.ssl.H2TlsStrategy;
+import org.apache.hc.client5.testing.BasicTestAuthenticator;
+import org.apache.hc.client5.testing.SSLTestContexts;
+import org.apache.hc.core5.function.Decorator;
+import org.apache.hc.core5.function.Supplier;
+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.HttpResponse;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.HttpVersion;
+import org.apache.hc.core5.http.URIScheme;
+import org.apache.hc.core5.http.config.H1Config;
+import org.apache.hc.core5.http.config.Lookup;
+import org.apache.hc.core5.http.impl.HttpProcessors;
+import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
+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 TestHttp1ClientAuthentication extends AbstractHttpAsyncClientAuthentication<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 TestHttp1ClientAuthentication(final URIScheme scheme) {
+ super(scheme, HttpVersion.HTTP_1_1);
+ }
+
+ @Override
+ void setDefaultAuthSchemeRegistry(final Lookup<AuthSchemeProvider> authSchemeRegistry) {
+ clientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
+ }
+
+ @Override
+ void setTargetAuthenticationStrategy(final AuthenticationStrategy targetAuthStrategy) {
+ clientBuilder.setTargetAuthenticationStrategy(targetAuthStrategy);
+ }
+
+ @Override
+ protected CloseableHttpAsyncClient createClient() throws Exception {
+ return clientBuilder.build();
+ }
+
+ @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());
+ }
+
+}
\ 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/TestHttp2Async.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp2Async.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp2Async.java
new file mode 100644
index 0000000..b0035e9
--- /dev/null
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp2Async.java
@@ -0,0 +1,88 @@
+/*
+ * ====================================================================
+ * 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 org.apache.hc.client5.http.config.RequestConfig;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.client5.http.impl.async.Http2AsyncClientBuilder;
+import org.apache.hc.client5.http.ssl.H2TlsStrategy;
+import org.apache.hc.client5.testing.SSLTestContexts;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.URIScheme;
+import org.apache.hc.core5.http2.config.H2Config;
+import org.junit.Rule;
+import org.junit.rules.ExternalResource;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+@RunWith(Parameterized.class)
+public class TestHttp2Async extends AbstractHttpAsyncFundamentalsTest<CloseableHttpAsyncClient> {
+
+ @Parameterized.Parameters(name = "HTTP/2 {0}")
+ public static Collection<Object[]> protocols() {
+ return Arrays.asList(new Object[][]{
+ { URIScheme.HTTP },
+ { URIScheme.HTTPS }
+ });
+ }
+
+ protected Http2AsyncClientBuilder clientBuilder;
+
+ @Rule
+ public ExternalResource clientResource = new ExternalResource() {
+
+ @Override
+ protected void before() throws Throwable {
+ clientBuilder = Http2AsyncClientBuilder.create()
+ .setDefaultRequestConfig(RequestConfig.custom()
+ .setSocketTimeout(TIMEOUT)
+ .setConnectTimeout(TIMEOUT)
+ .setConnectionRequestTimeout(TIMEOUT)
+ .build())
+ .setTlsStrategy(new H2TlsStrategy(SSLTestContexts.createClientSSLContext()));
+ }
+
+ };
+
+ public TestHttp2Async(final URIScheme scheme) {
+ super(scheme);
+ }
+
+ @Override
+ protected CloseableHttpAsyncClient createClient() {
+ return clientBuilder.build();
+ }
+
+ @Override
+ public HttpHost start() throws Exception {
+ return super.start(null, H2Config.DEFAULT);
+ }
+
+}
\ 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/TestHttp2AsyncMinimal.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp2AsyncMinimal.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp2AsyncMinimal.java
index 58765a2..a3369de 100644
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp2AsyncMinimal.java
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp2AsyncMinimal.java
@@ -26,50 +26,22 @@
*/
package org.apache.hc.client5.testing.async;
-import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Collection;
-import java.util.LinkedList;
-import java.util.Queue;
-import java.util.Random;
-import java.util.concurrent.Future;
-import org.apache.hc.client5.http.async.methods.AsyncRequestBuilder;
-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.HttpAsyncClients;
import org.apache.hc.client5.http.impl.async.MinimalHttp2AsyncClient;
-import org.apache.hc.client5.http.protocol.HttpClientContext;
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.ContentType;
import org.apache.hc.core5.http.HttpHost;
-import org.apache.hc.core5.http.HttpResponse;
-import org.apache.hc.core5.http.Message;
import org.apache.hc.core5.http.URIScheme;
-import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
-import org.apache.hc.core5.http.nio.BasicResponseConsumer;
-import org.apache.hc.core5.http.nio.entity.BasicAsyncEntityConsumer;
import org.apache.hc.core5.http2.config.H2Config;
-import org.apache.hc.core5.io.ShutdownType;
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.apache.hc.core5.util.Timeout;
-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 TestHttp2AsyncMinimal {
-
- public static final Timeout TIMEOUT = Timeout.ofSeconds(30);
+public class TestHttp2AsyncMinimal extends AbstractHttpAsyncFundamentalsTest<MinimalHttp2AsyncClient> {
@Parameterized.Parameters(name = "{0}")
public static Collection<Object[]> protocols() {
@@ -79,141 +51,22 @@ public class TestHttp2AsyncMinimal {
});
}
- protected final URIScheme scheme;
-
public TestHttp2AsyncMinimal(final URIScheme scheme) {
- this.scheme = scheme;
- }
-
- protected Http2TestServer server;
- protected MinimalHttp2AsyncClient httpclient;
-
- @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 clientResource = new ExternalResource() {
-
- @Override
- protected void before() throws Throwable {
- final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
- .setSoTimeout(TIMEOUT)
- .build();
- httpclient = HttpAsyncClients.createHttp2Minimal(
- H2Config.DEFAULT, ioReactorConfig, new H2TlsStrategy(SSLTestContexts.createClientSSLContext()));
- }
-
- @Override
- protected void after() {
- if (httpclient != null) {
- httpclient.shutdown(ShutdownType.GRACEFUL);
- httpclient = null;
- }
- }
-
- };
-
- public HttpHost start() throws Exception {
- server.start(H2Config.DEFAULT);
- final Future<ListenerEndpoint> endpointFuture = server.listen(new InetSocketAddress(0));
- httpclient.start();
- final ListenerEndpoint endpoint = endpointFuture.get();
- final InetSocketAddress address = (InetSocketAddress) endpoint.getAddress();
- return new HttpHost("localhost", address.getPort(), scheme.name());
+ super(scheme);
}
- @Test
- public void testSequenctialGetRequests() throws Exception {
- final HttpHost target = start();
- for (int i = 0; i < 3; i++) {
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/random/2048"), 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));
- }
+ @Override
+ protected MinimalHttp2AsyncClient createClient() throws Exception {
+ final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
+ .setSoTimeout(TIMEOUT)
+ .build();
+ return HttpAsyncClients.createHttp2Minimal(
+ H2Config.DEFAULT, ioReactorConfig, new H2TlsStrategy(SSLTestContexts.createClientSSLContext()));
}
- @Test
- public void testSequenctialHeadRequests() throws Exception {
- final HttpHost target = start();
- for (int i = 0; i < 3; i++) {
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.head(target, "/random/2048"), 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.nullValue());
- }
- }
-
- @Test
- public void testConcurrentPostsOver() throws Exception {
- final HttpHost target = start();
- final byte[] b1 = new byte[1024];
- final Random rnd = new Random(System.currentTimeMillis());
- rnd.nextBytes(b1);
-
- final int reqCount = 20;
-
- final Queue<Future<Message<HttpResponse, byte[]>>> queue = new LinkedList<>();
- for (int i = 0; i < reqCount; i++) {
- final Future<Message<HttpResponse, byte[]>> future = httpclient.execute(
- AsyncRequestBuilder.post(target, "/echo/")
- .setEntity(b1, ContentType.APPLICATION_OCTET_STREAM)
- .build(),
- new BasicResponseConsumer<>(new BasicAsyncEntityConsumer()), HttpClientContext.create(), null);
- queue.add(future);
- }
-
- while (!queue.isEmpty()) {
- final Future<Message<HttpResponse, byte[]>> future = queue.remove();
- final Message<HttpResponse, byte[]> responseMessage = future.get();
- Assert.assertThat(responseMessage, CoreMatchers.notNullValue());
- final HttpResponse response = responseMessage.getHead();
- Assert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
- final byte[] b2 = responseMessage.getBody();
- Assert.assertThat(b1, CoreMatchers.equalTo(b2));
- }
+ @Override
+ public HttpHost start() throws Exception {
+ return super.start(null, H2Config.DEFAULT);
}
}
\ 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/TestHttp2AsyncRedirect.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp2AsyncRedirect.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp2AsyncRedirect.java
new file mode 100644
index 0000000..63011af
--- /dev/null
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp2AsyncRedirect.java
@@ -0,0 +1,88 @@
+/*
+ * ====================================================================
+ * 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 org.apache.hc.client5.http.config.RequestConfig;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.client5.http.impl.async.Http2AsyncClientBuilder;
+import org.apache.hc.client5.http.ssl.H2TlsStrategy;
+import org.apache.hc.client5.testing.SSLTestContexts;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.URIScheme;
+import org.apache.hc.core5.http2.config.H2Config;
+import org.junit.Rule;
+import org.junit.rules.ExternalResource;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+@RunWith(Parameterized.class)
+public class TestHttp2AsyncRedirect extends AbstractHttpAsyncRedirectsTest<CloseableHttpAsyncClient> {
+
+ @Parameterized.Parameters(name = "HTTP/2 {0}")
+ public static Collection<Object[]> protocols() {
+ return Arrays.asList(new Object[][]{
+ { URIScheme.HTTP },
+ { URIScheme.HTTPS }
+ });
+ }
+
+ protected Http2AsyncClientBuilder clientBuilder;
+
+ @Rule
+ public ExternalResource clientResource = new ExternalResource() {
+
+ @Override
+ protected void before() throws Throwable {
+ clientBuilder = Http2AsyncClientBuilder.create()
+ .setDefaultRequestConfig(RequestConfig.custom()
+ .setSocketTimeout(TIMEOUT)
+ .setConnectTimeout(TIMEOUT)
+ .setConnectionRequestTimeout(TIMEOUT)
+ .build())
+ .setTlsStrategy(new H2TlsStrategy(SSLTestContexts.createClientSSLContext()));
+ }
+
+ };
+
+ public TestHttp2AsyncRedirect(final URIScheme scheme) {
+ super(scheme);
+ }
+
+ @Override
+ protected CloseableHttpAsyncClient createClient() {
+ return clientBuilder.build();
+ }
+
+ @Override
+ public HttpHost start() throws Exception {
+ return super.start(null, H2Config.DEFAULT);
+ }
+
+}
\ 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/TestHttp2ClientAuthentication.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp2ClientAuthentication.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp2ClientAuthentication.java
new file mode 100644
index 0000000..5cb1d80
--- /dev/null
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp2ClientAuthentication.java
@@ -0,0 +1,97 @@
+/*
+ * ====================================================================
+ * 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 org.apache.hc.client5.http.AuthenticationStrategy;
+import org.apache.hc.client5.http.auth.AuthSchemeProvider;
+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.Http2AsyncClientBuilder;
+import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
+import org.apache.hc.client5.http.ssl.H2TlsStrategy;
+import org.apache.hc.client5.testing.SSLTestContexts;
+import org.apache.hc.core5.http.HttpVersion;
+import org.apache.hc.core5.http.URIScheme;
+import org.apache.hc.core5.http.config.Lookup;
+import org.junit.Rule;
+import org.junit.rules.ExternalResource;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+@RunWith(Parameterized.class)
+public class TestHttp2ClientAuthentication extends AbstractHttpAsyncClientAuthentication<CloseableHttpAsyncClient> {
+
+ @Parameterized.Parameters(name = "HTTP/2 {0}")
+ public static Collection<Object[]> protocols() {
+ return Arrays.asList(new Object[][]{
+ {URIScheme.HTTP},
+ {URIScheme.HTTPS},
+ });
+ }
+
+ protected Http2AsyncClientBuilder clientBuilder;
+ protected PoolingAsyncClientConnectionManager connManager;
+
+ @Rule
+ public ExternalResource clientResource = new ExternalResource() {
+
+ @Override
+ protected void before() throws Throwable {
+ clientBuilder = Http2AsyncClientBuilder.create()
+ .setDefaultRequestConfig(RequestConfig.custom()
+ .setSocketTimeout(TIMEOUT)
+ .setConnectTimeout(TIMEOUT)
+ .setConnectionRequestTimeout(TIMEOUT)
+ .build())
+ .setTlsStrategy(new H2TlsStrategy(SSLTestContexts.createClientSSLContext()));
+ }
+
+ };
+
+ public TestHttp2ClientAuthentication(final URIScheme scheme) {
+ super(scheme, HttpVersion.HTTP_2);
+ }
+
+ @Override
+ void setDefaultAuthSchemeRegistry(final Lookup<AuthSchemeProvider> authSchemeRegistry) {
+ clientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
+ }
+
+ @Override
+ void setTargetAuthenticationStrategy(final AuthenticationStrategy targetAuthStrategy) {
+ clientBuilder.setTargetAuthenticationStrategy(targetAuthStrategy);
+ }
+
+ @Override
+ protected CloseableHttpAsyncClient createClient() throws Exception {
+ return clientBuilder.build();
+ }
+
+}
\ 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/TestHttpAsync.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttpAsync.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttpAsync.java
deleted file mode 100644
index 5f32a6f..0000000
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttpAsync.java
+++ /dev/null
@@ -1,252 +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.LinkedList;
-import java.util.Queue;
-import java.util.Random;
-import java.util.concurrent.Future;
-
-import org.apache.hc.client5.http.async.methods.AsyncRequestBuilder;
-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.impl.async.HttpAsyncClients;
-import org.apache.hc.client5.http.protocol.HttpClientContext;
-import org.apache.hc.core5.http.ContentType;
-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.HttpResponse;
-import org.apache.hc.core5.http.Message;
-import org.apache.hc.core5.http.URIScheme;
-import org.apache.hc.core5.http.nio.BasicResponseConsumer;
-import org.apache.hc.core5.http.nio.entity.BasicAsyncEntityConsumer;
-import org.hamcrest.CoreMatchers;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-
-@RunWith(Parameterized.class)
-public class TestHttpAsync extends IntegrationTestBase {
-
- @Parameterized.Parameters(name = "{0}")
- public static Collection<Object[]> protocols() {
- return Arrays.asList(new Object[][]{
- { URIScheme.HTTP },
- { URIScheme.HTTPS },
- });
- }
-
- public TestHttpAsync(final URIScheme scheme) {
- super(scheme);
- }
-
- @Test
- public void testSequenctialGetRequests() throws Exception {
- final HttpHost target = start();
- for (int i = 0; i < 3; i++) {
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/random/2048"), 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 testSequenctialHeadRequests() throws Exception {
- final HttpHost target = start();
- for (int i = 0; i < 3; i++) {
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.head(target, "/random/2048"), 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.nullValue());
- }
- }
-
- @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 testSequenctialPostRequests() throws Exception {
- final HttpHost target = start();
- for (int i = 0; i < 3; i++) {
- final byte[] b1 = new byte[1024];
- final Random rnd = new Random(System.currentTimeMillis());
- rnd.nextBytes(b1);
- final Future<Message<HttpResponse, byte[]>> future = httpclient.execute(
- AsyncRequestBuilder.post(target, "/echo/")
- .setEntity(b1, ContentType.APPLICATION_OCTET_STREAM)
- .build(),
- new BasicResponseConsumer<>(new BasicAsyncEntityConsumer()), HttpClientContext.create(), null);
- final Message<HttpResponse, byte[]> responseMessage = future.get();
- Assert.assertThat(responseMessage, CoreMatchers.notNullValue());
- final HttpResponse response = responseMessage.getHead();
- Assert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
- final byte[] b2 = responseMessage.getBody();
- Assert.assertThat(b1, CoreMatchers.equalTo(b2));
- }
- }
-
- @Test
- public void testConcurrentPostsOverMultipleConnections() throws Exception {
- final HttpHost target = start();
- final byte[] b1 = new byte[1024];
- final Random rnd = new Random(System.currentTimeMillis());
- rnd.nextBytes(b1);
-
- final int reqCount = 20;
-
- connManager.setDefaultMaxPerRoute(reqCount);
- connManager.setMaxTotal(100);
-
- final Queue<Future<Message<HttpResponse, byte[]>>> queue = new LinkedList<>();
- for (int i = 0; i < reqCount; i++) {
- final Future<Message<HttpResponse, byte[]>> future = httpclient.execute(
- AsyncRequestBuilder.post(target, "/echo/")
- .setEntity(b1, ContentType.APPLICATION_OCTET_STREAM)
- .build(),
- new BasicResponseConsumer<>(new BasicAsyncEntityConsumer()), HttpClientContext.create(), null);
- queue.add(future);
- }
-
- while (!queue.isEmpty()) {
- final Future<Message<HttpResponse, byte[]>> future = queue.remove();
- final Message<HttpResponse, byte[]> responseMessage = future.get();
- Assert.assertThat(responseMessage, CoreMatchers.notNullValue());
- final HttpResponse response = responseMessage.getHead();
- Assert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
- final byte[] b2 = responseMessage.getBody();
- Assert.assertThat(b1, CoreMatchers.equalTo(b2));
- }
- }
-
- @Test
- public void testConcurrentPostsOverSingleConnection() throws Exception {
- final HttpHost target = start();
- final byte[] b1 = new byte[1024];
- final Random rnd = new Random(System.currentTimeMillis());
- rnd.nextBytes(b1);
-
- final int reqCount = 20;
-
- connManager.setDefaultMaxPerRoute(1);
- connManager.setMaxTotal(100);
-
- final Queue<Future<Message<HttpResponse, byte[]>>> queue = new LinkedList<>();
- for (int i = 0; i < reqCount; i++) {
- final Future<Message<HttpResponse, byte[]>> future = httpclient.execute(
- AsyncRequestBuilder.post(target, "/echo/")
- .setEntity(b1, ContentType.APPLICATION_OCTET_STREAM)
- .build(),
- new BasicResponseConsumer<>(new BasicAsyncEntityConsumer()), HttpClientContext.create(), null);
- queue.add(future);
- }
-
- while (!queue.isEmpty()) {
- final Future<Message<HttpResponse, byte[]>> future = queue.remove();
- final Message<HttpResponse, byte[]> responseMessage = future.get();
- Assert.assertThat(responseMessage, CoreMatchers.notNullValue());
- final HttpResponse response = responseMessage.getHead();
- Assert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
- final byte[] b2 = responseMessage.getBody();
- Assert.assertThat(b1, CoreMatchers.equalTo(b2));
- }
- }
-
- @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
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/6228a736/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttpAsyncMinimal.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttpAsyncMinimal.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttpAsyncMinimal.java
index b7b1ef5..6173711 100644
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttpAsyncMinimal.java
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttpAsyncMinimal.java
@@ -26,7 +26,6 @@
*/
package org.apache.hc.client5.testing.async;
-import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
@@ -36,8 +35,6 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.hc.client5.http.async.methods.AsyncRequestBuilder;
-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.HttpAsyncClients;
import org.apache.hc.client5.http.impl.async.MinimalHttpAsyncClient;
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
@@ -45,7 +42,6 @@ import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBu
import org.apache.hc.client5.http.protocol.HttpClientContext;
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.ContentType;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpResponse;
@@ -54,31 +50,21 @@ import org.apache.hc.core5.http.Message;
import org.apache.hc.core5.http.URIScheme;
import org.apache.hc.core5.http.config.H1Config;
import org.apache.hc.core5.http.nio.AsyncClientEndpoint;
-import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
import org.apache.hc.core5.http.nio.BasicResponseConsumer;
import org.apache.hc.core5.http.nio.entity.BasicAsyncEntityConsumer;
import org.apache.hc.core5.http2.HttpVersionPolicy;
import org.apache.hc.core5.http2.config.H2Config;
-import org.apache.hc.core5.io.ShutdownType;
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.apache.hc.core5.util.Timeout;
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 TestHttpAsyncMinimal {
+public class TestHttpAsyncMinimal extends AbstractHttpAsyncFundamentalsTest<MinimalHttpAsyncClient> {
- public static final Timeout TIMEOUT = Timeout.ofSeconds(30);
-
- @Parameterized.Parameters(name = "{0} {1}")
+ @Parameterized.Parameters(name = "Minimal {0} {1}")
public static Collection<Object[]> protocols() {
return Arrays.asList(new Object[][]{
{ HttpVersion.HTTP_1_1, URIScheme.HTTP },
@@ -89,158 +75,40 @@ public class TestHttpAsyncMinimal {
}
protected final HttpVersion version;
- protected final URIScheme scheme;
public TestHttpAsyncMinimal(final HttpVersion version, final URIScheme scheme) {
+ super(scheme);
this.version = version;
- this.scheme = scheme;
}
- protected Http2TestServer server;
- protected MinimalHttpAsyncClient httpclient;
-
- @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 clientResource = new ExternalResource() {
-
- @Override
- protected void before() throws Throwable {
- final PoolingAsyncClientConnectionManager connectionManager = PoolingAsyncClientConnectionManagerBuilder.create()
- .setTlsStrategy(new H2TlsStrategy(SSLTestContexts.createClientSSLContext()))
- .build();
- final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
- .setSoTimeout(TIMEOUT)
- .build();
- if (version.greaterEquals(HttpVersion.HTTP_2)) {
- httpclient = HttpAsyncClients.createMinimal(
- HttpVersionPolicy.FORCE_HTTP_2, H2Config.DEFAULT, H1Config.DEFAULT, ioReactorConfig, connectionManager);
- } else {
- httpclient = HttpAsyncClients.createMinimal(
- HttpVersionPolicy.FORCE_HTTP_1, H2Config.DEFAULT, H1Config.DEFAULT, ioReactorConfig, connectionManager);
- }
- }
-
- @Override
- protected void after() {
- if (httpclient != null) {
- httpclient.shutdown(ShutdownType.GRACEFUL);
- httpclient = null;
- }
- }
-
- };
-
- public HttpHost start() throws Exception {
+ @Override
+ protected MinimalHttpAsyncClient createClient() throws Exception {
+ final PoolingAsyncClientConnectionManager connectionManager = PoolingAsyncClientConnectionManagerBuilder.create()
+ .setTlsStrategy(new H2TlsStrategy(SSLTestContexts.createClientSSLContext()))
+ .build();
+ final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
+ .setSoTimeout(TIMEOUT)
+ .build();
if (version.greaterEquals(HttpVersion.HTTP_2)) {
- server.start(H2Config.DEFAULT);
+ return HttpAsyncClients.createMinimal(
+ HttpVersionPolicy.FORCE_HTTP_2, H2Config.DEFAULT, H1Config.DEFAULT, ioReactorConfig, connectionManager);
} else {
- server.start(H1Config.DEFAULT);
+ return HttpAsyncClients.createMinimal(
+ HttpVersionPolicy.FORCE_HTTP_1, H2Config.DEFAULT, H1Config.DEFAULT, ioReactorConfig, connectionManager);
}
- final Future<ListenerEndpoint> endpointFuture = server.listen(new InetSocketAddress(0));
- httpclient.start();
- final ListenerEndpoint endpoint = endpointFuture.get();
- final InetSocketAddress address = (InetSocketAddress) endpoint.getAddress();
- return new HttpHost("localhost", address.getPort(), scheme.name());
}
- @Test
- public void testSequenctialGetRequests() throws Exception {
- final HttpHost target = start();
- for (int i = 0; i < 3; i++) {
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.get(target, "/random/2048"), 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 testSequenctialHeadRequests() throws Exception {
- final HttpHost target = start();
- for (int i = 0; i < 3; i++) {
- final Future<SimpleHttpResponse> future = httpclient.execute(
- SimpleHttpRequest.head(target, "/random/2048"), 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.nullValue());
- }
- }
-
- @Test
- public void testConcurrentPostsOverMultipleConnections() throws Exception {
- final HttpHost target = start();
- final byte[] b1 = new byte[1024];
- final Random rnd = new Random(System.currentTimeMillis());
- rnd.nextBytes(b1);
-
- final int reqCount = 20;
-
- final Queue<Future<Message<HttpResponse, byte[]>>> queue = new LinkedList<>();
- for (int i = 0; i < reqCount; i++) {
- final Future<Message<HttpResponse, byte[]>> future = httpclient.execute(
- AsyncRequestBuilder.post(target, "/echo/")
- .setEntity(b1, ContentType.APPLICATION_OCTET_STREAM)
- .build(),
- new BasicResponseConsumer<>(new BasicAsyncEntityConsumer()), HttpClientContext.create(), null);
- queue.add(future);
- }
-
- while (!queue.isEmpty()) {
- final Future<Message<HttpResponse, byte[]>> future = queue.remove();
- final Message<HttpResponse, byte[]> responseMessage = future.get();
- Assert.assertThat(responseMessage, CoreMatchers.notNullValue());
- final HttpResponse response = responseMessage.getHead();
- Assert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
- final byte[] b2 = responseMessage.getBody();
- Assert.assertThat(b1, CoreMatchers.equalTo(b2));
+ @Override
+ public HttpHost start() throws Exception {
+ if (version.greaterEquals(HttpVersion.HTTP_2)) {
+ return super.start(null, H2Config.DEFAULT);
+ } else {
+ return super.start(null, H1Config.DEFAULT);
}
}
@Test
- public void testConcurrentPostsOverSingleConnection() throws Exception {
+ public void testConcurrentPostRequestsSameEndpoint() throws Exception {
final HttpHost target = start();
final byte[] b1 = new byte[1024];
final Random rnd = new Random(System.currentTimeMillis());
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/6228a736/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncExecRuntimeImpl.java
----------------------------------------------------------------------
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncExecRuntimeImpl.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncExecRuntimeImpl.java
deleted file mode 100644
index 88d6bb3..0000000
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncExecRuntimeImpl.java
+++ /dev/null
@@ -1,276 +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.http.impl.async;
-
-import java.io.IOException;
-import java.io.InterruptedIOException;
-import java.util.concurrent.atomic.AtomicReference;
-
-import org.apache.hc.client5.http.HttpRoute;
-import org.apache.hc.client5.http.async.AsyncExecRuntime;
-import org.apache.hc.client5.http.config.RequestConfig;
-import org.apache.hc.client5.http.impl.ConnPoolSupport;
-import org.apache.hc.client5.http.nio.AsyncClientConnectionManager;
-import org.apache.hc.client5.http.nio.AsyncConnectionEndpoint;
-import org.apache.hc.client5.http.protocol.HttpClientContext;
-import org.apache.hc.core5.concurrent.FutureCallback;
-import org.apache.hc.core5.http.nio.AsyncClientExchangeHandler;
-import org.apache.hc.core5.http2.HttpVersionPolicy;
-import org.apache.hc.core5.reactor.ConnectionInitiator;
-import org.apache.hc.core5.util.TimeValue;
-import org.apache.logging.log4j.Logger;
-
-class AsyncExecRuntimeImpl implements AsyncExecRuntime {
-
- private final Logger log;
- private final AsyncClientConnectionManager manager;
- private final ConnectionInitiator connectionInitiator;
- private final HttpVersionPolicy versionPolicy;
- private final AtomicReference<AsyncConnectionEndpoint> endpointRef;
- private volatile boolean reusable;
- private volatile Object state;
- private volatile TimeValue validDuration;
-
- AsyncExecRuntimeImpl(
- final Logger log,
- final AsyncClientConnectionManager manager,
- final ConnectionInitiator connectionInitiator,
- final HttpVersionPolicy versionPolicy) {
- super();
- this.log = log;
- this.manager = manager;
- this.connectionInitiator = connectionInitiator;
- this.versionPolicy = versionPolicy;
- this.endpointRef = new AtomicReference<>(null);
- this.validDuration = TimeValue.NEG_ONE_MILLISECONDS;
- }
-
- @Override
- public boolean isConnectionAcquired() {
- return endpointRef.get() != null;
- }
-
- @Override
- public void acquireConnection(
- final HttpRoute route,
- final Object object,
- final HttpClientContext context,
- final FutureCallback<AsyncExecRuntime> callback) {
- if (endpointRef.get() == null) {
- state = object;
- final RequestConfig requestConfig = context.getRequestConfig();
- manager.lease(route, object, requestConfig.getConnectionRequestTimeout(), new FutureCallback<AsyncConnectionEndpoint>() {
-
- @Override
- public void completed(final AsyncConnectionEndpoint connectionEndpoint) {
- endpointRef.set(connectionEndpoint);
- reusable = connectionEndpoint.isConnected();
- callback.completed(AsyncExecRuntimeImpl.this);
- }
-
- @Override
- public void failed(final Exception ex) {
- callback.failed(ex);
- }
-
- @Override
- public void cancelled() {
- callback.cancelled();
- }
- });
- } else {
- callback.completed(this);
- }
- }
-
- private void discardEndpoint(final AsyncConnectionEndpoint endpoint) {
- try {
- endpoint.shutdown();
- if (log.isDebugEnabled()) {
- log.debug(ConnPoolSupport.getId(endpoint) + ": discarding endpoint");
- }
- } catch (final IOException ex) {
- if (log.isDebugEnabled()) {
- log.debug(ConnPoolSupport.getId(endpoint) + ": " + ex.getMessage(), ex);
- }
- } finally {
- manager.release(endpoint, null, TimeValue.ZERO_MILLISECONDS);
- }
- }
-
- @Override
- public void releaseConnection() {
- final AsyncConnectionEndpoint endpoint = endpointRef.getAndSet(null);
- if (endpoint != null) {
- if (reusable) {
- if (log.isDebugEnabled()) {
- log.debug(ConnPoolSupport.getId(endpoint) + ": releasing valid endpoint");
- }
- manager.release(endpoint, state, validDuration);
- } else {
- discardEndpoint(endpoint);
- }
- }
- }
-
- @Override
- public void discardConnection() {
- final AsyncConnectionEndpoint endpoint = endpointRef.getAndSet(null);
- if (endpoint != null) {
- discardEndpoint(endpoint);
- }
- }
-
- @Override
- public boolean validateConnection() {
- if (reusable) {
- final AsyncConnectionEndpoint endpoint = endpointRef.get();
- return endpoint != null && endpoint.isConnected();
- } else {
- final AsyncConnectionEndpoint endpoint = endpointRef.getAndSet(null);
- if (endpoint != null) {
- discardEndpoint(endpoint);
- }
- }
- return false;
- }
-
- AsyncConnectionEndpoint ensureValid() {
- final AsyncConnectionEndpoint endpoint = endpointRef.get();
- if (endpoint == null) {
- throw new IllegalStateException("Endpoint not acquired / already released");
- }
- return endpoint;
- }
-
- @Override
- public boolean isConnected() {
- final AsyncConnectionEndpoint endpoint = endpointRef.get();
- return endpoint != null && endpoint.isConnected();
- }
-
- @Override
- public void connect(
- final HttpClientContext context,
- final FutureCallback<AsyncExecRuntime> callback) {
- final AsyncConnectionEndpoint endpoint = ensureValid();
- if (endpoint.isConnected()) {
- callback.completed(this);
- } else {
- final RequestConfig requestConfig = context.getRequestConfig();
- manager.connect(
- endpoint,
- connectionInitiator,
- requestConfig.getConnectTimeout(),
- versionPolicy,
- context,
- new FutureCallback<AsyncConnectionEndpoint>() {
-
- @Override
- public void completed(final AsyncConnectionEndpoint endpoint) {
- final TimeValue socketTimeout = requestConfig.getSocketTimeout();
- if (TimeValue.isPositive(socketTimeout)) {
- endpoint.setSocketTimeout(socketTimeout.toMillisIntBound());
- }
- callback.completed(AsyncExecRuntimeImpl.this);
- }
-
- @Override
- public void failed(final Exception ex) {
- callback.failed(ex);
- }
-
- @Override
- public void cancelled() {
- callback.cancelled();
- }
-
- });
- }
-
- }
-
- @Override
- public void upgradeTls(final HttpClientContext context) {
- final AsyncConnectionEndpoint endpoint = ensureValid();
- manager.upgrade(endpoint, versionPolicy, context);
- }
-
- @Override
- public void execute(final AsyncClientExchangeHandler exchangeHandler, final HttpClientContext context) {
- final AsyncConnectionEndpoint endpoint = ensureValid();
- if (endpoint.isConnected()) {
- if (log.isDebugEnabled()) {
- log.debug(ConnPoolSupport.getId(endpoint) + ": executing " + ConnPoolSupport.getId(exchangeHandler));
- }
- endpoint.execute(exchangeHandler, context);
- } else {
- connect(context, new FutureCallback<AsyncExecRuntime>() {
-
- @Override
- public void completed(final AsyncExecRuntime runtime) {
- if (log.isDebugEnabled()) {
- log.debug(ConnPoolSupport.getId(endpoint) + ": executing " + ConnPoolSupport.getId(exchangeHandler));
- }
- try {
- endpoint.execute(exchangeHandler, context);
- } catch (final RuntimeException ex) {
- failed(ex);
- }
- }
-
- @Override
- public void failed(final Exception ex) {
- exchangeHandler.failed(ex);
- }
-
- @Override
- public void cancelled() {
- exchangeHandler.failed(new InterruptedIOException());
- }
-
- });
- }
-
- }
-
- @Override
- public void markConnectionReusable(final Object newState, final TimeValue newValidDuration) {
- reusable = true;
- state = newState;
- validDuration = newValidDuration;
- }
-
- @Override
- public void markConnectionNonReusable() {
- reusable = false;
- state = null;
- validDuration = null;
- }
-
-}