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/09/01 18:15:28 UTC
[4/6] httpcomponents-client git commit: Upgraded HttpCore to version
5.0-alpha4
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/1eb22180/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientAuthentication.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientAuthentication.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientAuthentication.java
index 7521f11..0ab7b88 100644
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientAuthentication.java
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientAuthentication.java
@@ -30,6 +30,7 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
@@ -37,6 +38,7 @@ import java.util.concurrent.atomic.AtomicLong;
import org.apache.hc.client5.http.auth.AuthCache;
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;
@@ -45,17 +47,21 @@ import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.auth.BasicAuthCache;
import org.apache.hc.client5.http.impl.auth.BasicScheme;
+import org.apache.hc.client5.http.impl.auth.BasicSchemeFactory;
import org.apache.hc.client5.http.impl.protocol.DefaultAuthenticationStrategy;
import org.apache.hc.client5.http.impl.sync.BasicCredentialsProvider;
+import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse;
import org.apache.hc.client5.http.protocol.ClientProtocolException;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.client5.http.protocol.NonRepeatableRequestException;
import org.apache.hc.client5.http.sync.methods.HttpGet;
import org.apache.hc.client5.http.sync.methods.HttpPost;
import org.apache.hc.client5.http.sync.methods.HttpPut;
-import org.apache.hc.client5.testing.auth.BasicAuthTokenExtractor;
-import org.apache.hc.client5.testing.auth.RequestBasicAuth;
-import org.apache.hc.client5.testing.auth.ResponseBasicUnauthorized;
+import org.apache.hc.client5.testing.BasicTestAuthenticator;
+import org.apache.hc.client5.testing.auth.Authenticator;
+import org.apache.hc.client5.testing.classic.AuthenticatingDecorator;
+import org.apache.hc.client5.testing.classic.EchoHandler;
+import org.apache.hc.core5.function.Decorator;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.EndpointDetails;
@@ -65,18 +71,19 @@ 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.HttpStatus;
+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.io.HttpExpectationVerifier;
import org.apache.hc.core5.http.io.HttpRequestHandler;
+import org.apache.hc.core5.http.io.HttpServerRequestHandler;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.InputStreamEntity;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.http.protocol.HttpCoreContext;
-import org.apache.hc.core5.http.protocol.HttpProcessor;
+import org.apache.hc.core5.net.URIAuthority;
import org.junit.Assert;
-import org.junit.Before;
import org.junit.Test;
/**
@@ -84,56 +91,19 @@ import org.junit.Test;
*/
public class TestClientAuthentication extends LocalServerTestBase {
- @Before @Override
- public void setUp() throws Exception {
- super.setUp();
- final HttpProcessor httpproc = HttpProcessors.customServer(null)
- .add(new RequestBasicAuth())
- .add(new ResponseBasicUnauthorized()).build();
- this.serverBootstrap.setHttpProcessor(httpproc);
- }
-
- static class AuthHandler implements HttpRequestHandler {
+ public HttpHost start(final Authenticator authenticator) throws IOException {
+ return super.start(null, new Decorator<HttpServerRequestHandler>() {
- @Override
- public void handle(
- final ClassicHttpRequest request,
- final ClassicHttpResponse response,
- final HttpContext context) throws HttpException, IOException {
- final String creds = (String) context.getAttribute("creds");
- if (creds == null || !creds.equals("test:test")) {
- response.setCode(HttpStatus.SC_UNAUTHORIZED);
- } else {
- response.setCode(HttpStatus.SC_OK);
- final StringEntity entity = new StringEntity("success", StandardCharsets.US_ASCII);
- response.setEntity(entity);
+ @Override
+ public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
+ return new AuthenticatingDecorator(requestHandler, authenticator);
}
- }
+ });
}
- static class AuthExpectationVerifier implements HttpExpectationVerifier {
-
- private final BasicAuthTokenExtractor authTokenExtractor;
-
- public AuthExpectationVerifier() {
- super();
- this.authTokenExtractor = new BasicAuthTokenExtractor();
- }
-
- @Override
- public void verify(
- final ClassicHttpRequest request,
- final ClassicHttpResponse response,
- final HttpContext context) throws HttpException {
- final String creds = this.authTokenExtractor.extract(request);
- if (creds == null || !creds.equals("test:test")) {
- response.setCode(HttpStatus.SC_UNAUTHORIZED);
- } else {
- response.setCode(HttpStatus.SC_CONTINUE);
- }
- }
-
+ public HttpHost start() throws IOException {
+ return start(new BasicTestAuthenticator("test:test", "test realm"));
}
static class TestCredentialsProvider implements CredentialsProvider {
@@ -160,8 +130,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
@Test
public void testBasicAuthenticationNoCreds() throws Exception {
- this.serverBootstrap.registerHandler("*", new AuthHandler());
-
+ this.server.registerHandler("*", new EchoHandler());
final HttpHost target = start();
final HttpClientContext context = HttpClientContext.create();
@@ -181,8 +150,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
@Test
public void testBasicAuthenticationFailure() throws Exception {
- this.serverBootstrap.registerHandler("*", new AuthHandler());
-
+ this.server.registerHandler("*", new EchoHandler());
final HttpHost target = start();
final HttpClientContext context = HttpClientContext.create();
@@ -203,8 +171,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
@Test
public void testBasicAuthenticationSuccess() throws Exception {
- this.serverBootstrap.registerHandler("*", new AuthHandler());
-
+ this.server.registerHandler("*", new EchoHandler());
final HttpGet httpget = new HttpGet("/");
final HttpClientContext context = HttpClientContext.create();
final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
@@ -225,13 +192,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
@Test
public void testBasicAuthenticationSuccessOnNonRepeatablePutExpectContinue() throws Exception {
- final HttpProcessor httpproc = HttpProcessors.customServer(null)
- .add(new RequestBasicAuth())
- .add(new ResponseBasicUnauthorized()).build();
- this.serverBootstrap.setHttpProcessor(httpproc)
- .setExpectationVerifier(new AuthExpectationVerifier())
- .registerHandler("*", new AuthHandler());
-
+ this.server.registerHandler("*", new EchoHandler());
final HttpHost target = start();
final RequestConfig config = RequestConfig.custom()
@@ -256,11 +217,10 @@ public class TestClientAuthentication extends LocalServerTestBase {
@Test(expected=ClientProtocolException.class)
public void testBasicAuthenticationFailureOnNonRepeatablePutDontExpectContinue() throws Exception {
- this.serverBootstrap.registerHandler("*", new AuthHandler());
-
+ this.server.registerHandler("*", new EchoHandler());
final HttpHost target = start();
- final RequestConfig config = RequestConfig.custom().setExpectContinueEnabled(true).build();
+ final RequestConfig config = RequestConfig.custom().setExpectContinueEnabled(false).build();
final HttpPut httpput = new HttpPut("/");
httpput.setConfig(config);
httpput.setEntity(new InputStreamEntity(
@@ -286,8 +246,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
@Test
public void testBasicAuthenticationSuccessOnRepeatablePost() throws Exception {
- this.serverBootstrap.registerHandler("*", new AuthHandler());
-
+ this.server.registerHandler("*", new EchoHandler());
final HttpHost target = start();
final HttpPost httppost = new HttpPost("/");
@@ -310,8 +269,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
@Test(expected=ClientProtocolException.class)
public void testBasicAuthenticationFailureOnNonRepeatablePost() throws Exception {
- this.serverBootstrap.registerHandler("*", new AuthHandler());
-
+ this.server.registerHandler("*", new EchoHandler());
final HttpHost target = start();
final HttpPost httppost = new HttpPost("/");
@@ -362,8 +320,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
@Test
public void testBasicAuthenticationCredentialsCaching() throws Exception {
- this.serverBootstrap.registerHandler("*", new AuthHandler());
-
+ this.server.registerHandler("*", new EchoHandler());
final TestTargetAuthenticationStrategy authStrategy = new TestTargetAuthenticationStrategy();
this.clientBuilder.setTargetAuthenticationStrategy(authStrategy);
@@ -392,43 +349,34 @@ public class TestClientAuthentication extends LocalServerTestBase {
Assert.assertEquals(1, authStrategy.getCount());
}
- static class RealmAuthHandler implements HttpRequestHandler {
-
- final String realm;
- final String realmCreds;
-
- public RealmAuthHandler(final String realm, final String realmCreds) {
- this.realm = realm;
- this.realmCreds = realmCreds;
- }
-
- @Override
- public void handle(
- final ClassicHttpRequest request,
- final ClassicHttpResponse response,
- final HttpContext context) throws HttpException, IOException {
- final String givenCreds = (String) context.getAttribute("creds");
- if (givenCreds == null || !givenCreds.equals(this.realmCreds)) {
- response.setCode(HttpStatus.SC_UNAUTHORIZED);
- response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"" + this.realm + "\"");
- } else {
- response.setCode(HttpStatus.SC_OK);
- final StringEntity entity = new StringEntity("success", StandardCharsets.US_ASCII);
- response.setEntity(entity);
- }
- }
-
- }
-
@Test
public void testAuthenticationCredentialsCachingReauthenticationOnDifferentRealm() throws Exception {
- this.serverBootstrap.registerHandler("/this", new RealmAuthHandler("this realm", "test:this"));
- this.serverBootstrap.registerHandler("/that", new RealmAuthHandler("that realm", "test:that"));
+ this.server.registerHandler("*", new EchoHandler());
+ final HttpHost target = start(new Authenticator() {
+
+ @Override
+ public boolean authenticate(final URIAuthority authority, final String requestUri, final String credentials) {
+ if (requestUri.equals("/this")) {
+ return "test:this".equals(credentials);
+ } else if (requestUri.equals("/that")) {
+ return "test:that".equals(credentials);
+ } else {
+ return "test:test".equals(credentials);
+ }
+ }
- this.server = this.serverBootstrap.create();
- this.server.start();
+ @Override
+ public String getRealm(final URIAuthority authority, final String requestUri) {
+ if (requestUri.equals("/this")) {
+ return "this realm";
+ } else if (requestUri.equals("/that")) {
+ return "that realm";
+ } else {
+ return "test realm";
+ }
+ }
- final HttpHost target = new HttpHost("localhost", this.server.getLocalPort(), this.scheme.name());
+ });
final TestTargetAuthenticationStrategy authStrategy = new TestTargetAuthenticationStrategy();
final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
@@ -472,8 +420,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
@Test
public void testAuthenticationUserinfoInRequestSuccess() throws Exception {
- this.serverBootstrap.registerHandler("*", new AuthHandler());
-
+ this.server.registerHandler("*", new EchoHandler());
final HttpHost target = start();
final HttpGet httpget = new HttpGet("http://test:test@" + target.toHostString() + "/");
@@ -487,8 +434,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
@Test
public void testAuthenticationUserinfoInRequestFailure() throws Exception {
- this.serverBootstrap.registerHandler("*", new AuthHandler());
-
+ this.server.registerHandler("*", new EchoHandler());
final HttpHost target = start();
final HttpGet httpget = new HttpGet("http://test:all-wrong@" + target.toHostString() + "/");
@@ -500,36 +446,39 @@ public class TestClientAuthentication extends LocalServerTestBase {
EntityUtils.consume(entity);
}
- private static class RedirectHandler implements HttpRequestHandler {
-
- public RedirectHandler() {
- super();
- }
-
- @Override
- public void handle(
- final ClassicHttpRequest request,
- final ClassicHttpResponse response,
- final HttpContext context) throws HttpException, IOException {
- final EndpointDetails endpoint = (EndpointDetails) context.getAttribute(HttpCoreContext.CONNECTION_ENDPOINT);
- final InetSocketAddress socketAddress = (InetSocketAddress) endpoint.getLocalAddress();
- final String localhost = socketAddress.getHostName();
- final int port = socketAddress.getPort();
- response.setCode(HttpStatus.SC_MOVED_PERMANENTLY);
- response.addHeader(new BasicHeader("Location",
- "http://test:test@" + localhost + ":" + port + "/"));
- }
-
- }
-
@Test
public void testAuthenticationUserinfoInRedirectSuccess() throws Exception {
- this.serverBootstrap.registerHandler("*", new AuthHandler());
- this.serverBootstrap.registerHandler("/thatway", new RedirectHandler());
+ this.server.registerHandler("/*", new EchoHandler());
+ this.server.registerHandler("/thatway", new HttpRequestHandler() {
+
+ @Override
+ public void handle(
+ final ClassicHttpRequest request,
+ final ClassicHttpResponse response,
+ final HttpContext context) throws HttpException, IOException {
+ final EndpointDetails endpoint = (EndpointDetails) context.getAttribute(HttpCoreContext.CONNECTION_ENDPOINT);
+ final InetSocketAddress socketAddress = (InetSocketAddress) endpoint.getLocalAddress();
+ final String localhost = socketAddress.getHostName();
+ final int port = socketAddress.getPort();
+ response.setCode(HttpStatus.SC_MOVED_PERMANENTLY);
+ response.addHeader(new BasicHeader("Location", "http://test:test@" + localhost + ":" + port + "/secure"));
+ }
- final HttpHost target = start();
+ });
- final HttpGet httpget = new HttpGet("http://" + target.toHostString() + "/thatway");
+ final HttpHost target = start(new BasicTestAuthenticator("test:test", "test realm") {
+
+ @Override
+ public boolean authenticate(final URIAuthority authority, final String requestUri, final String credentials) {
+ if (requestUri.equals("/secure") || requestUri.startsWith("/secure/")) {
+ return super.authenticate(authority, requestUri, credentials);
+ } else {
+ return true;
+ }
+ }
+ });
+
+ final HttpGet httpget = new HttpGet("/thatway");
final HttpClientContext context = HttpClientContext.create();
final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context);
@@ -539,29 +488,19 @@ public class TestClientAuthentication extends LocalServerTestBase {
EntityUtils.consume(entity);
}
- static class CountingAuthHandler implements HttpRequestHandler {
+ static class CountingAuthenticator extends BasicTestAuthenticator {
private final AtomicLong count;
- public CountingAuthHandler() {
- super();
+ public CountingAuthenticator(final String userToken, final String realm) {
+ super(userToken, realm);
this.count = new AtomicLong();
}
@Override
- public void handle(
- final ClassicHttpRequest request,
- final ClassicHttpResponse response,
- final HttpContext context) throws HttpException, IOException {
+ public boolean authenticate(final URIAuthority authority, final String requestUri, final String credentials) {
this.count.incrementAndGet();
- final String creds = (String) context.getAttribute("creds");
- if (creds == null || !creds.equals("test:test")) {
- response.setCode(HttpStatus.SC_UNAUTHORIZED);
- } else {
- response.setCode(HttpStatus.SC_OK);
- final StringEntity entity = new StringEntity("success", StandardCharsets.US_ASCII);
- response.setEntity(entity);
- }
+ return super.authenticate(authority, requestUri, credentials);
}
public long getCount() {
@@ -572,10 +511,9 @@ public class TestClientAuthentication extends LocalServerTestBase {
@Test
public void testPreemptiveAuthentication() throws Exception {
- final CountingAuthHandler requestHandler = new CountingAuthHandler();
- this.serverBootstrap.registerHandler("*", requestHandler);
-
- final HttpHost target = start();
+ this.server.registerHandler("*", new EchoHandler());
+ final CountingAuthenticator countingAuthenticator = new CountingAuthenticator("test:test", "test realm");
+ final HttpHost target = start(countingAuthenticator);
final BasicScheme basicScheme = new BasicScheme();
basicScheme.initPreemptive(new UsernamePasswordCredentials("test", "test".toCharArray()));
@@ -591,15 +529,15 @@ public class TestClientAuthentication extends LocalServerTestBase {
Assert.assertNotNull(entity1);
EntityUtils.consume(entity1);
- Assert.assertEquals(1, requestHandler.getCount());
+ Assert.assertEquals(1, countingAuthenticator.getCount());
}
@Test
public void testPreemptiveAuthenticationFailure() throws Exception {
- final CountingAuthHandler requestHandler = new CountingAuthHandler();
- this.serverBootstrap.registerHandler("*", requestHandler);
+ this.server.registerHandler("*", new EchoHandler());
+ final CountingAuthenticator countingAuthenticator = new CountingAuthenticator("test:test", "test realm");
- final HttpHost target = start();
+ final HttpHost target = start(countingAuthenticator);
final HttpClientContext context = HttpClientContext.create();
final AuthCache authCache = new BasicAuthCache();
@@ -617,7 +555,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
Assert.assertNotNull(entity1);
EntityUtils.consume(entity1);
- Assert.assertEquals(1, requestHandler.getCount());
+ Assert.assertEquals(1, countingAuthenticator.getCount());
}
static class ProxyAuthHandler implements HttpRequestHandler {
@@ -641,9 +579,9 @@ public class TestClientAuthentication extends LocalServerTestBase {
@Test
public void testAuthenticationTargetAsProxy() throws Exception {
- this.serverBootstrap.registerHandler("*", new ProxyAuthHandler());
+ this.server.registerHandler("*", new ProxyAuthHandler());
- final HttpHost target = start();
+ final HttpHost target = super.start();
final HttpClientContext context = HttpClientContext.create();
final TestCredentialsProvider credsProvider = new TestCredentialsProvider(null);
@@ -657,31 +595,27 @@ public class TestClientAuthentication extends LocalServerTestBase {
EntityUtils.consume(entity);
}
- static class ClosingAuthHandler implements HttpRequestHandler {
+ @Test
+ public void testConnectionCloseAfterAuthenticationSuccess() throws Exception {
+ this.server.registerHandler("*", new EchoHandler());
- @Override
- public void handle(
- final ClassicHttpRequest request,
- final ClassicHttpResponse response,
- final HttpContext context) throws HttpException, IOException {
- final String creds = (String) context.getAttribute("creds");
- if (creds == null || !creds.equals("test:test")) {
- response.setCode(HttpStatus.SC_UNAUTHORIZED);
- } else {
- response.setCode(HttpStatus.SC_OK);
- final StringEntity entity = new StringEntity("success", StandardCharsets.US_ASCII);
- response.setEntity(entity);
- response.setHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE);
- }
- }
+ final HttpHost target = start(
+ HttpProcessors.server(),
+ new Decorator<HttpServerRequestHandler>() {
- }
+ @Override
+ public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
+ return new AuthenticatingDecorator(requestHandler, new BasicTestAuthenticator("test:test", "test realm")) {
- @Test
- public void testConnectionCloseAfterAuthenticationSuccess() throws Exception {
- this.serverBootstrap.registerHandler("*", new ClosingAuthHandler());
+ @Override
+ protected void customizeUnauthorizedResponse(final ClassicHttpResponse unauthorized) {
+ unauthorized.addHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE);
+ }
- final HttpHost target = start();
+ };
+ }
+
+ });
final HttpClientContext context = HttpClientContext.create();
final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
@@ -698,4 +632,128 @@ public class TestClientAuthentication extends LocalServerTestBase {
}
}
+ @Test
+ public void testReauthentication() throws Exception {
+ this.server.registerHandler("*", new EchoHandler());
+
+ final BasicSchemeFactory myBasicAuthSchemeFactory = new BasicSchemeFactory() {
+
+ @Override
+ public AuthScheme create(final HttpContext context) {
+ return new BasicScheme() {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public String getName() {
+ return "MyBasic";
+ }
+
+ };
+ }
+
+ };
+
+ final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
+ new UsernamePasswordCredentials("test", "test".toCharArray()));
+
+ final RequestConfig config = RequestConfig.custom()
+ .setTargetPreferredAuthSchemes(Arrays.asList("MyBasic"))
+ .build();
+ final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
+ .register("MyBasic", myBasicAuthSchemeFactory)
+ .build();
+ this.httpclient = this.clientBuilder
+ .setDefaultAuthSchemeRegistry(authSchemeRegistry)
+ .setDefaultCredentialsProvider(credsProvider)
+ .build();
+
+ 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<HttpServerRequestHandler>() {
+
+ @Override
+ public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
+ return new AuthenticatingDecorator(requestHandler, authenticator) {
+
+ @Override
+ protected void customizeUnauthorizedResponse(final ClassicHttpResponse unauthorized) {
+ unauthorized.removeHeaders(HttpHeaders.WWW_AUTHENTICATE);
+ unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, "MyBasic realm=\"test realm\"");
+ }
+
+ };
+ }
+
+ });
+
+ final HttpClientContext context = HttpClientContext.create();
+ for (int i = 0; i < 10; i++) {
+ final HttpGet httpget = new HttpGet("/");
+ httpget.setConfig(config);
+ try (final CloseableHttpResponse response = this.httpclient.execute(target, httpget, context)) {
+ final HttpEntity entity = response.getEntity();
+ Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
+ Assert.assertNotNull(entity);
+ EntityUtils.consume(entity);
+ }
+ }
+ }
+
+ @Test
+ public void testAuthenticationFallback() throws Exception {
+ this.server.registerHandler("*", new EchoHandler());
+
+ final HttpHost target = start(
+ HttpProcessors.server(),
+ new Decorator<HttpServerRequestHandler>() {
+
+ @Override
+ public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
+ return new AuthenticatingDecorator(requestHandler, new BasicTestAuthenticator("test:test", "test realm")) {
+
+ @Override
+ protected void customizeUnauthorizedResponse(final ClassicHttpResponse unauthorized) {
+ unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"test realm\" invalid");
+ }
+
+ };
+ }
+
+ });
+
+ final HttpClientContext context = HttpClientContext.create();
+ final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
+ new UsernamePasswordCredentials("test", "test".toCharArray()));
+ context.setCredentialsProvider(credsProvider);
+ final HttpGet httpget = new HttpGet("/");
+
+ final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context);
+ final HttpEntity entity = response.getEntity();
+ Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
+ Assert.assertNotNull(entity);
+ EntityUtils.consume(entity);
+ final AuthScope authscope = credsProvider.getAuthScope();
+ Assert.assertNotNull(authscope);
+ Assert.assertEquals("test realm", authscope.getRealm());
+ }
+
}
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/1eb22180/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientAuthenticationFakeNTLM.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientAuthenticationFakeNTLM.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientAuthenticationFakeNTLM.java
index b205fc4..64da94e 100644
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientAuthenticationFakeNTLM.java
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientAuthenticationFakeNTLM.java
@@ -66,7 +66,7 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase {
@Test
public void testNTLMAuthenticationFailure() throws Exception {
- this.serverBootstrap.registerHandler("*", new NtlmResponseHandler());
+ this.server.registerHandler("*", new NtlmResponseHandler());
final HttpHost target = start();
@@ -112,7 +112,7 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase {
@Test
public void testNTLMv1Type2Message() throws Exception {
- this.serverBootstrap.registerHandler("*", new NtlmType2MessageResponseHandler("TlRMTVNTUAACAA" +
+ this.server.registerHandler("*", new NtlmType2MessageResponseHandler("TlRMTVNTUAACAA" +
"AADAAMADgAAAAzggLiASNFZ4mrze8AAAAAAAAAAAAAAAAAAAAABgBwFwAAAA9T" +
"AGUAcgB2AGUAcgA="));
final HttpHost target = start();
@@ -136,7 +136,7 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase {
@Test
public void testNTLMv2Type2Message() throws Exception {
- this.serverBootstrap.registerHandler("*", new NtlmType2MessageResponseHandler("TlRMTVNTUAACAA" +
+ this.server.registerHandler("*", new NtlmType2MessageResponseHandler("TlRMTVNTUAACAA" +
"AADAAMADgAAAAzgoriASNFZ4mrze8AAAAAAAAAACQAJABEAAAABgBwFwAAAA9T" +
"AGUAcgB2AGUAcgACAAwARABvAG0AYQBpAG4AAQAMAFMAZQByAHYAZQByAAAAAAA="));
final HttpHost target = start();
@@ -179,7 +179,7 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase {
@Test
public void testNTLMType2MessageOnlyAuthenticationFailure() throws Exception {
- this.serverBootstrap.registerHandler("*", new NtlmType2MessageOnlyResponseHandler("TlRMTVNTUAACAA" +
+ this.server.registerHandler("*", new NtlmType2MessageOnlyResponseHandler("TlRMTVNTUAACAA" +
"AADAAMADgAAAAzggLiASNFZ4mrze8AAAAAAAAAAAAAAAAAAAAABgBwFwAAAA9T" +
"AGUAcgB2AGUAcgA="));
@@ -200,7 +200,7 @@ public class TestClientAuthenticationFakeNTLM extends LocalServerTestBase {
@Test
public void testNTLMType2NonUnicodeMessageOnlyAuthenticationFailure() throws Exception {
- this.serverBootstrap.registerHandler("*", new NtlmType2MessageOnlyResponseHandler("TlRMTVNTUAACAA" +
+ this.server.registerHandler("*", new NtlmType2MessageOnlyResponseHandler("TlRMTVNTUAACAA" +
"AABgAGADgAAAAyggLiASNFZ4mrze8AAAAAAAAAAAAAAAAAAAAABgBwFwAAAA9T" +
"ZXJ2ZXI="));
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/1eb22180/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientAuthenticationFallBack.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientAuthenticationFallBack.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientAuthenticationFallBack.java
deleted file mode 100644
index 3bbfe70..0000000
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientAuthenticationFallBack.java
+++ /dev/null
@@ -1,148 +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.sync;
-
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-
-import org.apache.hc.client5.http.auth.AuthScope;
-import org.apache.hc.client5.http.auth.Credentials;
-import org.apache.hc.client5.http.auth.CredentialsProvider;
-import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
-import org.apache.hc.client5.http.protocol.HttpClientContext;
-import org.apache.hc.client5.http.sync.methods.HttpGet;
-import org.apache.hc.client5.testing.auth.RequestBasicAuth;
-import org.apache.hc.core5.http.ClassicHttpRequest;
-import org.apache.hc.core5.http.ClassicHttpResponse;
-import org.apache.hc.core5.http.EntityDetails;
-import org.apache.hc.core5.http.HttpEntity;
-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.HttpResponseInterceptor;
-import org.apache.hc.core5.http.HttpStatus;
-import org.apache.hc.core5.http.impl.HttpProcessors;
-import org.apache.hc.core5.http.io.HttpRequestHandler;
-import org.apache.hc.core5.http.io.entity.EntityUtils;
-import org.apache.hc.core5.http.io.entity.StringEntity;
-import org.apache.hc.core5.http.protocol.HttpContext;
-import org.apache.hc.core5.http.protocol.HttpProcessor;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-public class TestClientAuthenticationFallBack extends LocalServerTestBase {
-
- public class ResponseBasicUnauthorized implements HttpResponseInterceptor {
-
- @Override
- public void process(
- final HttpResponse response,
- final EntityDetails entityDetails,
- final HttpContext context) throws HttpException, IOException {
- if (response.getCode() == HttpStatus.SC_UNAUTHORIZED) {
- response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Digest realm=\"test realm\" invalid");
- response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"test realm\"");
- }
- }
-
- }
-
- @Before @Override
- public void setUp() throws Exception {
- super.setUp();
- final HttpProcessor httpproc = HttpProcessors.customServer(null)
- .add(new RequestBasicAuth())
- .add(new ResponseBasicUnauthorized()).build();
- this.serverBootstrap.setHttpProcessor(httpproc);
- }
-
- static class AuthHandler implements HttpRequestHandler {
-
- @Override
- public void handle(
- final ClassicHttpRequest request,
- final ClassicHttpResponse response,
- final HttpContext context) throws HttpException, IOException {
- final String creds = (String) context.getAttribute("creds");
- if (creds == null || !creds.equals("test:test")) {
- response.setCode(HttpStatus.SC_UNAUTHORIZED);
- } else {
- response.setCode(HttpStatus.SC_OK);
- final StringEntity entity = new StringEntity("success", StandardCharsets.US_ASCII);
- response.setEntity(entity);
- }
- }
-
- }
-
- static class TestCredentialsProvider implements CredentialsProvider {
-
- private final Credentials creds;
- private AuthScope authscope;
-
- TestCredentialsProvider(final Credentials creds) {
- super();
- this.creds = creds;
- }
-
- @Override
- public Credentials getCredentials(final AuthScope authscope, final HttpContext context) {
- this.authscope = authscope;
- return this.creds;
- }
-
- public AuthScope getAuthScope() {
- return this.authscope;
- }
-
- }
-
- @Test
- public void testBasicAuthenticationSuccess() throws Exception {
- this.serverBootstrap.registerHandler("*", new AuthHandler());
-
- final HttpHost target = start();
-
- final HttpClientContext context = HttpClientContext.create();
- final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
- new UsernamePasswordCredentials("test", "test".toCharArray()));
- context.setCredentialsProvider(credsProvider);
- final HttpGet httpget = new HttpGet("/");
-
- final ClassicHttpResponse response = this.httpclient.execute(target, httpget, context);
- final HttpEntity entity = response.getEntity();
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- Assert.assertNotNull(entity);
- EntityUtils.consume(entity);
- final AuthScope authscope = credsProvider.getAuthScope();
- Assert.assertNotNull(authscope);
- Assert.assertEquals("test realm", authscope.getRealm());
- }
-
-}
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/1eb22180/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientReauthentication.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientReauthentication.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientReauthentication.java
deleted file mode 100644
index 9737ea9..0000000
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientReauthentication.java
+++ /dev/null
@@ -1,188 +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.sync;
-
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.util.Arrays;
-import java.util.concurrent.atomic.AtomicLong;
-
-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.Credentials;
-import org.apache.hc.client5.http.auth.CredentialsProvider;
-import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
-import org.apache.hc.client5.http.config.RequestConfig;
-import org.apache.hc.client5.http.impl.auth.BasicScheme;
-import org.apache.hc.client5.http.impl.auth.BasicSchemeFactory;
-import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse;
-import org.apache.hc.client5.http.protocol.HttpClientContext;
-import org.apache.hc.client5.http.sync.methods.HttpGet;
-import org.apache.hc.client5.testing.auth.RequestBasicAuth;
-import org.apache.hc.core5.http.ClassicHttpRequest;
-import org.apache.hc.core5.http.ClassicHttpResponse;
-import org.apache.hc.core5.http.EntityDetails;
-import org.apache.hc.core5.http.HttpEntity;
-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.HttpResponseInterceptor;
-import org.apache.hc.core5.http.HttpStatus;
-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.io.HttpRequestHandler;
-import org.apache.hc.core5.http.io.entity.EntityUtils;
-import org.apache.hc.core5.http.io.entity.StringEntity;
-import org.apache.hc.core5.http.protocol.HttpContext;
-import org.apache.hc.core5.http.protocol.HttpProcessor;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-public class TestClientReauthentication extends LocalServerTestBase {
-
- public class ResponseBasicUnauthorized implements HttpResponseInterceptor {
-
- @Override
- public void process(
- final HttpResponse response,
- final EntityDetails entityDetails,
- final HttpContext context) throws HttpException, IOException {
- if (response.getCode() == HttpStatus.SC_UNAUTHORIZED) {
- response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "MyBasic realm=\"test realm\"");
- }
- }
-
- }
-
- @Before @Override
- public void setUp() throws Exception {
- super.setUp();
- final HttpProcessor httpproc = HttpProcessors.customServer(null)
- .add(new RequestBasicAuth())
- .add(new ResponseBasicUnauthorized()).build();
- this.serverBootstrap.setHttpProcessor(httpproc);
- }
-
- static class AuthHandler implements HttpRequestHandler {
-
- private final AtomicLong count = new AtomicLong(0);
-
- @Override
- public void handle(
- final ClassicHttpRequest request,
- final ClassicHttpResponse response,
- final HttpContext context) throws HttpException, IOException {
- final String creds = (String) context.getAttribute("creds");
- if (creds == null || !creds.equals("test:test")) {
- response.setCode(HttpStatus.SC_UNAUTHORIZED);
- } else {
- // Make client re-authenticate on each fourth request
- if (this.count.incrementAndGet() % 4 == 0) {
- response.setCode(HttpStatus.SC_UNAUTHORIZED);
- } else {
- response.setCode(HttpStatus.SC_OK);
- final StringEntity entity = new StringEntity("success", StandardCharsets.US_ASCII);
- response.setEntity(entity);
- }
- }
- }
-
- }
-
- static class TestCredentialsProvider implements CredentialsProvider {
-
- private final Credentials creds;
- private AuthScope authscope;
-
- TestCredentialsProvider(final Credentials creds) {
- super();
- this.creds = creds;
- }
-
- @Override
- public Credentials getCredentials(final AuthScope authscope, final HttpContext context) {
- this.authscope = authscope;
- return this.creds;
- }
-
- }
-
- @Test
- public void testBasicAuthenticationSuccess() throws Exception {
- this.serverBootstrap.registerHandler("*", new AuthHandler());
-
- final BasicSchemeFactory myBasicAuthSchemeFactory = new BasicSchemeFactory() {
-
- @Override
- public AuthScheme create(final HttpContext context) {
- return new BasicScheme() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public String getName() {
- return "MyBasic";
- }
-
- };
- }
-
- };
-
- final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
- new UsernamePasswordCredentials("test", "test".toCharArray()));
-
- final RequestConfig config = RequestConfig.custom()
- .setTargetPreferredAuthSchemes(Arrays.asList("MyBasic"))
- .build();
- final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
- .register("MyBasic", myBasicAuthSchemeFactory)
- .build();
- this.httpclient = this.clientBuilder
- .setDefaultAuthSchemeRegistry(authSchemeRegistry)
- .setDefaultCredentialsProvider(credsProvider)
- .build();
-
- final HttpHost target = start();
-
- final HttpClientContext context = HttpClientContext.create();
- for (int i = 0; i < 10; i++) {
- final HttpGet httpget = new HttpGet("/");
- httpget.setConfig(config);
- try (final CloseableHttpResponse response = this.httpclient.execute(target, httpget, context)) {
- final HttpEntity entity = response.getEntity();
- Assert.assertEquals(HttpStatus.SC_OK, response.getCode());
- Assert.assertNotNull(entity);
- EntityUtils.consume(entity);
- }
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/1eb22180/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientRequestExecution.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientRequestExecution.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientRequestExecution.java
index 02741fd..c715248 100644
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientRequestExecution.java
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientRequestExecution.java
@@ -110,7 +110,7 @@ public class TestClientRequestExecution extends LocalServerTestBase {
@Test
public void testAutoGeneratedHeaders() throws Exception {
- this.serverBootstrap.registerHandler("*", new SimpleService());
+ this.server.registerHandler("*", new SimpleService());
final HttpRequestInterceptor interceptor = new HttpRequestInterceptor() {
@@ -163,7 +163,7 @@ public class TestClientRequestExecution extends LocalServerTestBase {
@Test(expected=ClientProtocolException.class)
public void testNonRepeatableEntity() throws Exception {
- this.serverBootstrap.registerHandler("*", new SimpleService());
+ this.server.registerHandler("*", new SimpleService());
final HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {
@@ -206,7 +206,7 @@ public class TestClientRequestExecution extends LocalServerTestBase {
@Test
public void testNonCompliantURI() throws Exception {
- this.serverBootstrap.registerHandler("*", new SimpleService());
+ this.server.registerHandler("*", new SimpleService());
final HttpHost target = start();
@@ -224,7 +224,7 @@ public class TestClientRequestExecution extends LocalServerTestBase {
@Test
public void testRelativeRequestURIWithFragment() throws Exception {
- this.serverBootstrap.registerHandler("*", new SimpleService());
+ this.server.registerHandler("*", new SimpleService());
final HttpHost target = start();
@@ -241,7 +241,7 @@ public class TestClientRequestExecution extends LocalServerTestBase {
@Test
public void testAbsoluteRequestURIWithFragment() throws Exception {
- this.serverBootstrap.registerHandler("*", new SimpleService());
+ this.server.registerHandler("*", new SimpleService());
final HttpHost target = start();
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/1eb22180/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestConnectionAutoRelease.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestConnectionAutoRelease.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestConnectionAutoRelease.java
deleted file mode 100644
index 17f25fa..0000000
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestConnectionAutoRelease.java
+++ /dev/null
@@ -1,229 +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.sync;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.net.Socket;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-
-import org.apache.hc.client5.http.HttpRoute;
-import org.apache.hc.client5.http.io.ConnectionEndpoint;
-import org.apache.hc.client5.http.io.LeaseRequest;
-import org.apache.hc.client5.http.sync.methods.HttpGet;
-import org.apache.hc.core5.function.Supplier;
-import org.apache.hc.core5.http.ClassicHttpResponse;
-import org.apache.hc.core5.http.Header;
-import org.apache.hc.core5.http.HttpEntity;
-import org.apache.hc.core5.http.HttpHost;
-import org.apache.hc.core5.http.config.CharCodingConfig;
-import org.apache.hc.core5.http.config.H1Config;
-import org.apache.hc.core5.http.impl.io.DefaultBHttpServerConnection;
-import org.apache.hc.core5.http.impl.io.DefaultBHttpServerConnectionFactory;
-import org.apache.hc.core5.http.io.SessionOutputBuffer;
-import org.apache.hc.core5.http.io.entity.EntityUtils;
-import org.apache.hc.core5.util.TimeValue;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class TestConnectionAutoRelease extends LocalServerTestBase {
-
- @Test
- public void testReleaseOnEntityConsumeContent() throws Exception {
- this.connManager.setDefaultMaxPerRoute(1);
- this.connManager.setMaxTotal(1);
-
- // Zero connections in the pool
- Assert.assertEquals(0, this.connManager.getTotalStats().getAvailable());
-
- final HttpHost target = start();
- // Get some random data
- final HttpGet httpget = new HttpGet("/random/20000");
- final ClassicHttpResponse response = this.httpclient.execute(target, httpget);
-
- final LeaseRequest connreq1 = this.connManager.lease(new HttpRoute(target), null);
- try {
- connreq1.get(250, TimeUnit.MILLISECONDS);
- Assert.fail("ConnectionPoolTimeoutException should have been thrown");
- } catch (final TimeoutException expected) {
- }
-
- final HttpEntity e = response.getEntity();
- Assert.assertNotNull(e);
- EntityUtils.consume(e);
-
- // Expect one connection in the pool
- Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable());
-
- // Make sure one connection is available
- final LeaseRequest connreq2 = this.connManager.lease(new HttpRoute(target), null);
- final ConnectionEndpoint endpoint = connreq2.get(250, TimeUnit.MILLISECONDS);
-
- this.connManager.release(endpoint, null, TimeValue.NEG_ONE_MILLISECONDS);
- }
-
- @Test
- public void testReleaseOnEntityWriteTo() throws Exception {
- this.connManager.setDefaultMaxPerRoute(1);
- this.connManager.setMaxTotal(1);
-
- // Zero connections in the pool
- Assert.assertEquals(0, this.connManager.getTotalStats().getAvailable());
-
- final HttpHost target = start();
- // Get some random data
- final HttpGet httpget = new HttpGet("/random/20000");
- final ClassicHttpResponse response = this.httpclient.execute(target, httpget);
-
- final LeaseRequest connreq1 = this.connManager.lease(new HttpRoute(target), null);
- try {
- connreq1.get(250, TimeUnit.MILLISECONDS);
- Assert.fail("ConnectionPoolTimeoutException should have been thrown");
- } catch (final TimeoutException expected) {
- }
-
- final HttpEntity e = response.getEntity();
- Assert.assertNotNull(e);
- final ByteArrayOutputStream outsteam = new ByteArrayOutputStream();
- e.writeTo(outsteam);
-
- // Expect one connection in the pool
- Assert.assertEquals(1, this.connManager.getTotalStats().getAvailable());
-
- // Make sure one connection is available
- final LeaseRequest connreq2 = this.connManager.lease(new HttpRoute(target), null);
- final ConnectionEndpoint endpoint = connreq2.get(250, TimeUnit.MILLISECONDS);
-
- this.connManager.release(endpoint, null, TimeValue.NEG_ONE_MILLISECONDS);
- }
-
- @Test
- public void testReleaseOnAbort() throws Exception {
- this.connManager.setDefaultMaxPerRoute(1);
- this.connManager.setMaxTotal(1);
-
- // Zero connections in the pool
- Assert.assertEquals(0, this.connManager.getTotalStats().getAvailable());
-
- final HttpHost target = start();
-
- // Get some random data
- final HttpGet httpget = new HttpGet("/random/20000");
- final ClassicHttpResponse response = this.httpclient.execute(target, httpget);
-
- final LeaseRequest connreq1 = this.connManager.lease(new HttpRoute(target), null);
- try {
- connreq1.get(250, TimeUnit.MILLISECONDS);
- Assert.fail("ConnectionPoolTimeoutException should have been thrown");
- } catch (final TimeoutException expected) {
- }
-
- final HttpEntity e = response.getEntity();
- Assert.assertNotNull(e);
- httpget.abort();
-
- // Expect zero connections in the pool
- Assert.assertEquals(0, this.connManager.getTotalStats().getAvailable());
-
- // Make sure one connection is available
- final LeaseRequest connreq2 = this.connManager.lease(new HttpRoute(target), null);
- final ConnectionEndpoint endpoint = connreq2.get(250, TimeUnit.MILLISECONDS);
-
- this.connManager.release(endpoint, null, TimeValue.NEG_ONE_MILLISECONDS);
- }
-
- @Test
- public void testReleaseOnIOException() throws Exception {
- serverBootstrap.setConnectionFactory(new DefaultBHttpServerConnectionFactory(null, H1Config.DEFAULT, CharCodingConfig.DEFAULT) {
-
- @Override
- public DefaultBHttpServerConnection createConnection(final Socket socket) throws IOException {
- final DefaultBHttpServerConnection conn = new DefaultBHttpServerConnection(null, H1Config.DEFAULT) {
-
- @Override
- protected OutputStream createContentOutputStream(
- final long len,
- final SessionOutputBuffer buffer,
- final OutputStream outputStream,
- final Supplier<List<? extends Header>> trailers) {
- try {
- buffer.flush(outputStream);
- outputStream.close();
- } catch (final IOException ignore) {
- }
- return super.createContentOutputStream(len, buffer, outputStream, trailers);
- }
- };
- conn.bind(socket);
- return conn;
- }
- });
-
- this.connManager.setDefaultMaxPerRoute(1);
- this.connManager.setMaxTotal(1);
-
- // Zero connections in the pool
- Assert.assertEquals(0, this.connManager.getTotalStats().getAvailable());
-
- final HttpHost target = start();
-
- // Get some random data
- final HttpGet httpget = new HttpGet("/random/1024");
- final ClassicHttpResponse response = this.httpclient.execute(target, httpget);
-
- final LeaseRequest connreq1 = this.connManager.lease(new HttpRoute(target), null);
- try {
- connreq1.get(250, TimeUnit.MILLISECONDS);
- Assert.fail("ConnectionPoolTimeoutException should have been thrown");
- } catch (final TimeoutException expected) {
- }
-
- final HttpEntity e = response.getEntity();
- Assert.assertNotNull(e);
- // Read the content
- try {
- EntityUtils.toByteArray(e);
- Assert.fail("IOException should have been thrown");
- } catch (final IOException expected) {
-
- }
-
- // Expect zero connections in the pool
- Assert.assertEquals(0, this.connManager.getTotalStats().getAvailable());
-
- // Make sure one connection is available
- final LeaseRequest connreq2 = this.connManager.lease(new HttpRoute(target), null);
- final ConnectionEndpoint endpoint = connreq2.get(250, TimeUnit.MILLISECONDS);
-
- this.connManager.release(endpoint, null, TimeValue.NEG_ONE_MILLISECONDS);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/1eb22180/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestConnectionReuse.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestConnectionReuse.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestConnectionReuse.java
index 9e1d625..b3f04fa 100644
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestConnectionReuse.java
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestConnectionReuse.java
@@ -32,7 +32,6 @@ import java.net.URI;
import org.apache.hc.client5.http.impl.sync.CloseableHttpClient;
import org.apache.hc.client5.http.sync.methods.HttpGet;
-import org.apache.hc.client5.testing.classic.RandomHandler;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.EntityDetails;
import org.apache.hc.core5.http.Header;
@@ -53,11 +52,6 @@ public class TestConnectionReuse extends LocalServerTestBase {
@Test
public void testReuseOfPersistentConnections() throws Exception {
- final HttpProcessor httpproc = HttpProcessors.customServer(null).build();
-
- this.serverBootstrap.setHttpProcessor(httpproc)
- .registerHandler("/random/*", new RandomHandler());
-
this.connManager.setMaxTotal(5);
this.connManager.setDefaultMaxPerRoute(5);
@@ -101,16 +95,13 @@ public class TestConnectionReuse extends LocalServerTestBase {
@Test
public void testReuseOfClosedConnections() throws Exception {
- final HttpProcessor httpproc = HttpProcessors.customServer(null)
- .add(new AlwaysCloseConn()).build();
-
- this.serverBootstrap.setHttpProcessor(httpproc)
- .registerHandler("/random/*", new RandomHandler());
-
this.connManager.setMaxTotal(5);
this.connManager.setDefaultMaxPerRoute(5);
- final HttpHost target = start();
+ final HttpProcessor httpproc = HttpProcessors.customServer(null)
+ .add(new AlwaysCloseConn())
+ .build();
+ final HttpHost target = start(httpproc, null);
final WorkerThread[] workers = new WorkerThread[10];
for (int i = 0; i < workers.length; i++) {
@@ -138,11 +129,6 @@ public class TestConnectionReuse extends LocalServerTestBase {
@Test
public void testReuseOfAbortedConnections() throws Exception {
- final HttpProcessor httpproc = HttpProcessors.customServer(null).build();
-
- this.serverBootstrap.setHttpProcessor(httpproc)
- .registerHandler("/random/*", new RandomHandler());
-
this.connManager.setMaxTotal(5);
this.connManager.setDefaultMaxPerRoute(5);
@@ -174,16 +160,13 @@ public class TestConnectionReuse extends LocalServerTestBase {
@Test
public void testKeepAliveHeaderRespected() throws Exception {
- final HttpProcessor httpproc = HttpProcessors.customServer(null)
- .add(new ResponseKeepAlive()).build();
-
- this.serverBootstrap.setHttpProcessor(httpproc)
- .registerHandler("/random/*", new RandomHandler());
-
this.connManager.setMaxTotal(1);
this.connManager.setDefaultMaxPerRoute(1);
- final HttpHost target = start();
+ final HttpProcessor httpproc = HttpProcessors.customServer(null)
+ .add(new ResponseKeepAlive())
+ .build();
+ final HttpHost target = start(httpproc, null);
ClassicHttpResponse response = this.httpclient.execute(target, new HttpGet("/random/2000"));
EntityUtils.consume(response.getEntity());
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/1eb22180/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestContentCodings.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestContentCodings.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestContentCodings.java
index 19f33c7..35b22bd 100644
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestContentCodings.java
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestContentCodings.java
@@ -41,7 +41,7 @@ import java.util.concurrent.Executors;
import java.util.zip.Deflater;
import java.util.zip.GZIPOutputStream;
-import org.apache.hc.client5.http.impl.sync.BasicResponseHandler;
+import org.apache.hc.client5.http.impl.sync.BasicHttpClientResponseHandler;
import org.apache.hc.client5.http.impl.sync.CloseableHttpClient;
import org.apache.hc.client5.http.sync.methods.HttpGet;
import org.apache.hc.core5.http.ClassicHttpRequest;
@@ -75,7 +75,7 @@ public class TestContentCodings extends LocalServerTestBase {
*/
@Test
public void testResponseWithNoContent() throws Exception {
- this.serverBootstrap.registerHandler("*", new HttpRequestHandler() {
+ this.server.registerHandler("*", new HttpRequestHandler() {
/**
* {@inheritDoc}
@@ -107,7 +107,7 @@ public class TestContentCodings extends LocalServerTestBase {
public void testDeflateSupportForServerReturningRfc1950Stream() throws Exception {
final String entityText = "Hello, this is some plain text coming back.";
- this.serverBootstrap.registerHandler("*", createDeflateEncodingRequestHandler(entityText, false));
+ this.server.registerHandler("*", createDeflateEncodingRequestHandler(entityText, false));
final HttpHost target = start();
@@ -127,7 +127,7 @@ public class TestContentCodings extends LocalServerTestBase {
public void testDeflateSupportForServerReturningRfc1951Stream() throws Exception {
final String entityText = "Hello, this is some plain text coming back.";
- this.serverBootstrap.registerHandler("*", createDeflateEncodingRequestHandler(entityText, true));
+ this.server.registerHandler("*", createDeflateEncodingRequestHandler(entityText, true));
final HttpHost target = start();
@@ -146,7 +146,7 @@ public class TestContentCodings extends LocalServerTestBase {
public void testGzipSupport() throws Exception {
final String entityText = "Hello, this is some plain text coming back.";
- this.serverBootstrap.registerHandler("*", createGzipEncodingRequestHandler(entityText));
+ this.server.registerHandler("*", createGzipEncodingRequestHandler(entityText));
final HttpHost target = start();
@@ -166,7 +166,7 @@ public class TestContentCodings extends LocalServerTestBase {
public void testThreadSafetyOfContentCodings() throws Exception {
final String entityText = "Hello, this is some plain text coming back.";
- this.serverBootstrap.registerHandler("*", createGzipEncodingRequestHandler(entityText));
+ this.server.registerHandler("*", createGzipEncodingRequestHandler(entityText));
/*
* Create a load of workers which will access the resource. Half will use the default
@@ -212,7 +212,7 @@ public class TestContentCodings extends LocalServerTestBase {
public void testHttpEntityWriteToForGzip() throws Exception {
final String entityText = "Hello, this is some plain text coming back.";
- this.serverBootstrap.registerHandler("*", createGzipEncodingRequestHandler(entityText));
+ this.server.registerHandler("*", createGzipEncodingRequestHandler(entityText));
final HttpHost target = start();
@@ -229,7 +229,7 @@ public class TestContentCodings extends LocalServerTestBase {
public void testHttpEntityWriteToForDeflate() throws Exception {
final String entityText = "Hello, this is some plain text coming back.";
- this.serverBootstrap.registerHandler("*", createDeflateEncodingRequestHandler(entityText, true));
+ this.server.registerHandler("*", createDeflateEncodingRequestHandler(entityText, true));
final HttpHost target = start();
@@ -246,12 +246,12 @@ public class TestContentCodings extends LocalServerTestBase {
public void gzipResponsesWorkWithBasicResponseHandler() throws Exception {
final String entityText = "Hello, this is some plain text coming back.";
- this.serverBootstrap.registerHandler("*", createGzipEncodingRequestHandler(entityText));
+ this.server.registerHandler("*", createGzipEncodingRequestHandler(entityText));
final HttpHost target = start();
final HttpGet request = new HttpGet("/some-resource");
- final String response = this.httpclient.execute(target, request, new BasicResponseHandler());
+ final String response = this.httpclient.execute(target, request, new BasicHttpClientResponseHandler());
Assert.assertEquals("The entity text is correctly transported", entityText, response);
}
@@ -259,12 +259,12 @@ public class TestContentCodings extends LocalServerTestBase {
public void deflateResponsesWorkWithBasicResponseHandler() throws Exception {
final String entityText = "Hello, this is some plain text coming back.";
- this.serverBootstrap.registerHandler("*", createDeflateEncodingRequestHandler(entityText, false));
+ this.server.registerHandler("*", createDeflateEncodingRequestHandler(entityText, false));
final HttpHost target = start();
final HttpGet request = new HttpGet("/some-resource");
- final String response = this.httpclient.execute(target, request, new BasicResponseHandler());
+ final String response = this.httpclient.execute(target, request, new BasicHttpClientResponseHandler());
Assert.assertEquals("The entity text is correctly transported", entityText, response);
}
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/1eb22180/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestCookieVirtualHost.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestCookieVirtualHost.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestCookieVirtualHost.java
index 47199d6..8adbd85 100644
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestCookieVirtualHost.java
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestCookieVirtualHost.java
@@ -55,7 +55,7 @@ public class TestCookieVirtualHost extends LocalServerTestBase {
@Test
public void testCookieMatchingWithVirtualHosts() throws Exception {
- this.serverBootstrap.registerHandler("*", new HttpRequestHandler() {
+ this.server.registerHandlerVirtual("app.mydomain.fr", "*", new HttpRequestHandler() {
@Override
public void handle(
final ClassicHttpRequest request,
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/1eb22180/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestMalformedServerResponse.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestMalformedServerResponse.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestMalformedServerResponse.java
index 6d353b2..e4fd3cb 100644
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestMalformedServerResponse.java
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestMalformedServerResponse.java
@@ -29,7 +29,9 @@ package org.apache.hc.client5.testing.sync;
import java.io.IOException;
import java.net.Socket;
+import org.apache.hc.client5.http.impl.sync.CloseableHttpClient;
import org.apache.hc.client5.http.impl.sync.CloseableHttpResponse;
+import org.apache.hc.client5.http.impl.sync.HttpClientBuilder;
import org.apache.hc.client5.http.sync.methods.HttpGet;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
@@ -37,6 +39,8 @@ import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.config.H1Config;
+import org.apache.hc.core5.http.impl.bootstrap.HttpServer;
+import org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap;
import org.apache.hc.core5.http.impl.io.DefaultBHttpServerConnection;
import org.apache.hc.core5.http.io.HttpConnectionFactory;
import org.apache.hc.core5.http.io.HttpRequestHandler;
@@ -46,7 +50,7 @@ import org.apache.hc.core5.http.protocol.HttpContext;
import org.junit.Assert;
import org.junit.Test;
-public class TestMalformedServerResponse extends LocalServerTestBase {
+public class TestMalformedServerResponse {
static class BrokenServerConnection extends DefaultBHttpServerConnection {
@@ -85,41 +89,46 @@ public class TestMalformedServerResponse extends LocalServerTestBase {
@Test
public void testNoContentResponseWithGarbage() throws Exception {
- this.serverBootstrap.setConnectionFactory(new BrokenServerConnectionFactory());
- this.serverBootstrap.registerHandler("/nostuff", new HttpRequestHandler() {
+ try (final HttpServer server = ServerBootstrap.bootstrap()
+ .setConnectionFactory(new BrokenServerConnectionFactory())
+ .register("/nostuff", new HttpRequestHandler() {
- @Override
- public void handle(
- final ClassicHttpRequest request,
- final ClassicHttpResponse response,
- final HttpContext context) throws HttpException, IOException {
- response.setCode(HttpStatus.SC_NO_CONTENT);
- }
-
- });
- this.serverBootstrap.registerHandler("/stuff", new HttpRequestHandler() {
+ @Override
+ public void handle(
+ final ClassicHttpRequest request,
+ final ClassicHttpResponse response,
+ final HttpContext context) throws HttpException, IOException {
+ response.setCode(HttpStatus.SC_NO_CONTENT);
+ }
- @Override
- public void handle(
- final ClassicHttpRequest request,
- final ClassicHttpResponse response,
- final HttpContext context) throws HttpException, IOException {
- response.setCode(HttpStatus.SC_OK);
- response.setEntity(new StringEntity("Some important stuff"));
- }
+ })
+ .register("/stuff", new HttpRequestHandler() {
- });
+ @Override
+ public void handle(
+ final ClassicHttpRequest request,
+ final ClassicHttpResponse response,
+ final HttpContext context) throws HttpException, IOException {
+ response.setCode(HttpStatus.SC_OK);
+ response.setEntity(new StringEntity("Some important stuff"));
+ }
- final HttpHost target = start();
- final HttpGet get1 = new HttpGet("/nostuff");
- try (CloseableHttpResponse response1 = this.httpclient.execute(target, get1)) {
- Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response1.getCode());
- EntityUtils.consume(response1.getEntity());
- }
- final HttpGet get2 = new HttpGet("/stuff");
- try (CloseableHttpResponse response2 = this.httpclient.execute(target, get2)) {
- Assert.assertEquals(HttpStatus.SC_OK, response2.getCode());
- EntityUtils.consume(response2.getEntity());
+ })
+ .create()) {
+ server.start();
+ final HttpHost target = new HttpHost("localhost", server.getLocalPort());
+ try (final CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
+ final HttpGet get1 = new HttpGet("/nostuff");
+ try (final CloseableHttpResponse response1 = httpclient.execute(target, get1)) {
+ Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response1.getCode());
+ EntityUtils.consume(response1.getEntity());
+ }
+ final HttpGet get2 = new HttpGet("/stuff");
+ try (final CloseableHttpResponse response2 = httpclient.execute(target, get2)) {
+ Assert.assertEquals(HttpStatus.SC_OK, response2.getCode());
+ EntityUtils.consume(response2.getEntity());
+ }
+ }
}
}
http://git-wip-us.apache.org/repos/asf/httpcomponents-client/blob/1eb22180/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestMinimalClientRequestExecution.java
----------------------------------------------------------------------
diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestMinimalClientRequestExecution.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestMinimalClientRequestExecution.java
index 1e315c4..61baafa 100644
--- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestMinimalClientRequestExecution.java
+++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestMinimalClientRequestExecution.java
@@ -72,7 +72,7 @@ public class TestMinimalClientRequestExecution extends LocalServerTestBase {
@Test
public void testNonCompliantURI() throws Exception {
- this.serverBootstrap.registerHandler("*", new SimpleService());
+ this.server.registerHandler("*", new SimpleService());
this.httpclient = HttpClients.createMinimal();
final HttpHost target = start();