use of org.apache.hc.core5.http2.config.H2Config in project httpcomponents-core by apache.
the class H2RequestExecutionExample 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.FORCE_HTTP_2).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 target = new HttpHost("nghttp2.org");
final String[] requestUris = new String[] { "/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers" };
final CountDownLatch latch = new CountDownLatch(requestUris.length);
for (final String requestUri : requestUris) {
final Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofSeconds(5));
final AsyncClientEndpoint clientEndpoint = future.get();
clientEndpoint.execute(AsyncRequestBuilder.get().setHttpHost(target).setPath(requestUri).build(), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() {
@Override
public void completed(final Message<HttpResponse, String> message) {
clientEndpoint.releaseAndReuse();
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) {
clientEndpoint.releaseAndDiscard();
System.out.println(requestUri + "->" + ex);
latch.countDown();
}
@Override
public void cancelled() {
clientEndpoint.releaseAndDiscard();
System.out.println(requestUri + " cancelled");
latch.countDown();
}
});
}
latch.await();
System.out.println("Shutting down I/O reactor");
requester.initiateShutdown();
}
use of org.apache.hc.core5.http2.config.H2Config 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.http2.config.H2Config in project httpcomponents-core by apache.
the class H2TestServer method start.
public InetSocketAddress start(final HttpProcessor httpProcessor, final Decorator<AsyncServerExchangeHandler> exchangeHandlerDecorator, final H2Config h2Config) throws Exception {
start(new InternalServerProtocolNegotiationStarter(httpProcessor != null ? httpProcessor : H2Processors.server(), new DefaultAsyncResponseExchangeHandlerFactory(registry, exchangeHandlerDecorator != null ? exchangeHandlerDecorator : BasicAsyncServerExpectationDecorator::new), HttpVersionPolicy.FORCE_HTTP_2, h2Config, Http1Config.DEFAULT, CharCodingConfig.DEFAULT, sslContext, sslSessionInitializer, sslSessionVerifier));
final Future<ListenerEndpoint> future = listen(new InetSocketAddress(0));
final ListenerEndpoint listener = future.get();
return (InetSocketAddress) listener.getAddress();
}
use of org.apache.hc.core5.http2.config.H2Config in project httpcomponents-core by apache.
the class H2RequesterBootstrap method create.
public H2AsyncRequester create() {
final ManagedConnPool<HttpHost, IOSession> connPool;
switch(poolConcurrencyPolicy != null ? poolConcurrencyPolicy : PoolConcurrencyPolicy.STRICT) {
case LAX:
connPool = new LaxConnPool<>(defaultMaxPerRoute > 0 ? defaultMaxPerRoute : 20, timeToLive, poolReusePolicy, new DefaultDisposalCallback<>(), connPoolListener);
break;
case STRICT:
default:
connPool = new StrictConnPool<>(defaultMaxPerRoute > 0 ? defaultMaxPerRoute : 20, maxTotal > 0 ? maxTotal : 50, timeToLive, poolReusePolicy, new DefaultDisposalCallback<>(), connPoolListener);
break;
}
final RequestHandlerRegistry<Supplier<AsyncPushConsumer>> registry = new RequestHandlerRegistry<>(uriPatternType);
for (final HandlerEntry<Supplier<AsyncPushConsumer>> entry : pushConsumerList) {
registry.register(entry.hostname, entry.uriPattern, entry.handler);
}
final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory = new ClientH2StreamMultiplexerFactory(httpProcessor != null ? httpProcessor : H2Processors.client(), new DefaultAsyncPushConsumerFactory(registry), h2Config != null ? h2Config : H2Config.DEFAULT, charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT, streamListener);
final TlsStrategy actualTlsStrategy = tlsStrategy != null ? tlsStrategy : new H2ClientTlsStrategy();
final ClientHttp1StreamDuplexerFactory http1StreamHandlerFactory = new ClientHttp1StreamDuplexerFactory(httpProcessor != null ? httpProcessor : HttpProcessors.client(), http1Config != null ? http1Config : Http1Config.DEFAULT, charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT, DefaultConnectionReuseStrategy.INSTANCE, new DefaultHttpResponseParserFactory(http1Config), DefaultHttpRequestWriterFactory.INSTANCE, DefaultContentLengthStrategy.INSTANCE, DefaultContentLengthStrategy.INSTANCE, http1StreamListener);
final IOEventHandlerFactory ioEventHandlerFactory = new ClientHttpProtocolNegotiationStarter(http1StreamHandlerFactory, http2StreamHandlerFactory, versionPolicy != null ? versionPolicy : HttpVersionPolicy.NEGOTIATE, actualTlsStrategy, handshakeTimeout);
return new H2AsyncRequester(versionPolicy != null ? versionPolicy : HttpVersionPolicy.NEGOTIATE, ioReactorConfig, ioEventHandlerFactory, ioSessionDecorator, exceptionCallback, sessionListener, connPool, actualTlsStrategy, handshakeTimeout);
}
use of org.apache.hc.core5.http2.config.H2Config in project httpcomponents-core by apache.
the class H2ServerBootstrap method create.
public HttpAsyncServer create() {
final String actualCanonicalHostName = canonicalHostName != null ? canonicalHostName : InetAddressUtils.getCanonicalLocalHostName();
final RequestHandlerRegistry<Supplier<AsyncServerExchangeHandler>> registry = new RequestHandlerRegistry<>(actualCanonicalHostName, () -> lookupRegistry != null ? lookupRegistry : UriPatternType.newMatcher(UriPatternType.URI_PATTERN));
for (final HandlerEntry<Supplier<AsyncServerExchangeHandler>> entry : handlerList) {
registry.register(entry.hostname, entry.uriPattern, entry.handler);
}
final HandlerFactory<AsyncServerExchangeHandler> handlerFactory;
if (!filters.isEmpty()) {
final NamedElementChain<AsyncFilterHandler> filterChainDefinition = new NamedElementChain<>();
filterChainDefinition.addLast(new TerminalAsyncServerFilter(new DefaultAsyncResponseExchangeHandlerFactory(registry)), StandardFilter.MAIN_HANDLER.name());
filterChainDefinition.addFirst(new AsyncServerExpectationFilter(), StandardFilter.EXPECT_CONTINUE.name());
for (final FilterEntry<AsyncFilterHandler> entry : filters) {
switch(entry.position) {
case AFTER:
filterChainDefinition.addAfter(entry.existing, entry.filterHandler, entry.name);
break;
case BEFORE:
filterChainDefinition.addBefore(entry.existing, entry.filterHandler, entry.name);
break;
case REPLACE:
filterChainDefinition.replace(entry.existing, entry.filterHandler);
break;
case FIRST:
filterChainDefinition.addFirst(entry.filterHandler, entry.name);
break;
case LAST:
// Don't add last, after TerminalAsyncServerFilter, as that does not delegate to the chain
// Instead, add the filter just before it, making it effectively the last filter
filterChainDefinition.addBefore(StandardFilter.MAIN_HANDLER.name(), entry.filterHandler, entry.name);
break;
}
}
NamedElementChain<AsyncFilterHandler>.Node current = filterChainDefinition.getLast();
AsyncServerFilterChainElement execChain = null;
while (current != null) {
execChain = new AsyncServerFilterChainElement(current.getValue(), execChain);
current = current.getPrevious();
}
handlerFactory = new AsyncServerFilterChainExchangeHandlerFactory(execChain, exceptionCallback);
} else {
handlerFactory = new DefaultAsyncResponseExchangeHandlerFactory(registry, handler -> new BasicAsyncServerExpectationDecorator(handler, exceptionCallback));
}
final ServerH2StreamMultiplexerFactory http2StreamHandlerFactory = new ServerH2StreamMultiplexerFactory(httpProcessor != null ? httpProcessor : H2Processors.server(), handlerFactory, h2Config != null ? h2Config : H2Config.DEFAULT, charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT, h2StreamListener);
final TlsStrategy actualTlsStrategy = tlsStrategy != null ? tlsStrategy : new H2ServerTlsStrategy();
final ServerHttp1StreamDuplexerFactory http1StreamHandlerFactory = new ServerHttp1StreamDuplexerFactory(httpProcessor != null ? httpProcessor : HttpProcessors.server(), handlerFactory, http1Config != null ? http1Config : Http1Config.DEFAULT, charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT, DefaultConnectionReuseStrategy.INSTANCE, DefaultHttpRequestParserFactory.INSTANCE, DefaultHttpResponseWriterFactory.INSTANCE, DefaultContentLengthStrategy.INSTANCE, DefaultContentLengthStrategy.INSTANCE, http1StreamListener);
final IOEventHandlerFactory ioEventHandlerFactory = new ServerHttpProtocolNegotiationStarter(http1StreamHandlerFactory, http2StreamHandlerFactory, versionPolicy != null ? versionPolicy : HttpVersionPolicy.NEGOTIATE, actualTlsStrategy, handshakeTimeout);
return new HttpAsyncServer(ioEventHandlerFactory, ioReactorConfig, ioSessionDecorator, exceptionCallback, sessionListener, actualCanonicalHostName);
}
Aggregations