use of org.apache.hc.core5.http.HttpConnection in project httpcomponents-core by apache.
the class H2FullDuplexServerExample 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 H2Config h2Config = H2Config.custom().setPushEnabled(true).setMaxConcurrentStreams(100).build();
final HttpAsyncServer server = H2ServerBootstrap.bootstrap().setIOReactorConfig(config).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) {
}
}).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.ofDays(Long.MAX_VALUE));
}
use of org.apache.hc.core5.http.HttpConnection in project httpcomponents-core by apache.
the class TestStrictConnPool method testCloseIdle.
@Test
public void testCloseIdle() throws Exception {
final HttpConnection conn1 = Mockito.mock(HttpConnection.class);
final HttpConnection conn2 = Mockito.mock(HttpConnection.class);
final StrictConnPool<String, HttpConnection> pool = new StrictConnPool<>(2, 2);
final Future<PoolEntry<String, HttpConnection>> future1 = pool.lease("somehost", null);
final Future<PoolEntry<String, HttpConnection>> future2 = pool.lease("somehost", null);
Assertions.assertTrue(future1.isDone());
final PoolEntry<String, HttpConnection> entry1 = future1.get();
Assertions.assertNotNull(entry1);
entry1.assignConnection(conn1);
Assertions.assertTrue(future2.isDone());
final PoolEntry<String, HttpConnection> entry2 = future2.get();
Assertions.assertNotNull(entry2);
entry2.assignConnection(conn2);
entry1.updateState(null);
pool.release(entry1, true);
Thread.sleep(200L);
entry2.updateState(null);
pool.release(entry2, true);
pool.closeIdle(TimeValue.of(50, TimeUnit.MILLISECONDS));
Mockito.verify(conn1).close(CloseMode.GRACEFUL);
Mockito.verify(conn2, Mockito.never()).close(ArgumentMatchers.any());
PoolStats totals = pool.getTotalStats();
Assertions.assertEquals(1, totals.getAvailable());
Assertions.assertEquals(0, totals.getLeased());
Assertions.assertEquals(0, totals.getPending());
PoolStats stats = pool.getStats("somehost");
Assertions.assertEquals(1, stats.getAvailable());
Assertions.assertEquals(0, stats.getLeased());
Assertions.assertEquals(0, stats.getPending());
pool.closeIdle(TimeValue.of(-1, TimeUnit.MILLISECONDS));
Mockito.verify(conn2).close(CloseMode.GRACEFUL);
totals = pool.getTotalStats();
Assertions.assertEquals(0, totals.getAvailable());
Assertions.assertEquals(0, totals.getLeased());
Assertions.assertEquals(0, totals.getPending());
stats = pool.getStats("somehost");
Assertions.assertEquals(0, stats.getAvailable());
Assertions.assertEquals(0, stats.getLeased());
Assertions.assertEquals(0, stats.getPending());
}
use of org.apache.hc.core5.http.HttpConnection in project httpcomponents-core by apache.
the class TestStrictConnPool method testLeaseRequestTimeout.
@Test
public void testLeaseRequestTimeout() throws Exception {
final HttpConnection conn1 = Mockito.mock(HttpConnection.class);
final StrictConnPool<String, HttpConnection> pool = new StrictConnPool<>(1, 1);
final Future<PoolEntry<String, HttpConnection>> future1 = pool.lease("somehost", null, Timeout.ofMilliseconds(0), null);
final Future<PoolEntry<String, HttpConnection>> future2 = pool.lease("somehost", null, Timeout.ofMilliseconds(0), null);
final Future<PoolEntry<String, HttpConnection>> future3 = pool.lease("somehost", null, Timeout.ofMilliseconds(10), null);
Assertions.assertTrue(future1.isDone());
final PoolEntry<String, HttpConnection> entry1 = future1.get();
Assertions.assertNotNull(entry1);
entry1.assignConnection(conn1);
Assertions.assertFalse(future2.isDone());
Assertions.assertFalse(future3.isDone());
Thread.sleep(100);
pool.validatePendingRequests();
Assertions.assertFalse(future2.isDone());
Assertions.assertTrue(future3.isDone());
}
use of org.apache.hc.core5.http.HttpConnection in project httpcomponents-core by apache.
the class TestLaxConnPool method testCloseExpired.
@Test
public void testCloseExpired() throws Exception {
final HttpConnection conn1 = Mockito.mock(HttpConnection.class);
final HttpConnection conn2 = Mockito.mock(HttpConnection.class);
final LaxConnPool<String, HttpConnection> pool = new LaxConnPool<>(2);
final Future<PoolEntry<String, HttpConnection>> future1 = pool.lease("somehost", null);
final Future<PoolEntry<String, HttpConnection>> future2 = pool.lease("somehost", null);
Assertions.assertTrue(future1.isDone());
final PoolEntry<String, HttpConnection> entry1 = future1.get();
Assertions.assertNotNull(entry1);
entry1.assignConnection(conn1);
Assertions.assertTrue(future2.isDone());
final PoolEntry<String, HttpConnection> entry2 = future2.get();
Assertions.assertNotNull(entry2);
entry2.assignConnection(conn2);
entry1.updateExpiry(TimeValue.of(1, TimeUnit.MILLISECONDS));
pool.release(entry1, true);
Thread.sleep(200);
entry2.updateExpiry(TimeValue.of(1000, TimeUnit.SECONDS));
pool.release(entry2, true);
pool.closeExpired();
Mockito.verify(conn1).close(CloseMode.GRACEFUL);
Mockito.verify(conn2, Mockito.never()).close(ArgumentMatchers.any());
final PoolStats totals = pool.getTotalStats();
Assertions.assertEquals(1, totals.getAvailable());
Assertions.assertEquals(0, totals.getLeased());
Assertions.assertEquals(0, totals.getPending());
final PoolStats stats = pool.getStats("somehost");
Assertions.assertEquals(1, stats.getAvailable());
Assertions.assertEquals(0, stats.getLeased());
Assertions.assertEquals(0, stats.getPending());
}
use of org.apache.hc.core5.http.HttpConnection in project httpcomponents-core by apache.
the class TestLaxConnPool method testCreateNewIfExpired.
@Test
public void testCreateNewIfExpired() throws Exception {
final HttpConnection conn1 = Mockito.mock(HttpConnection.class);
final LaxConnPool<String, HttpConnection> pool = new LaxConnPool<>(2);
final Future<PoolEntry<String, HttpConnection>> future1 = pool.lease("somehost", null);
Assertions.assertTrue(future1.isDone());
final PoolEntry<String, HttpConnection> entry1 = future1.get();
Assertions.assertNotNull(entry1);
entry1.assignConnection(conn1);
entry1.updateExpiry(TimeValue.of(1, TimeUnit.MILLISECONDS));
pool.release(entry1, true);
Thread.sleep(200L);
final Future<PoolEntry<String, HttpConnection>> future2 = pool.lease("somehost", null);
Assertions.assertTrue(future2.isDone());
Mockito.verify(conn1).close(CloseMode.GRACEFUL);
final PoolStats totals = pool.getTotalStats();
Assertions.assertEquals(0, totals.getAvailable());
Assertions.assertEquals(1, totals.getLeased());
Assertions.assertEquals(Collections.singleton("somehost"), pool.getRoutes());
final PoolStats stats = pool.getStats("somehost");
Assertions.assertEquals(0, stats.getAvailable());
Assertions.assertEquals(1, stats.getLeased());
}
Aggregations