Search in sources :

Example 1 with ListenerEndpoint

use of org.apache.hc.core5.reactor.ListenerEndpoint in project httpcomponents-core by apache.

the class H2AlpnTest method testALPN.

@Test
public void testALPN() throws Exception {
    server.start();
    final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), URIScheme.HTTPS);
    final ListenerEndpoint listener = future.get();
    final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
    requester.start();
    final HttpHost target = new HttpHost(URIScheme.HTTPS.id, "localhost", address.getPort());
    final Future<Message<HttpResponse, String>> resultFuture1 = requester.execute(new BasicRequestProducer(Method.POST, target, "/stuff", new StringAsyncEntityProducer("some stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
    final Message<HttpResponse, String> message1;
    try {
        message1 = resultFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    } catch (final ExecutionException e) {
        final Throwable cause = e.getCause();
        assertFalse(h2Allowed, "h2 negotiation was enabled, but h2 was not negotiated");
        assertTrue(cause instanceof ProtocolNegotiationException);
        assertEquals("ALPN: missing application protocol", cause.getMessage());
        assertTrue(strictALPN, "strict ALPN mode was not enabled, but the client negotiator still threw");
        return;
    }
    assertTrue(h2Allowed, "h2 negotiation was disabled, but h2 was negotiated");
    assertThat(message1, CoreMatchers.notNullValue());
    final HttpResponse response1 = message1.getHead();
    assertThat(response1.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
    final String body1 = message1.getBody();
    assertThat(body1, CoreMatchers.equalTo("some stuff"));
}
Also used : StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) HttpHost(org.apache.hc.core5.http.HttpHost) ProtocolNegotiationException(org.apache.hc.core5.http2.impl.nio.ProtocolNegotiationException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Example 2 with ListenerEndpoint

use of org.apache.hc.core5.reactor.ListenerEndpoint in project httpcomponents-core by apache.

the class BenchmarkToolTest method setup.

public void setup(final HttpVersionPolicy versionPolicy) throws Exception {
    server = H2ServerBootstrap.bootstrap().register("/", new AsyncServerRequestHandler<Message<HttpRequest, Void>>() {

        @Override
        public AsyncRequestConsumer<Message<HttpRequest, Void>> prepare(final HttpRequest request, final EntityDetails entityDetails, final HttpContext context) throws HttpException {
            return new BasicRequestConsumer<>(entityDetails != null ? new DiscardingEntityConsumer<>() : null);
        }

        @Override
        public void handle(final Message<HttpRequest, Void> requestObject, final ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException {
            responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_OK).setEntity("0123456789ABCDEF").build(), context);
        }
    }).setVersionPolicy(versionPolicy).create();
    server.start();
    final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), URIScheme.HTTP);
    final ListenerEndpoint listener = future.get();
    address = (InetSocketAddress) listener.getAddress();
}
Also used : AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) HttpRequest(org.apache.hc.core5.http.HttpRequest) DiscardingEntityConsumer(org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer) Message(org.apache.hc.core5.http.Message) BasicRequestConsumer(org.apache.hc.core5.http.nio.support.BasicRequestConsumer) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) InetSocketAddress(java.net.InetSocketAddress) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpContext(org.apache.hc.core5.http.protocol.HttpContext)

Example 3 with ListenerEndpoint

use of org.apache.hc.core5.reactor.ListenerEndpoint 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();
}
Also used : ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) InetSocketAddress(java.net.InetSocketAddress) DefaultAsyncResponseExchangeHandlerFactory(org.apache.hc.core5.http.nio.support.DefaultAsyncResponseExchangeHandlerFactory)

Example 4 with ListenerEndpoint

use of org.apache.hc.core5.reactor.ListenerEndpoint in project httpcomponents-core by apache.

the class Http1TestServer method start.

public InetSocketAddress start(final IOEventHandlerFactory handlerFactory) throws Exception {
    execute(handlerFactory);
    final Future<ListenerEndpoint> future = listen(new InetSocketAddress(0));
    final ListenerEndpoint listener = future.get();
    return (InetSocketAddress) listener.getAddress();
}
Also used : ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) InetSocketAddress(java.net.InetSocketAddress)

Example 5 with ListenerEndpoint

use of org.apache.hc.core5.reactor.ListenerEndpoint 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));
}
Also used : SocketException(java.net.SocketException) HttpConnection(org.apache.hc.core5.http.HttpConnection) InetSocketAddress(java.net.InetSocketAddress) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) H2StreamListener(org.apache.hc.core5.http2.impl.nio.H2StreamListener) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) List(java.util.List) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler) HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) ByteBuffer(java.nio.ByteBuffer) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) SocketException(java.net.SocketException) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) Header(org.apache.hc.core5.http.Header) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) RawFrame(org.apache.hc.core5.http2.frame.RawFrame) H2Config(org.apache.hc.core5.http2.config.H2Config)

Aggregations

InetSocketAddress (java.net.InetSocketAddress)42 ListenerEndpoint (org.apache.hc.core5.reactor.ListenerEndpoint)42 Message (org.apache.hc.core5.http.Message)30 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)27 HttpHost (org.apache.hc.core5.http.HttpHost)26 HttpResponse (org.apache.hc.core5.http.HttpResponse)26 BasicRequestProducer (org.apache.hc.core5.http.nio.support.BasicRequestProducer)26 StringAsyncEntityProducer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer)22 Test (org.junit.Test)16 HttpRequest (org.apache.hc.core5.http.HttpRequest)12 Test (org.junit.jupiter.api.Test)12 AsyncClientEndpoint (org.apache.hc.core5.http.nio.AsyncClientEndpoint)8 IOException (java.io.IOException)7 EntityDetails (org.apache.hc.core5.http.EntityDetails)7 HttpAsyncServer (org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer)7 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)7 IOReactorConfig (org.apache.hc.core5.reactor.IOReactorConfig)7 ExecutionException (java.util.concurrent.ExecutionException)6 BasicClientTlsStrategy (org.apache.hc.core5.http.nio.ssl.BasicClientTlsStrategy)5 BasicServerTlsStrategy (org.apache.hc.core5.http.nio.ssl.BasicServerTlsStrategy)5