use of org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer in project httpcomponents-core by apache.
the class H2ViaHttp1ProxyExecutionExample method main.
public static void main(final String[] args) throws Exception {
// Create and start requester
final H2Config h2Config = H2Config.custom().setPushEnabled(false).build();
final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap().setH2Config(h2Config).setVersionPolicy(HttpVersionPolicy.NEGOTIATE).setStreamListener(new Http1StreamListener() {
@Override
public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
}
@Override
public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
}
@Override
public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
if (keepAlive) {
System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
} else {
System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
}
}
}).setStreamListener(new H2StreamListener() {
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
for (int i = 0; i < headers.size(); i++) {
System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
}
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
for (int i = 0; i < headers.size(); i++) {
System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
}
}
@Override
public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
}
@Override
public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
}
@Override
public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
}
@Override
public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
}
}).create();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("HTTP requester shutting down");
requester.close(CloseMode.GRACEFUL);
}));
requester.start();
final HttpHost proxy = new HttpHost("localhost", 8888);
final HttpHost target = new HttpHost("https", "nghttp2.org");
final ComplexFuture<AsyncClientEndpoint> tunnelFuture = new ComplexFuture<>(null);
tunnelFuture.setDependency(requester.connect(proxy, Timeout.ofSeconds(30), null, new FutureContribution<AsyncClientEndpoint>(tunnelFuture) {
@Override
public void completed(final AsyncClientEndpoint endpoint) {
if (endpoint instanceof TlsUpgradeCapable) {
final HttpRequest connect = new BasicHttpRequest(Method.CONNECT, proxy, target.toHostString());
endpoint.execute(new BasicRequestProducer(connect, null), new BasicResponseConsumer<>(new DiscardingEntityConsumer<>()), new FutureContribution<Message<HttpResponse, Void>>(tunnelFuture) {
@Override
public void completed(final Message<HttpResponse, Void> message) {
final HttpResponse response = message.getHead();
if (response.getCode() == HttpStatus.SC_OK) {
((TlsUpgradeCapable) endpoint).tlsUpgrade(target, new FutureContribution<ProtocolIOSession>(tunnelFuture) {
@Override
public void completed(final ProtocolIOSession protocolSession) {
System.out.println("Tunnel to " + target + " via " + proxy + " established");
tunnelFuture.completed(endpoint);
}
});
} else {
tunnelFuture.failed(new HttpException("Tunnel refused: " + new StatusLine(response)));
}
}
});
} else {
tunnelFuture.failed(new IllegalStateException("TLS upgrade not supported"));
}
}
}));
final String[] requestUris = new String[] { "/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers" };
final AsyncClientEndpoint endpoint = tunnelFuture.get(1, TimeUnit.MINUTES);
try {
final CountDownLatch latch = new CountDownLatch(requestUris.length);
for (final String requestUri : requestUris) {
endpoint.execute(new BasicRequestProducer(Method.GET, target, requestUri), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() {
@Override
public void completed(final Message<HttpResponse, String> message) {
final HttpResponse response = message.getHead();
final String body = message.getBody();
System.out.println(requestUri + "->" + response.getCode());
System.out.println(body);
latch.countDown();
}
@Override
public void failed(final Exception ex) {
System.out.println(requestUri + "->" + ex);
latch.countDown();
}
@Override
public void cancelled() {
System.out.println(requestUri + " cancelled");
latch.countDown();
}
});
}
latch.await();
} finally {
endpoint.releaseAndDiscard();
}
System.out.println("Shutting down I/O reactor");
requester.initiateShutdown();
}
use of org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer in project httpcomponents-core by apache.
the class H2IntegrationTest method testExcessOfConcurrentStreams.
@Test
public void testExcessOfConcurrentStreams() throws Exception {
server.register("/", () -> new MultiLineResponseHandler("0123456789abcdef", 2000));
final InetSocketAddress serverEndpoint = server.start(H2Config.custom().setMaxConcurrentStreams(20).build());
client.start(H2Config.custom().setMaxConcurrentStreams(20).build());
final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
final ClientSessionEndpoint streamEndpoint = connectFuture.get();
final Queue<Future<Message<HttpResponse, Void>>> queue = new LinkedList<>();
for (int i = 0; i < 2000; i++) {
final HttpRequest request1 = new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/"));
final Future<Message<HttpResponse, Void>> future = streamEndpoint.execute(new BasicRequestProducer(request1, null), new BasicResponseConsumer<>(new DiscardingEntityConsumer<>()), null);
queue.add(future);
}
while (!queue.isEmpty()) {
final Future<Message<HttpResponse, Void>> future = queue.remove();
final Message<HttpResponse, Void> result = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
Assertions.assertNotNull(result);
final HttpResponse response = result.getHead();
Assertions.assertNotNull(response);
Assertions.assertEquals(200, response.getCode());
}
}
use of org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer in project httpcomponents-core by apache.
the class H2IntegrationTest method testPushRefused.
@Test
public void testPushRefused() throws Exception {
final BlockingQueue<Exception> pushResultQueue = new LinkedBlockingDeque<>();
final InetSocketAddress serverEndpoint = server.start();
server.register("/hello", new Supplier<AsyncServerExchangeHandler>() {
@Override
public AsyncServerExchangeHandler get() {
return new MessageExchangeHandler<Void>(new DiscardingEntityConsumer<>()) {
@Override
protected void handle(final Message<HttpRequest, Void> request, final AsyncServerRequestHandler.ResponseTrigger responseTrigger, final HttpContext context) throws IOException, HttpException {
responseTrigger.pushPromise(new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/stuff")), context, new BasicPushProducer(AsyncEntityProducers.create("Pushing all sorts of stuff")) {
@Override
public void failed(final Exception cause) {
pushResultQueue.add(cause);
super.failed(cause);
}
});
responseTrigger.pushPromise(new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/more-stuff")), context, new BasicPushProducer(new MultiLineEntityProducer("Pushing lots of stuff", 500)) {
@Override
public void failed(final Exception cause) {
pushResultQueue.add(cause);
super.failed(cause);
}
});
responseTrigger.submitResponse(new BasicResponseProducer(HttpStatus.SC_OK, AsyncEntityProducers.create("Hi there")), context);
}
};
}
});
client.start(H2Config.custom().setPushEnabled(true).build());
final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
final ClientSessionEndpoint streamEndpoint = connectFuture.get();
final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(Method.GET, createRequestURI(serverEndpoint, "/hello")), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
final Message<HttpResponse, String> result1 = future1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
Assertions.assertNotNull(result1);
final HttpResponse response1 = result1.getHead();
final String entity1 = result1.getBody();
Assertions.assertNotNull(response1);
Assertions.assertEquals(200, response1.getCode());
Assertions.assertEquals("Hi there", entity1);
final Object result2 = pushResultQueue.poll(5, TimeUnit.SECONDS);
Assertions.assertNotNull(result2);
Assertions.assertTrue(result2 instanceof H2StreamResetException);
Assertions.assertEquals(H2Error.REFUSED_STREAM.getCode(), ((H2StreamResetException) result2).getCode());
final Object result3 = pushResultQueue.poll(5, TimeUnit.SECONDS);
Assertions.assertNotNull(result3);
Assertions.assertTrue(result3 instanceof H2StreamResetException);
Assertions.assertEquals(H2Error.REFUSED_STREAM.getCode(), ((H2StreamResetException) result3).getCode());
}
use of org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer in project httpcomponents-core by apache.
the class BenchmarkToolTest method setup.
public void setup(final HttpVersionPolicy versionPolicy) throws Exception {
server = H2ServerBootstrap.bootstrap().register("/", new AsyncServerRequestHandler<Message<HttpRequest, Void>>() {
@Override
public AsyncRequestConsumer<Message<HttpRequest, Void>> prepare(final HttpRequest request, final EntityDetails entityDetails, final HttpContext context) throws HttpException {
return new BasicRequestConsumer<>(entityDetails != null ? new DiscardingEntityConsumer<>() : null);
}
@Override
public void handle(final Message<HttpRequest, Void> requestObject, final ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException {
responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_OK).setEntity("0123456789ABCDEF").build(), context);
}
}).setVersionPolicy(versionPolicy).create();
server.start();
final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), URIScheme.HTTP);
final ListenerEndpoint listener = future.get();
address = (InetSocketAddress) listener.getAddress();
}
use of org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer in project httpcomponents-core by apache.
the class H2CompatibilityTest method executeH2.
void executeH2(final HttpHost target) throws Exception {
{
System.out.println("*** HTTP/2 simple request execution ***");
final Future<AsyncClientEndpoint> connectFuture = client.connect(target, TIMEOUT, HttpVersionPolicy.FORCE_HTTP_2, null);
try {
final AsyncClientEndpoint endpoint = connectFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
final CountDownLatch countDownLatch = new CountDownLatch(1);
final HttpRequest httpget = new BasicHttpRequest(Method.GET, target, "/status.html");
endpoint.execute(new BasicRequestProducer(httpget, null), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() {
@Override
public void completed(final Message<HttpResponse, String> responseMessage) {
final HttpResponse response = responseMessage.getHead();
final int code = response.getCode();
if (code == HttpStatus.SC_OK) {
logResult(TestResult.OK, target, httpget, response, Objects.toString(response.getFirstHeader("server")));
} else {
logResult(TestResult.NOK, target, httpget, response, "(status " + code + ")");
}
countDownLatch.countDown();
}
@Override
public void failed(final Exception ex) {
logResult(TestResult.NOK, target, httpget, null, "(" + ex.getMessage() + ")");
countDownLatch.countDown();
}
@Override
public void cancelled() {
logResult(TestResult.NOK, target, httpget, null, "(cancelled)");
countDownLatch.countDown();
}
});
if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
logResult(TestResult.NOK, target, null, null, "(single request execution failed to complete in time)");
}
} catch (final ExecutionException ex) {
final Throwable cause = ex.getCause();
logResult(TestResult.NOK, target, null, null, "(" + cause.getMessage() + ")");
} catch (final TimeoutException ex) {
logResult(TestResult.NOK, target, null, null, "(time out)");
}
}
{
System.out.println("*** HTTP/2 multiplexed request execution ***");
final Future<AsyncClientEndpoint> connectFuture = client.connect(target, TIMEOUT, HttpVersionPolicy.FORCE_HTTP_2, null);
try {
final AsyncClientEndpoint endpoint = connectFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
final int reqCount = 20;
final CountDownLatch countDownLatch = new CountDownLatch(reqCount);
for (int i = 0; i < reqCount; i++) {
final HttpRequest httpget = new BasicHttpRequest(Method.GET, target, "/status.html");
endpoint.execute(new BasicRequestProducer(httpget, null), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() {
@Override
public void completed(final Message<HttpResponse, String> responseMessage) {
final HttpResponse response = responseMessage.getHead();
final int code = response.getCode();
if (code == HttpStatus.SC_OK) {
logResult(TestResult.OK, target, httpget, response, "multiplexed / " + response.getFirstHeader("server"));
} else {
logResult(TestResult.NOK, target, httpget, response, "(status " + code + ")");
}
countDownLatch.countDown();
}
@Override
public void failed(final Exception ex) {
logResult(TestResult.NOK, target, httpget, null, "(" + ex.getMessage() + ")");
countDownLatch.countDown();
}
@Override
public void cancelled() {
logResult(TestResult.NOK, target, httpget, null, "(cancelled)");
countDownLatch.countDown();
}
});
}
if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
logResult(TestResult.NOK, target, null, null, "(multiplexed request execution failed to complete in time)");
}
} catch (final ExecutionException ex) {
final Throwable cause = ex.getCause();
logResult(TestResult.NOK, target, null, null, "(" + cause.getMessage() + ")");
} catch (final TimeoutException ex) {
logResult(TestResult.NOK, target, null, null, "(time out)");
}
}
{
System.out.println("*** HTTP/2 request execution with push ***");
final Future<AsyncClientEndpoint> connectFuture = client.connect(target, TIMEOUT, HttpVersionPolicy.FORCE_HTTP_2, null);
try {
final AsyncClientEndpoint endpoint = connectFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
final CountDownLatch countDownLatch = new CountDownLatch(5);
final HttpRequest httpget = new BasicHttpRequest(Method.GET, target, "/index.html");
final Future<Message<HttpResponse, String>> future = endpoint.execute(new BasicRequestProducer(httpget, null), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), (request, context) -> new AbstractAsyncPushHandler<Message<HttpResponse, Void>>(new BasicResponseConsumer<>(new DiscardingEntityConsumer<>())) {
@Override
protected void handleResponse(final HttpRequest promise, final Message<HttpResponse, Void> responseMessage) throws IOException, HttpException {
final HttpResponse response = responseMessage.getHead();
logResult(TestResult.OK, target, promise, response, "pushed / " + response.getFirstHeader("server"));
countDownLatch.countDown();
}
@Override
protected void handleError(final HttpRequest promise, final Exception cause) {
logResult(TestResult.NOK, target, promise, null, "(" + cause.getMessage() + ")");
countDownLatch.countDown();
}
}, null, null);
final Message<HttpResponse, String> message = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
final HttpResponse response = message.getHead();
final int code = response.getCode();
if (code == HttpStatus.SC_OK) {
logResult(TestResult.OK, target, httpget, response, Objects.toString(response.getFirstHeader("server")));
if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
logResult(TestResult.NOK, target, null, null, "Push messages not received");
}
} else {
logResult(TestResult.NOK, target, httpget, response, "(status " + code + ")");
}
} catch (final ExecutionException ex) {
final Throwable cause = ex.getCause();
logResult(TestResult.NOK, target, null, null, "(" + cause.getMessage() + ")");
} catch (final TimeoutException ex) {
logResult(TestResult.NOK, target, null, null, "(time out)");
}
}
}
Aggregations