use of org.apache.hc.core5.http.nio.AsyncServerExchangeHandler in project httpcomponents-core by apache.
the class H2IntegrationTest method testPrematureResponse.
@Test
public void testPrematureResponse() throws Exception {
server.register("*", new Supplier<AsyncServerExchangeHandler>() {
@Override
public AsyncServerExchangeHandler get() {
return new AsyncServerExchangeHandler() {
private final AtomicReference<AsyncResponseProducer> responseProducer = new AtomicReference<>();
@Override
public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
capacityChannel.update(Integer.MAX_VALUE);
}
@Override
public void consume(final ByteBuffer src) throws IOException {
}
@Override
public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
}
@Override
public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
final AsyncResponseProducer producer;
final Header h = request.getFirstHeader("password");
if (h != null && "secret".equals(h.getValue())) {
producer = new BasicResponseProducer(HttpStatus.SC_OK, "All is well");
} else {
producer = new BasicResponseProducer(HttpStatus.SC_UNAUTHORIZED, "You shall not pass");
}
responseProducer.set(producer);
producer.sendResponse(responseChannel, context);
}
@Override
public int available() {
final AsyncResponseProducer producer = this.responseProducer.get();
return producer.available();
}
@Override
public void produce(final DataStreamChannel channel) throws IOException {
final AsyncResponseProducer producer = this.responseProducer.get();
producer.produce(channel);
}
@Override
public void failed(final Exception cause) {
}
@Override
public void releaseResources() {
}
};
}
});
final InetSocketAddress serverEndpoint = server.start();
client.start();
final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
final ClientSessionEndpoint streamEndpoint = connectFuture.get();
final HttpRequest request1 = new BasicHttpRequest(Method.POST, createRequestURI(serverEndpoint, "/echo"));
final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, new MultiLineEntityProducer("0123456789abcdef", 5000)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
final Message<HttpResponse, String> result1 = future1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
Assertions.assertNotNull(result1);
final HttpResponse response1 = result1.getHead();
Assertions.assertNotNull(response1);
Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response1.getCode());
Assertions.assertNotNull("You shall not pass", result1.getBody());
}
use of org.apache.hc.core5.http.nio.AsyncServerExchangeHandler 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.AsyncServerExchangeHandler 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.http.nio.AsyncServerExchangeHandler 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);
}
use of org.apache.hc.core5.http.nio.AsyncServerExchangeHandler 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));
}
Aggregations