use of org.apache.hc.core5.http.impl.Http1StreamListener in project httpcomponents-core by apache.
the class AsyncFullDuplexClientExample method main.
public static void main(final String[] args) throws Exception {
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(5, TimeUnit.SECONDS).build();
// Create and start requester
// Disable 'Expect: Continue' handshake some servers cannot handle well
final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap().setIOReactorConfig(ioReactorConfig).setHttpProcessor(HttpProcessors.customClient(null).addLast((HttpRequestInterceptor) (request, entity, context) -> request.removeHeaders(HttpHeaders.EXPECT)).build()).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)");
}
}
}).create();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("HTTP requester shutting down");
requester.close(CloseMode.GRACEFUL);
}));
requester.start();
final URI requestUri = new URI("http://httpbin.org/post");
final AsyncRequestProducer requestProducer = AsyncRequestBuilder.post(requestUri).setEntity("stuff").build();
final BasicResponseConsumer<String> responseConsumer = new BasicResponseConsumer<>(new StringAsyncEntityConsumer());
final CountDownLatch latch = new CountDownLatch(1);
requester.execute(new AsyncClientExchangeHandler() {
@Override
public void releaseResources() {
requestProducer.releaseResources();
responseConsumer.releaseResources();
latch.countDown();
}
@Override
public void cancel() {
System.out.println(requestUri + " cancelled");
}
@Override
public void failed(final Exception cause) {
System.out.println(requestUri + "->" + cause);
}
@Override
public void produceRequest(final RequestChannel channel, final HttpContext httpContext) throws HttpException, IOException {
requestProducer.sendRequest(channel, httpContext);
}
@Override
public int available() {
return requestProducer.available();
}
@Override
public void produce(final DataStreamChannel channel) throws IOException {
requestProducer.produce(channel);
}
@Override
public void consumeInformation(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
System.out.println(requestUri + "->" + response.getCode());
}
@Override
public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext) throws HttpException, IOException {
System.out.println(requestUri + "->" + response.getCode());
responseConsumer.consumeResponse(response, entityDetails, httpContext, null);
}
@Override
public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
responseConsumer.updateCapacity(capacityChannel);
}
@Override
public void consume(final ByteBuffer src) throws IOException {
responseConsumer.consume(src);
}
@Override
public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
responseConsumer.streamEnd(trailers);
}
}, Timeout.ofSeconds(30), HttpCoreContext.create());
latch.await(1, TimeUnit.MINUTES);
System.out.println("Shutting down I/O reactor");
requester.initiateShutdown();
}
use of org.apache.hc.core5.http.impl.Http1StreamListener in project httpcomponents-core by apache.
the class AsyncReverseProxyExample method main.
public static void main(final String[] args) throws Exception {
if (args.length < 1) {
System.out.println("Usage: <hostname[:port]> [listener port] [--quiet]");
System.exit(1);
}
// Target host
final HttpHost targetHost = HttpHost.create(args[0]);
int port = 8080;
if (args.length > 1) {
port = Integer.parseInt(args[1]);
}
for (final String s : args) {
if ("--quiet".equalsIgnoreCase(s)) {
quiet = true;
break;
}
}
println("Reverse proxy to " + targetHost);
final IOReactorConfig config = IOReactorConfig.custom().setSoTimeout(1, TimeUnit.MINUTES).build();
final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap().setIOReactorConfig(config).setConnPoolListener(new ConnPoolListener<HttpHost>() {
@Override
public void onLease(final HttpHost route, final ConnPoolStats<HttpHost> connPoolStats) {
final StringBuilder buf = new StringBuilder();
buf.append("[proxy->origin] connection leased ").append(route);
println(buf.toString());
}
@Override
public void onRelease(final HttpHost route, final ConnPoolStats<HttpHost> connPoolStats) {
final StringBuilder buf = new StringBuilder();
buf.append("[proxy->origin] connection released ").append(route);
final PoolStats totals = connPoolStats.getTotalStats();
buf.append("; total kept alive: ").append(totals.getAvailable()).append("; ");
buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable());
buf.append(" of ").append(totals.getMax());
println(buf.toString());
}
}).setStreamListener(new Http1StreamListener() {
@Override
public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
// empty
}
@Override
public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
// empty
}
@Override
public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
println("[proxy<-origin] connection " + connection.getLocalAddress() + "->" + connection.getRemoteAddress() + (keepAlive ? " kept alive" : " cannot be kept alive"));
}
}).setMaxTotal(100).setDefaultMaxPerRoute(20).create();
final HttpAsyncServer server = AsyncServerBootstrap.bootstrap().setIOReactorConfig(config).setStreamListener(new Http1StreamListener() {
@Override
public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
// empty
}
@Override
public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
// empty
}
@Override
public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
println("[client<-proxy] connection " + connection.getLocalAddress() + "->" + connection.getRemoteAddress() + (keepAlive ? " kept alive" : " cannot be kept alive"));
}
}).register("*", () -> new IncomingExchangeHandler(targetHost, requester)).create();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
println("Reverse proxy shutting down");
server.close(CloseMode.GRACEFUL);
requester.close(CloseMode.GRACEFUL);
}));
requester.start();
server.start();
server.listen(new InetSocketAddress(port), URIScheme.HTTP);
println("Listening on port " + port);
server.awaitShutdown(TimeValue.MAX_VALUE);
}
use of org.apache.hc.core5.http.impl.Http1StreamListener in project httpcomponents-core by apache.
the class ClassicGetExecutionExample method main.
public static void main(final String[] args) throws Exception {
final HttpRequester httpRequester = RequesterBootstrap.bootstrap().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)");
}
}
}).setSocketConfig(SocketConfig.custom().setSoTimeout(5, TimeUnit.SECONDS).build()).create();
final HttpCoreContext coreContext = HttpCoreContext.create();
final HttpHost target = new HttpHost("httpbin.org");
final String[] requestUris = new String[] { "/", "/ip", "/user-agent", "/headers" };
for (int i = 0; i < requestUris.length; i++) {
final String requestUri = requestUris[i];
final ClassicHttpRequest request = ClassicRequestBuilder.get().setHttpHost(target).setPath(requestUri).build();
try (ClassicHttpResponse response = httpRequester.execute(target, request, Timeout.ofSeconds(5), coreContext)) {
System.out.println(requestUri + "->" + response.getCode());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
}
}
}
use of org.apache.hc.core5.http.impl.Http1StreamListener in project httpcomponents-core by apache.
the class AsyncFullDuplexServerExample method main.
public static void main(final String[] args) throws Exception {
int port = 8080;
if (args.length >= 1) {
port = Integer.parseInt(args[0]);
}
final IOReactorConfig config = IOReactorConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
final HttpAsyncServer server = AsyncServerBootstrap.bootstrap().setIOReactorConfig(config).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)");
}
}
}).register("/echo", () -> new AsyncServerExchangeHandler() {
ByteBuffer buffer = ByteBuffer.allocate(2048);
CapacityChannel inputCapacityChannel;
DataStreamChannel outputDataChannel;
boolean endStream;
private void ensureCapacity(final int chunk) {
if (buffer.remaining() < chunk) {
final ByteBuffer oldBuffer = buffer;
oldBuffer.flip();
buffer = ByteBuffer.allocate(oldBuffer.remaining() + (chunk > 2048 ? chunk : 2048));
buffer.put(oldBuffer);
}
}
@Override
public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK);
responseChannel.sendResponse(response, entityDetails, context);
}
@Override
public void consume(final ByteBuffer src) throws IOException {
if (buffer.position() == 0) {
if (outputDataChannel != null) {
outputDataChannel.write(src);
}
}
if (src.hasRemaining()) {
ensureCapacity(src.remaining());
buffer.put(src);
if (outputDataChannel != null) {
outputDataChannel.requestOutput();
}
}
}
@Override
public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
if (buffer.hasRemaining()) {
capacityChannel.update(buffer.remaining());
inputCapacityChannel = null;
} else {
inputCapacityChannel = capacityChannel;
}
}
@Override
public void streamEnd(final List<? extends Header> trailers) throws IOException {
endStream = true;
if (buffer.position() == 0) {
if (outputDataChannel != null) {
outputDataChannel.endStream();
}
} else {
if (outputDataChannel != null) {
outputDataChannel.requestOutput();
}
}
}
@Override
public int available() {
return buffer.position();
}
@Override
public void produce(final DataStreamChannel channel) throws IOException {
outputDataChannel = channel;
buffer.flip();
if (buffer.hasRemaining()) {
channel.write(buffer);
}
buffer.compact();
if (buffer.position() == 0 && endStream) {
channel.endStream();
}
final CapacityChannel capacityChannel = inputCapacityChannel;
if (capacityChannel != null && buffer.hasRemaining()) {
capacityChannel.update(buffer.remaining());
}
}
@Override
public void failed(final Exception cause) {
if (!(cause instanceof SocketException)) {
cause.printStackTrace(System.out);
}
}
@Override
public void releaseResources() {
}
}).create();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("HTTP server shutting down");
server.close(CloseMode.GRACEFUL);
}));
server.start();
final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(port), URIScheme.HTTP);
final ListenerEndpoint listenerEndpoint = future.get();
System.out.print("Listening on " + listenerEndpoint.getAddress());
server.awaitShutdown(TimeValue.MAX_VALUE);
}
use of org.apache.hc.core5.http.impl.Http1StreamListener in project httpcomponents-core by apache.
the class AsyncPipelinedRequestExecutionExample method main.
public static void main(final String[] args) throws Exception {
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(5, TimeUnit.SECONDS).build();
// Create and start requester
final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap().setIOReactorConfig(ioReactorConfig).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)");
}
}
}).create();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("HTTP requester shutting down");
requester.close(CloseMode.GRACEFUL);
}));
requester.start();
final HttpHost target = new HttpHost("httpbin.org");
final String[] requestUris = new String[] { "/", "/ip", "/user-agent", "/headers" };
final Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofSeconds(5));
final AsyncClientEndpoint clientEndpoint = future.get();
final CountDownLatch latch = new CountDownLatch(requestUris.length);
for (final String requestUri : requestUris) {
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) {
latch.countDown();
final HttpResponse response = message.getHead();
final String body = message.getBody();
System.out.println(requestUri + "->" + response.getCode());
System.out.println(body);
}
@Override
public void failed(final Exception ex) {
latch.countDown();
System.out.println(requestUri + "->" + ex);
}
@Override
public void cancelled() {
latch.countDown();
System.out.println(requestUri + " cancelled");
}
});
}
latch.await();
// Manually release client endpoint when done !!!
clientEndpoint.releaseAndDiscard();
System.out.println("Shutting down I/O reactor");
requester.initiateShutdown();
}
Aggregations