use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-client by apache.
the class AbstractHttpAsyncClientAuthentication method testReauthentication.
@Test
public void testReauthentication() throws Exception {
server.register("*", AsyncEchoHandler::new);
final CredentialsProvider credsProvider = Mockito.mock(CredentialsProvider.class);
Mockito.when(credsProvider.getCredentials(Mockito.any(), Mockito.any())).thenReturn(new UsernamePasswordCredentials("test", "test".toCharArray()));
final Registry<AuthSchemeFactory> authSchemeRegistry = RegistryBuilder.<AuthSchemeFactory>create().register("MyBasic", context -> new BasicScheme() {
private static final long serialVersionUID = 1L;
@Override
public String getName() {
return "MyBasic";
}
}).build();
setDefaultAuthSchemeRegistry(authSchemeRegistry);
final Authenticator authenticator = new BasicTestAuthenticator("test:test", "test realm") {
private final AtomicLong count = new AtomicLong(0);
@Override
public boolean authenticate(final URIAuthority authority, final String requestUri, final String credentials) {
final boolean authenticated = super.authenticate(authority, requestUri, credentials);
if (authenticated) {
return this.count.incrementAndGet() % 4 != 0;
}
return false;
}
};
final HttpHost target = start(exchangeHandler -> new AuthenticatingAsyncDecorator(exchangeHandler, authenticator) {
@Override
protected void customizeUnauthorizedResponse(final HttpResponse unauthorized) {
unauthorized.removeHeaders(HttpHeaders.WWW_AUTHENTICATE);
unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, "MyBasic realm=\"test realm\"");
}
});
final RequestConfig config = RequestConfig.custom().setTargetPreferredAuthSchemes(Collections.singletonList("MyBasic")).build();
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
for (int i = 0; i < 10; i++) {
final SimpleHttpRequest request = SimpleRequestBuilder.get().setHttpHost(target).setPath("/").build();
request.setConfig(config);
final Future<SimpleHttpResponse> future = httpclient.execute(request, context, null);
final SimpleHttpResponse response = future.get();
Assertions.assertNotNull(response);
Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
}
}
use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-client by apache.
the class AbstractHttpAsyncClientAuthentication method testAuthenticationUserinfoInRequestFailure.
@Test
public void testAuthenticationUserinfoInRequestFailure() throws Exception {
server.register("*", AsyncEchoHandler::new);
final HttpHost target = start();
final HttpClientContext context = HttpClientContext.create();
final Future<SimpleHttpResponse> future = httpclient.execute(SimpleRequestBuilder.get().setScheme(target.getSchemeName()).setAuthority(new URIAuthority("test:test", target.getHostName(), target.getPort())).setPath("/").build(), context, null);
final ExecutionException exception = Assertions.assertThrows(ExecutionException.class, () -> future.get());
assertThat(exception.getCause(), CoreMatchers.instanceOf(ProtocolException.class));
}
use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-client by apache.
the class TestHttp1AsyncStatefulConnManagement method testRouteSpecificPoolRecylcing.
@Test
public void testRouteSpecificPoolRecylcing() throws Exception {
server.register("*", () -> new AbstractSimpleServerExchangeHandler() {
@Override
protected SimpleHttpResponse handle(final SimpleHttpRequest request, final HttpCoreContext context) throws HttpException {
final SimpleHttpResponse response = new SimpleHttpResponse(HttpStatus.SC_OK);
response.setBody("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 = (route, context) -> 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 SimpleHttpRequest request1 = SimpleRequestBuilder.get().setHttpHost(target).setPath("/").build();
final Future<SimpleHttpResponse> future1 = httpclient.execute(request1, context1, null);
final HttpResponse response1 = future1.get();
Assertions.assertNotNull(response1);
Assertions.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 SimpleHttpRequest request2 = SimpleRequestBuilder.get().setScheme(target.getSchemeName()).setAuthority(new URIAuthority("127.0.0.1", target.getPort())).setPath("/").build();
final Future<SimpleHttpResponse> future2 = httpclient.execute(request2, context2, null);
final HttpResponse response2 = future2.get();
Assertions.assertNotNull(response2);
Assertions.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 SimpleHttpRequest request3 = SimpleRequestBuilder.get().setHttpHost(target).setPath("/").build();
final Future<SimpleHttpResponse> future3 = httpclient.execute(request3, context3, null);
final HttpResponse response3 = future3.get();
Assertions.assertNotNull(response3);
Assertions.assertEquals(200, response3.getCode());
}
use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-client by apache.
the class AuthenticatingAsyncDecorator method handleRequest.
@Override
public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
final Header h = request.getFirstHeader(HttpHeaders.AUTHORIZATION);
final String challengeResponse = h != null ? authTokenExtractor.extract(h.getValue()) : null;
final URIAuthority authority = request.getAuthority();
final String requestUri = request.getRequestUri();
final boolean authenticated = authenticator.authenticate(authority, requestUri, challengeResponse);
final Header expect = request.getFirstHeader(HttpHeaders.EXPECT);
final boolean expectContinue = expect != null && "100-continue".equalsIgnoreCase(expect.getValue());
if (authenticated) {
if (expectContinue) {
responseChannel.sendInformation(new BasicClassicHttpResponse(HttpStatus.SC_CONTINUE), context);
}
exchangeHandler.handleRequest(request, entityDetails, responseChannel, context);
} else {
final HttpResponse unauthorized = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED);
final String realm = authenticator.getRealm(authority, requestUri);
unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, StandardAuthScheme.BASIC + " realm=\"" + realm + "\"");
customizeUnauthorizedResponse(unauthorized);
final AsyncResponseProducer responseProducer = new BasicResponseProducer(unauthorized, new BasicAsyncEntityProducer("Unauthorized", ContentType.TEXT_PLAIN));
responseProducerRef.set(responseProducer);
responseProducer.sendResponse(responseChannel, context);
}
}
use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-client by apache.
the class TestCachingExecChain method testUsesVirtualHostForCacheKey.
@Test
public void testUsesVirtualHostForCacheKey() throws Exception {
final ClassicHttpResponse response = HttpTestUtils.make200Response();
response.setHeader("Cache-Control", "max-age=3600");
Mockito.when(mockExecChain.proceed(Mockito.any(), Mockito.any())).thenReturn(response);
impl.execute(request, new ExecChain.Scope("test", route, request, mockExecRuntime, context), mockExecChain);
Mockito.verify(mockExecChain, Mockito.times(1)).proceed(Mockito.any(), Mockito.any());
request.setAuthority(new URIAuthority("bar.example.com"));
impl.execute(request, new ExecChain.Scope("test", route, request, mockExecRuntime, context), mockExecChain);
Mockito.verify(mockExecChain, Mockito.times(2)).proceed(Mockito.any(), Mockito.any());
impl.execute(request, new ExecChain.Scope("test", route, request, mockExecRuntime, context), mockExecChain);
Mockito.verify(mockExecChain, Mockito.times(2)).proceed(Mockito.any(), Mockito.any());
}
Aggregations