Search in sources :

Example 1 with HttpVersionPolicy

use of org.apache.hc.core5.http2.HttpVersionPolicy 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 2 with HttpVersionPolicy

use of org.apache.hc.core5.http2.HttpVersionPolicy in project httpcomponents-core by apache.

the class ClientHttpProtocolNegotiationStarter method createHandler.

@Override
public HttpConnectionEventHandler createHandler(final ProtocolIOSession ioSession, final Object attachment) {
    HttpVersionPolicy endpointPolicy = versionPolicy;
    if (attachment instanceof EndpointParameters) {
        final EndpointParameters params = (EndpointParameters) attachment;
        if (tlsStrategy != null && URIScheme.HTTPS.same(params.getScheme())) {
            tlsStrategy.upgrade(ioSession, params, params.getAttachment(), handshakeTimeout, null);
        }
        if (params.getAttachment() instanceof HttpVersionPolicy) {
            endpointPolicy = (HttpVersionPolicy) params.getAttachment();
        }
    }
    ioSession.registerProtocol(ApplicationProtocol.HTTP_1_1.id, new ClientHttp1UpgradeHandler(http1StreamHandlerFactory));
    ioSession.registerProtocol(ApplicationProtocol.HTTP_2.id, new ClientH2UpgradeHandler(http2StreamHandlerFactory));
    switch(endpointPolicy) {
        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);
    }
}
Also used : HttpVersionPolicy(org.apache.hc.core5.http2.HttpVersionPolicy) EndpointParameters(org.apache.hc.core5.reactor.EndpointParameters) ClientHttp1IOEventHandler(org.apache.hc.core5.http.impl.nio.ClientHttp1IOEventHandler)

Example 3 with HttpVersionPolicy

use of org.apache.hc.core5.http2.HttpVersionPolicy in project httpcomponents-core by apache.

the class ReactiveClientTest method testRequestTimeout.

@Test
public void testRequestTimeout() throws Exception {
    final InetSocketAddress address = startClientAndServer();
    final AtomicBoolean requestPublisherWasCancelled = new AtomicBoolean(false);
    final Publisher<ByteBuffer> publisher = Flowable.<ByteBuffer>never().doOnCancel(() -> requestPublisherWasCancelled.set(true));
    final ReactiveEntityProducer producer = new ReactiveEntityProducer(publisher, -1, null, null);
    final BasicRequestProducer request = getRequestProducer(address, producer);
    final ReactiveResponseConsumer consumer = new ReactiveResponseConsumer();
    final Future<Void> future = requester.execute(request, consumer, Timeout.ofSeconds(1), null);
    final ExecutionException exception = Assertions.assertThrows(ExecutionException.class, () -> future.get(RESULT_TIMEOUT.getDuration(), RESULT_TIMEOUT.getTimeUnit()));
    Assertions.assertTrue(requestPublisherWasCancelled.get());
    final Throwable cause = exception.getCause();
    if (versionPolicy == HttpVersionPolicy.FORCE_HTTP_1) {
        Assertions.assertTrue(cause instanceof SocketTimeoutException, "Expected SocketTimeoutException, but got " + cause.getClass().getName());
    } else if (versionPolicy == HttpVersionPolicy.FORCE_HTTP_2) {
        Assertions.assertTrue(cause instanceof HttpStreamResetException, format("Expected RST_STREAM, but %s was thrown", cause.getClass().getName()));
    } else {
        Assertions.fail("Unknown HttpVersionPolicy: " + versionPolicy);
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) ByteBuffer(java.nio.ByteBuffer) ReactiveEntityProducer(org.apache.hc.core5.reactive.ReactiveEntityProducer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SocketTimeoutException(java.net.SocketTimeoutException) ReactiveResponseConsumer(org.apache.hc.core5.reactive.ReactiveResponseConsumer) ExecutionException(java.util.concurrent.ExecutionException) HttpStreamResetException(org.apache.hc.core5.http.HttpStreamResetException) Test(org.junit.Test)

Example 4 with HttpVersionPolicy

use of org.apache.hc.core5.http2.HttpVersionPolicy in project httpcomponents-core by apache.

the class BenchmarkToolTest method testBasics.

@ParameterizedTest(name = "{0}")
@MethodSource("protocols")
public void testBasics(final HttpVersionPolicy versionPolicy) throws Exception {
    setup(versionPolicy);
    final BenchmarkConfig config = BenchmarkConfig.custom().setKeepAlive(true).setMethod(Method.POST.name()).setPayloadText("0123456789ABCDEF").setUri(new URIBuilder().setScheme(URIScheme.HTTP.id).setHost("localhost").setPort(address.getPort()).build()).setConcurrencyLevel(3).setForceHttp2(versionPolicy == HttpVersionPolicy.FORCE_HTTP_2).setRequests(100).build();
    final HttpBenchmark httpBenchmark = new HttpBenchmark(config);
    final Results results = httpBenchmark.execute();
    Assertions.assertNotNull(results);
    Assertions.assertEquals(100, results.getSuccessCount());
    Assertions.assertEquals(0, results.getFailureCount());
    Assertions.assertEquals(16, results.getContentLength());
    Assertions.assertEquals(3, results.getConcurrencyLevel());
    Assertions.assertEquals(100 * 16, results.getTotalContentBytesRecvd());
    if (versionPolicy == HttpVersionPolicy.FORCE_HTTP_2) {
        Assertions.assertEquals(HttpVersion.HTTP_2, results.getProtocolVersion());
    }
}
Also used : URIBuilder(org.apache.hc.core5.net.URIBuilder) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 5 with HttpVersionPolicy

use of org.apache.hc.core5.http2.HttpVersionPolicy in project httpcomponents-core by apache.

the class HttpBenchmark method execute.

public Results execute() throws Exception {
    final HttpProcessorBuilder builder = HttpProcessorBuilder.create().addAll(new H2RequestContent(), new H2RequestTargetHost(), new H2RequestConnControl(), new RequestUserAgent("HttpCore-AB/5.0"));
    if (this.config.isUseExpectContinue()) {
        builder.add(new RequestExpectContinue());
    }
    final SSLContext sslContext;
    if ("https".equals(config.getUri().getScheme())) {
        final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.setProtocol("SSL");
        if (config.isDisableSSLVerification()) {
            sslContextBuilder.loadTrustMaterial(null, (chain, authType) -> true);
        } else if (config.getTrustStorePath() != null) {
            sslContextBuilder.loadTrustMaterial(new File(config.getTrustStorePath()), config.getTrustStorePassword() != null ? config.getTrustStorePassword().toCharArray() : null);
        }
        if (config.getIdentityStorePath() != null) {
            sslContextBuilder.loadKeyMaterial(Paths.get(config.getIdentityStorePath()), config.getIdentityStorePassword() != null ? config.getIdentityStorePassword().toCharArray() : null, config.getIdentityStorePassword() != null ? config.getIdentityStorePassword().toCharArray() : null);
        }
        sslContext = sslContextBuilder.build();
    } else {
        sslContext = SSLContexts.createSystemDefault();
    }
    final HttpVersionPolicy versionPolicy;
    if (config.isForceHttp2()) {
        versionPolicy = HttpVersionPolicy.FORCE_HTTP_2;
    } else {
        if (sslContext != null) {
            versionPolicy = HttpVersionPolicy.NEGOTIATE;
        } else {
            versionPolicy = HttpVersionPolicy.FORCE_HTTP_1;
        }
    }
    final Stats stats = new Stats();
    try (final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap().setHttpProcessor(builder.build()).setTlsStrategy(new BasicClientTlsStrategy(sslContext)).setVersionPolicy(versionPolicy).setH2Config(H2Config.custom().setPushEnabled(false).build()).setIOSessionDecorator(ioSession -> new IOSession() {

        @Override
        public String getId() {
            return ioSession.getId();
        }

        @Override
        public Lock getLock() {
            return ioSession.getLock();
        }

        @Override
        public void enqueue(final Command command, final Command.Priority priority) {
            ioSession.enqueue(command, priority);
        }

        @Override
        public boolean hasCommands() {
            return ioSession.hasCommands();
        }

        @Override
        public Command poll() {
            return ioSession.poll();
        }

        @Override
        public ByteChannel channel() {
            return ioSession.channel();
        }

        @Override
        public SocketAddress getRemoteAddress() {
            return ioSession.getRemoteAddress();
        }

        @Override
        public SocketAddress getLocalAddress() {
            return ioSession.getLocalAddress();
        }

        @Override
        public int getEventMask() {
            return ioSession.getEventMask();
        }

        @Override
        public void setEventMask(final int ops) {
            ioSession.setEventMask(ops);
        }

        @Override
        public void setEvent(final int op) {
            ioSession.setEvent(op);
        }

        @Override
        public void clearEvent(final int op) {
            ioSession.clearEvent(op);
        }

        @Override
        public void close() {
            ioSession.close();
        }

        @Override
        public Status getStatus() {
            return ioSession.getStatus();
        }

        @Override
        public int read(final ByteBuffer dst) throws IOException {
            final int bytesRead = ioSession.read(dst);
            if (bytesRead > 0) {
                stats.incTotalBytesRecv(bytesRead);
            }
            return bytesRead;
        }

        @Override
        public int write(final ByteBuffer src) throws IOException {
            final int bytesWritten = ioSession.write(src);
            if (bytesWritten > 0) {
                stats.incTotalBytesSent(bytesWritten);
            }
            return bytesWritten;
        }

        @Override
        public boolean isOpen() {
            return ioSession.isOpen();
        }

        @Override
        public Timeout getSocketTimeout() {
            return ioSession.getSocketTimeout();
        }

        @Override
        public void setSocketTimeout(final Timeout timeout) {
            ioSession.setSocketTimeout(timeout);
        }

        @Override
        public long getLastReadTime() {
            return ioSession.getLastReadTime();
        }

        @Override
        public long getLastWriteTime() {
            return ioSession.getLastWriteTime();
        }

        @Override
        public long getLastEventTime() {
            return ioSession.getLastEventTime();
        }

        @Override
        public void updateReadTime() {
            ioSession.updateReadTime();
        }

        @Override
        public void updateWriteTime() {
            ioSession.updateWriteTime();
        }

        @Override
        public void close(final CloseMode closeMode) {
            ioSession.close(closeMode);
        }

        @Override
        public IOEventHandler getHandler() {
            return ioSession.getHandler();
        }

        @Override
        public void upgrade(final IOEventHandler handler) {
            ioSession.upgrade(handler);
        }
    }).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            if (config.getVerbosity() >= 3) {
                System.out.println(">> " + request.getMethod() + " " + request.getRequestUri());
                final Header[] headers = request.getHeaders();
                for (final Header header : headers) {
                    System.out.println(">> " + header);
                }
                System.out.println();
            }
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            if (config.getVerbosity() >= 3) {
                System.out.println("<< " + response.getCode() + " " + response.getReasonPhrase());
                final Header[] headers = response.getHeaders();
                for (final Header header : headers) {
                    System.out.println("<< " + header);
                }
                System.out.println();
            }
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
        }
    }).setStreamListener(new H2StreamListener() {

        private final FramePrinter framePrinter = new FramePrinter();

        @Override
        public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
            if (config.getVerbosity() >= 3) {
                for (final Header header : headers) {
                    System.out.println("<< " + header);
                }
                System.out.println();
            }
        }

        @Override
        public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
            if (config.getVerbosity() >= 3) {
                for (final Header header : headers) {
                    System.out.println(">> " + header);
                }
                System.out.println();
            }
        }

        @Override
        public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
            if (config.getVerbosity() >= 4) {
                System.out.print("<< ");
                try {
                    framePrinter.printFrameInfo(frame, System.out);
                    System.out.println();
                    if (!frame.isType(FrameType.DATA)) {
                        framePrinter.printPayload(frame, System.out);
                        System.out.println();
                    }
                } catch (final IOException ignore) {
                }
            }
        }

        @Override
        public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
            if (config.getVerbosity() >= 4) {
                System.out.print(">> ");
                try {
                    framePrinter.printFrameInfo(frame, System.out);
                    System.out.println();
                    if (!frame.isType(FrameType.DATA)) {
                        framePrinter.printPayload(frame, System.out);
                        System.out.println();
                    }
                } catch (final IOException ignore) {
                }
            }
        }

        @Override
        public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
            if (config.getVerbosity() >= 5) {
                System.out.println("<< stream " + streamId + ": " + actualSize + " " + delta);
            }
        }

        @Override
        public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
            if (config.getVerbosity() >= 5) {
                System.out.println(">> stream " + streamId + ": " + actualSize + " " + delta);
            }
        }
    }).setIOReactorConfig(IOReactorConfig.custom().setSoTimeout(config.getSocketTimeout()).build()).create()) {
        requester.setDefaultMaxPerRoute(config.getConcurrencyLevel());
        requester.setMaxTotal(config.getConcurrencyLevel() * 2);
        requester.start();
        return doExecute(requester, stats);
    }
}
Also used : HttpConnection(org.apache.hc.core5.http.HttpConnection) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) H2RequestContent(org.apache.hc.core5.http2.protocol.H2RequestContent) H2RequestConnControl(org.apache.hc.core5.http2.protocol.H2RequestConnControl) H2StreamListener(org.apache.hc.core5.http2.impl.nio.H2StreamListener) HttpVersionPolicy(org.apache.hc.core5.http2.HttpVersionPolicy) IOSession(org.apache.hc.core5.reactor.IOSession) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester) SocketAddress(java.net.SocketAddress) SSLContextBuilder(org.apache.hc.core5.ssl.SSLContextBuilder) HttpRequest(org.apache.hc.core5.http.HttpRequest) FramePrinter(org.apache.hc.core5.http2.frame.FramePrinter) RequestExpectContinue(org.apache.hc.core5.http.protocol.RequestExpectContinue) RequestUserAgent(org.apache.hc.core5.http.protocol.RequestUserAgent) Timeout(org.apache.hc.core5.util.Timeout) HttpResponse(org.apache.hc.core5.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Lock(java.util.concurrent.locks.Lock) IOEventHandler(org.apache.hc.core5.reactor.IOEventHandler) HttpProcessorBuilder(org.apache.hc.core5.http.protocol.HttpProcessorBuilder) ByteChannel(java.nio.channels.ByteChannel) BasicClientTlsStrategy(org.apache.hc.core5.http.nio.ssl.BasicClientTlsStrategy) Header(org.apache.hc.core5.http.Header) Command(org.apache.hc.core5.reactor.Command) CloseMode(org.apache.hc.core5.io.CloseMode) RawFrame(org.apache.hc.core5.http2.frame.RawFrame) H2RequestTargetHost(org.apache.hc.core5.http2.protocol.H2RequestTargetHost) File(java.io.File)

Aggregations

HttpVersionPolicy (org.apache.hc.core5.http2.HttpVersionPolicy)3 InetSocketAddress (java.net.InetSocketAddress)2 ByteBuffer (java.nio.ByteBuffer)2 HttpRequest (org.apache.hc.core5.http.HttpRequest)2 EndpointParameters (org.apache.hc.core5.reactor.EndpointParameters)2 File (java.io.File)1 IOException (java.io.IOException)1 SocketAddress (java.net.SocketAddress)1 SocketTimeoutException (java.net.SocketTimeoutException)1 ByteChannel (java.nio.channels.ByteChannel)1 ExecutionException (java.util.concurrent.ExecutionException)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 Lock (java.util.concurrent.locks.Lock)1 SSLContext (javax.net.ssl.SSLContext)1 EntityDetails (org.apache.hc.core5.http.EntityDetails)1 Header (org.apache.hc.core5.http.Header)1 HttpConnection (org.apache.hc.core5.http.HttpConnection)1 HttpResponse (org.apache.hc.core5.http.HttpResponse)1 HttpStreamResetException (org.apache.hc.core5.http.HttpStreamResetException)1 Message (org.apache.hc.core5.http.Message)1