Search in sources :

Example 56 with HttpCoreContext

use of org.apache.hc.core5.http.protocol.HttpCoreContext in project httpcomponents-core by apache.

the class TestStandardInterceptors method testRequestExpectContinueGenerated.

@Test
public void testRequestExpectContinueGenerated() throws Exception {
    final HttpCoreContext context = HttpCoreContext.create();
    final BasicClassicHttpRequest request = new BasicClassicHttpRequest(Method.POST, "/");
    request.setEntity(new StringEntity("whatever", StandardCharsets.US_ASCII));
    final RequestExpectContinue interceptor = new RequestExpectContinue();
    interceptor.process(request, request.getEntity(), context);
    final Header header = request.getFirstHeader(HttpHeaders.EXPECT);
    Assertions.assertNotNull(header);
    Assertions.assertEquals(HeaderElements.CONTINUE, header.getValue());
}
Also used : StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) Header(org.apache.hc.core5.http.Header) BasicHeader(org.apache.hc.core5.http.message.BasicHeader) Test(org.junit.jupiter.api.Test)

Example 57 with HttpCoreContext

use of org.apache.hc.core5.http.protocol.HttpCoreContext in project httpcomponents-core by apache.

the class HttpBenchmark method doExecute.

private Results doExecute(final HttpAsyncRequester requester, final Stats stats) throws Exception {
    final URI requestUri = config.getUri();
    final HttpHost host = new HttpHost(requestUri.getScheme(), requestUri.getHost(), requestUri.getPort());
    final AtomicLong requestCount = new AtomicLong(config.getRequests());
    final HttpVersion version = HttpVersion.HTTP_1_1;
    final CountDownLatch completionLatch = new CountDownLatch(config.getConcurrencyLevel());
    final BenchmarkWorker[] workers = new BenchmarkWorker[config.getConcurrencyLevel()];
    for (int i = 0; i < workers.length; i++) {
        final HttpCoreContext context = HttpCoreContext.create();
        context.setProtocolVersion(version);
        final BenchmarkWorker worker = new BenchmarkWorker(requester, host, context, requestCount, completionLatch, stats, config);
        workers[i] = worker;
    }
    final long deadline = config.getTimeLimit() != null ? config.getTimeLimit().toMilliseconds() : Long.MAX_VALUE;
    final long startTime = System.currentTimeMillis();
    for (int i = 0; i < workers.length; i++) {
        workers[i].execute();
    }
    completionLatch.await(deadline, TimeUnit.MILLISECONDS);
    if (config.getVerbosity() >= 3) {
        System.out.println("...done");
    }
    final long endTime = System.currentTimeMillis();
    for (int i = 0; i < workers.length; i++) {
        workers[i].releaseResources();
    }
    return new Results(stats.getServerName(), stats.getVersion(), host.getHostName(), host.getPort() > 0 ? host.getPort() : host.getSchemeName().equalsIgnoreCase("https") ? 443 : 80, requestUri.toASCIIString(), stats.getContentLength(), config.getConcurrencyLevel(), endTime - startTime, stats.getSuccessCount(), stats.getFailureCount(), stats.getKeepAliveCount(), stats.getTotalBytesRecv(), stats.getTotalBytesSent(), stats.getTotalContentLength());
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) HttpHost(org.apache.hc.core5.http.HttpHost) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) HttpVersion(org.apache.hc.core5.http.HttpVersion)

Example 58 with HttpCoreContext

use of org.apache.hc.core5.http.protocol.HttpCoreContext in project httpcomponents-core by apache.

the class H2FileServerExample method main.

public static void main(final String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("Please specify document root directory");
        System.exit(1);
    }
    // Document root directory
    final File docRoot = new File(args[0]);
    int port = 8080;
    if (args.length >= 2) {
        port = Integer.parseInt(args[1]);
    }
    final IOReactorConfig config = IOReactorConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
    final HttpAsyncServer server = H2ServerBootstrap.bootstrap().setIOReactorConfig(config).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("*", 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> message, final ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException {
            final HttpRequest request = message.getHead();
            final URI requestUri;
            try {
                requestUri = request.getUri();
            } catch (final URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
            final String path = requestUri.getPath();
            final File file = new File(docRoot, path);
            if (!file.exists()) {
                System.out.println("File " + file.getPath() + " not found");
                responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_NOT_FOUND).setEntity("<html><body><h1>File" + file.getPath() + " not found</h1></body></html>", ContentType.TEXT_HTML).build(), context);
            } else if (!file.canRead() || file.isDirectory()) {
                System.out.println("Cannot read file " + file.getPath());
                responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_FORBIDDEN).setEntity("<html><body><h1>Access denied</h1></body></html>", ContentType.TEXT_HTML).build(), context);
            } else {
                final ContentType contentType;
                final String filename = TextUtils.toLowerCase(file.getName());
                if (filename.endsWith(".txt")) {
                    contentType = ContentType.TEXT_PLAIN;
                } else if (filename.endsWith(".html") || filename.endsWith(".htm")) {
                    contentType = ContentType.TEXT_HTML;
                } else if (filename.endsWith(".xml")) {
                    contentType = ContentType.TEXT_XML;
                } else {
                    contentType = ContentType.DEFAULT_BINARY;
                }
                final HttpCoreContext coreContext = HttpCoreContext.adapt(context);
                final EndpointDetails endpoint = coreContext.getEndpointDetails();
                System.out.println(endpoint + ": serving file " + file.getPath());
                responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_OK).setEntity(AsyncEntityProducers.create(file, contentType)).build(), context);
            }
        }
    }).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 : Message(org.apache.hc.core5.http.Message) ContentType(org.apache.hc.core5.http.ContentType) HttpConnection(org.apache.hc.core5.http.HttpConnection) BasicRequestConsumer(org.apache.hc.core5.http.nio.support.BasicRequestConsumer) InetSocketAddress(java.net.InetSocketAddress) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) H2StreamListener(org.apache.hc.core5.http2.impl.nio.H2StreamListener) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpRequest(org.apache.hc.core5.http.HttpRequest) ProtocolException(org.apache.hc.core5.http.ProtocolException) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) EndpointDetails(org.apache.hc.core5.http.EndpointDetails) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) DiscardingEntityConsumer(org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) RawFrame(org.apache.hc.core5.http2.frame.RawFrame) File(java.io.File)

Example 59 with HttpCoreContext

use of org.apache.hc.core5.http.protocol.HttpCoreContext in project httpcomponents-core by apache.

the class ServerHttp1StreamDuplexer method terminateExchange.

void terminateExchange(final HttpException ex) throws HttpException, IOException {
    suspendSessionInput();
    final ServerHttp1StreamHandler streamHandler;
    final HttpCoreContext context = HttpCoreContext.create();
    context.setAttribute(HttpCoreContext.SSL_SESSION, getSSLSession());
    context.setAttribute(HttpCoreContext.CONNECTION_ENDPOINT, getEndpointDetails());
    if (outgoing == null) {
        streamHandler = new ServerHttp1StreamHandler(outputChannel, httpProcessor, connectionReuseStrategy, exchangeHandlerFactory, context);
        outgoing = streamHandler;
    } else {
        streamHandler = new ServerHttp1StreamHandler(new DelayedOutputChannel(outputChannel), httpProcessor, connectionReuseStrategy, exchangeHandlerFactory, context);
        pipeline.add(streamHandler);
    }
    streamHandler.terminateExchange(ex);
    incoming = null;
}
Also used : HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext)

Example 60 with HttpCoreContext

use of org.apache.hc.core5.http.protocol.HttpCoreContext in project httpcomponents-core by apache.

the class ServerHttp1StreamDuplexer method consumeHeader.

@Override
void consumeHeader(final HttpRequest request, final EntityDetails entityDetails) throws HttpException, IOException {
    if (streamListener != null) {
        streamListener.onRequestHead(this, request);
    }
    final ServerHttp1StreamHandler streamHandler;
    final HttpCoreContext context = HttpCoreContext.create();
    context.setAttribute(HttpCoreContext.SSL_SESSION, getSSLSession());
    context.setAttribute(HttpCoreContext.CONNECTION_ENDPOINT, getEndpointDetails());
    if (outgoing == null) {
        streamHandler = new ServerHttp1StreamHandler(outputChannel, httpProcessor, connectionReuseStrategy, exchangeHandlerFactory, context);
        outgoing = streamHandler;
    } else {
        streamHandler = new ServerHttp1StreamHandler(new DelayedOutputChannel(outputChannel), httpProcessor, connectionReuseStrategy, exchangeHandlerFactory, context);
        pipeline.add(streamHandler);
    }
    request.setScheme(scheme);
    streamHandler.consumeHeader(request, entityDetails);
    incoming = streamHandler;
}
Also used : HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext)

Aggregations

HttpCoreContext (org.apache.hc.core5.http.protocol.HttpCoreContext)56 BasicClassicHttpRequest (org.apache.hc.core5.http.message.BasicClassicHttpRequest)46 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)39 ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)33 BasicClassicHttpResponse (org.apache.hc.core5.http.message.BasicClassicHttpResponse)29 HttpHost (org.apache.hc.core5.http.HttpHost)26 Test (org.junit.jupiter.api.Test)25 Test (org.junit.Test)21 HttpEntity (org.apache.hc.core5.http.HttpEntity)16 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)13 HttpClientConnection (org.apache.hc.core5.http.io.HttpClientConnection)12 ByteArrayEntity (org.apache.hc.core5.http.io.entity.ByteArrayEntity)12 HttpProcessor (org.apache.hc.core5.http.protocol.HttpProcessor)12 AbstractHttpEntity (org.apache.hc.core5.http.io.entity.AbstractHttpEntity)9 Random (java.util.Random)8 Header (org.apache.hc.core5.http.Header)8 ArrayList (java.util.ArrayList)6 HttpRequest (org.apache.hc.core5.http.HttpRequest)6 ProtocolException (org.apache.hc.core5.http.ProtocolException)6 ContentType (org.apache.hc.core5.http.ContentType)5