use of org.apache.hc.core5.http.HttpConnection in project httpcomponents-client by apache.
the class HttpAsyncClientProtocolNegotiationStarter method createHandler.
@Override
public IOEventHandler createHandler(final ProtocolIOSession ioSession, final Object attachment) {
final ClientHttp1StreamDuplexerFactory http1StreamHandlerFactory;
final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory;
if (STREAM_LOG.isDebugEnabled() || HEADER_LOG.isDebugEnabled() || FRAME_LOG.isDebugEnabled() || FRAME_PAYLOAD_LOG.isDebugEnabled() || FLOW_CTRL_LOG.isDebugEnabled()) {
final String id = ioSession.getId();
http1StreamHandlerFactory = new ClientHttp1StreamDuplexerFactory(httpProcessor, h1Config, charCodingConfig, http1ConnectionReuseStrategy, http1ResponseParserFactory, http1RequestWriterFactory, new Http1StreamListener() {
@Override
public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
if (HEADER_LOG.isDebugEnabled()) {
HEADER_LOG.debug("{} >> {}", id, new RequestLine(request));
for (final Iterator<Header> it = request.headerIterator(); it.hasNext(); ) {
HEADER_LOG.debug("{} >> {}", id, it.next());
}
}
}
@Override
public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
if (HEADER_LOG.isDebugEnabled()) {
HEADER_LOG.debug("{} << {}", id, new StatusLine(response));
for (final Iterator<Header> it = response.headerIterator(); it.hasNext(); ) {
HEADER_LOG.debug("{} << {}", id, it.next());
}
}
}
@Override
public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
if (STREAM_LOG.isDebugEnabled()) {
if (keepAlive) {
STREAM_LOG.debug("{} Connection is kept alive", id);
} else {
STREAM_LOG.debug("{} Connection is not kept alive", id);
}
}
}
});
http2StreamHandlerFactory = new ClientH2StreamMultiplexerFactory(httpProcessor, exchangeHandlerFactory, h2Config, charCodingConfig, new H2StreamListener() {
final FramePrinter framePrinter = new FramePrinter();
private void logFrameInfo(final String prefix, final RawFrame frame) {
try {
final LogAppendable logAppendable = new LogAppendable(FRAME_LOG, prefix);
framePrinter.printFrameInfo(frame, logAppendable);
logAppendable.flush();
} catch (final IOException ignore) {
}
}
private void logFramePayload(final String prefix, final RawFrame frame) {
try {
final LogAppendable logAppendable = new LogAppendable(FRAME_PAYLOAD_LOG, prefix);
framePrinter.printPayload(frame, logAppendable);
logAppendable.flush();
} catch (final IOException ignore) {
}
}
private void logFlowControl(final String prefix, final int streamId, final int delta, final int actualSize) {
FLOW_CTRL_LOG.debug("{} stream {} flow control {} -> {}", prefix, streamId, delta, actualSize);
}
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
if (HEADER_LOG.isDebugEnabled()) {
for (int i = 0; i < headers.size(); i++) {
HEADER_LOG.debug("{} << {}", id, headers.get(i));
}
}
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
if (HEADER_LOG.isDebugEnabled()) {
for (int i = 0; i < headers.size(); i++) {
HEADER_LOG.debug("{} >> {}", id, headers.get(i));
}
}
}
@Override
public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
if (FRAME_LOG.isDebugEnabled()) {
logFrameInfo(id + " <<", frame);
}
if (FRAME_PAYLOAD_LOG.isDebugEnabled()) {
logFramePayload(id + " <<", frame);
}
}
@Override
public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
if (FRAME_LOG.isDebugEnabled()) {
logFrameInfo(id + " >>", frame);
}
if (FRAME_PAYLOAD_LOG.isDebugEnabled()) {
logFramePayload(id + " >>", frame);
}
}
@Override
public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
if (FLOW_CTRL_LOG.isDebugEnabled()) {
logFlowControl(id + " <<", streamId, delta, actualSize);
}
}
@Override
public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
if (FLOW_CTRL_LOG.isDebugEnabled()) {
logFlowControl(id + " >>", streamId, delta, actualSize);
}
}
});
} else {
http1StreamHandlerFactory = new ClientHttp1StreamDuplexerFactory(httpProcessor, h1Config, charCodingConfig, http1ConnectionReuseStrategy, http1ResponseParserFactory, http1RequestWriterFactory, null);
http2StreamHandlerFactory = new ClientH2StreamMultiplexerFactory(httpProcessor, exchangeHandlerFactory, h2Config, charCodingConfig, null);
}
ioSession.registerProtocol(ApplicationProtocol.HTTP_1_1.id, new ClientHttp1UpgradeHandler(http1StreamHandlerFactory));
ioSession.registerProtocol(ApplicationProtocol.HTTP_2.id, new ClientH2UpgradeHandler(http2StreamHandlerFactory));
final HttpVersionPolicy versionPolicy = attachment instanceof HttpVersionPolicy ? (HttpVersionPolicy) attachment : HttpVersionPolicy.NEGOTIATE;
switch(versionPolicy) {
case FORCE_HTTP_2:
return new ClientH2PrefaceHandler(ioSession, http2StreamHandlerFactory, false);
case FORCE_HTTP_1:
return new ClientHttp1IOEventHandler(http1StreamHandlerFactory.create(ioSession));
default:
return new HttpProtocolNegotiator(ioSession, null);
}
}
use of org.apache.hc.core5.http.HttpConnection in project httpcomponents-core by apache.
the class LoggingHttp1StreamListener method onRequestHead.
@Override
public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
if (headerLog.isDebugEnabled()) {
final String idRequestDirection = LoggingSupport.getId(connection) + requestDirection;
headerLog.debug("{}{}", idRequestDirection, new RequestLine(request));
for (final Iterator<Header> it = request.headerIterator(); it.hasNext(); ) {
headerLog.debug("{}{}", idRequestDirection, it.next());
}
}
}
use of org.apache.hc.core5.http.HttpConnection 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.HttpConnection 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();
}
use of org.apache.hc.core5.http.HttpConnection in project httpcomponents-core by apache.
the class AsyncRequestExecutionExample 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 CountDownLatch latch = new CountDownLatch(requestUris.length);
for (final String requestUri : requestUris) {
requester.execute(AsyncRequestBuilder.get().setHttpHost(target).setPath(requestUri).build(), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), Timeout.ofSeconds(5), 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();
System.out.println("Shutting down I/O reactor");
requester.initiateShutdown();
}
Aggregations