Search in sources :

Example 1 with AsyncRequestConsumer

use of org.apache.hc.core5.http.nio.AsyncRequestConsumer in project httpcomponents-core by apache.

the class H2IntegrationTest method testMessageWithTrailers.

@Test
public void testMessageWithTrailers() throws Exception {
    server.register("/hello", () -> new AbstractServerExchangeHandler<Message<HttpRequest, String>>() {

        @Override
        protected AsyncRequestConsumer<Message<HttpRequest, String>> supplyConsumer(final HttpRequest request, final EntityDetails entityDetails, final HttpContext context) throws HttpException {
            return new BasicRequestConsumer<>(entityDetails != null ? new StringAsyncEntityConsumer() : null);
        }

        @Override
        protected void handle(final Message<HttpRequest, String> requestMessage, final AsyncServerRequestHandler.ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException {
            responseTrigger.submitResponse(new BasicResponseProducer(HttpStatus.SC_OK, new DigestingEntityProducer("MD5", new StringAsyncEntityProducer("Hello back with some trailers"))), context);
        }
    });
    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.GET, createRequestURI(serverEndpoint, "/hello"));
    final DigestingEntityConsumer<String> entityConsumer = new DigestingEntityConsumer<>("MD5", new StringAsyncEntityConsumer());
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, null), new BasicResponseConsumer<>(entityConsumer), 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(200, response1.getCode());
    Assertions.assertEquals("Hello back with some trailers", result1.getBody());
    final List<Header> trailers = entityConsumer.getTrailers();
    Assertions.assertNotNull(trailers);
    Assertions.assertEquals(2, trailers.size());
    final Map<String, String> map = new HashMap<>();
    for (final Header header : trailers) {
        map.put(TextUtils.toLowerCase(header.getName()), header.getValue());
    }
    final String digest = TextUtils.toHexString(entityConsumer.getDigest());
    Assertions.assertEquals("MD5", map.get("digest-algo"));
    Assertions.assertEquals(digest, map.get("digest"));
}
Also used : Message(org.apache.hc.core5.http.Message) DigestingEntityProducer(org.apache.hc.core5.http.nio.entity.DigestingEntityProducer) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpException(org.apache.hc.core5.http.HttpException) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) DigestingEntityConsumer(org.apache.hc.core5.http.nio.entity.DigestingEntityConsumer) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) AsyncRequestConsumer(org.apache.hc.core5.http.nio.AsyncRequestConsumer) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) Header(org.apache.hc.core5.http.Header) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer) Test(org.junit.Test)

Example 2 with AsyncRequestConsumer

use of org.apache.hc.core5.http.nio.AsyncRequestConsumer 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 AsyncRequestConsumer

use of org.apache.hc.core5.http.nio.AsyncRequestConsumer in project httpcomponents-core by apache.

the class Http1IntegrationTest method testMessageWithTrailers.

@Test
public void testMessageWithTrailers() throws Exception {
    server.register("/hello", () -> new AbstractServerExchangeHandler<Message<HttpRequest, String>>() {

        @Override
        protected AsyncRequestConsumer<Message<HttpRequest, String>> supplyConsumer(final HttpRequest request, final EntityDetails entityDetails, final HttpContext context) throws HttpException {
            return new BasicRequestConsumer<>(entityDetails != null ? new StringAsyncEntityConsumer() : null);
        }

        @Override
        protected void handle(final Message<HttpRequest, String> requestMessage, final AsyncServerRequestHandler.ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException {
            responseTrigger.submitResponse(new BasicResponseProducer(HttpStatus.SC_OK, new DigestingEntityProducer("MD5", new StringAsyncEntityProducer("Hello back with some trailers"))), context);
        }
    });
    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.GET, createRequestURI(serverEndpoint, "/hello"));
    final DigestingEntityConsumer<String> entityConsumer = new DigestingEntityConsumer<>("MD5", new StringAsyncEntityConsumer());
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, null), new BasicResponseConsumer<>(entityConsumer), 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(200, response1.getCode());
    Assertions.assertEquals("Hello back with some trailers", result1.getBody());
    final List<Header> trailers = entityConsumer.getTrailers();
    Assertions.assertNotNull(trailers);
    Assertions.assertEquals(2, trailers.size());
    final Map<String, String> map = new HashMap<>();
    for (final Header header : trailers) {
        map.put(TextUtils.toLowerCase(header.getName()), header.getValue());
    }
    final String digest = TextUtils.toHexString(entityConsumer.getDigest());
    Assertions.assertEquals("MD5", map.get("digest-algo"));
    Assertions.assertEquals(digest, map.get("digest"));
}
Also used : Message(org.apache.hc.core5.http.Message) DigestingEntityProducer(org.apache.hc.core5.http.nio.entity.DigestingEntityProducer) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpException(org.apache.hc.core5.http.HttpException) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) DigestingEntityConsumer(org.apache.hc.core5.http.nio.entity.DigestingEntityConsumer) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) AsyncRequestConsumer(org.apache.hc.core5.http.nio.AsyncRequestConsumer) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) Header(org.apache.hc.core5.http.Header) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer) Test(org.junit.Test)

Example 4 with AsyncRequestConsumer

use of org.apache.hc.core5.http.nio.AsyncRequestConsumer in project httpcomponents-core by apache.

the class AsyncServerFilterExample 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 HttpAsyncServer server = AsyncServerBootstrap.bootstrap().setIOReactorConfig(config).replaceFilter(StandardFilter.EXPECT_CONTINUE.name(), new AbstractAsyncServerAuthFilter<String>(true) {

        @Override
        protected String parseChallengeResponse(final String authorizationValue, final HttpContext context) throws HttpException {
            return authorizationValue;
        }

        @Override
        protected boolean authenticate(final String challengeResponse, final URIAuthority authority, final String requestUri, final HttpContext context) {
            return "let me pass".equals(challengeResponse);
        }

        @Override
        protected String generateChallenge(final String challengeResponse, final URIAuthority authority, final String requestUri, final HttpContext context) {
            return "who goes there?";
        }
    }).addFilterFirst("my-filter", (request, entityDetails, context, responseTrigger, chain) -> {
        if (request.getRequestUri().equals("/back-door")) {
            responseTrigger.submitResponse(new BasicHttpResponse(HttpStatus.SC_OK), AsyncEntityProducers.create("Welcome"));
            return null;
        }
        return chain.proceed(request, entityDetails, context, new AsyncFilterChain.ResponseTrigger() {

            @Override
            public void sendInformation(final HttpResponse response) throws HttpException, IOException {
                responseTrigger.sendInformation(response);
            }

            @Override
            public void submitResponse(final HttpResponse response, final AsyncEntityProducer entityProducer) throws HttpException, IOException {
                response.addHeader("X-Filter", "My-Filter");
                responseTrigger.submitResponse(response, entityProducer);
            }

            @Override
            public void pushPromise(final HttpRequest promise, final AsyncPushProducer responseProducer) throws HttpException, IOException {
                responseTrigger.pushPromise(promise, responseProducer);
            }
        });
    }).register("*", new AsyncServerRequestHandler<Message<HttpRequest, String>>() {

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

        @Override
        public void handle(final Message<HttpRequest, String> requestMessage, final ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException {
            // do something useful
            responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_OK).setEntity("Hello").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.MAX_VALUE);
}
Also used : URIAuthority(org.apache.hc.core5.net.URIAuthority) Message(org.apache.hc.core5.http.Message) BasicRequestConsumer(org.apache.hc.core5.http.nio.support.BasicRequestConsumer) InetSocketAddress(java.net.InetSocketAddress) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) AsyncFilterChain(org.apache.hc.core5.http.nio.AsyncFilterChain) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpException(org.apache.hc.core5.http.HttpException) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) AsyncPushProducer(org.apache.hc.core5.http.nio.AsyncPushProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) IOException(java.io.IOException) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) AbstractAsyncServerAuthFilter(org.apache.hc.core5.http.nio.support.AbstractAsyncServerAuthFilter)

Example 5 with AsyncRequestConsumer

use of org.apache.hc.core5.http.nio.AsyncRequestConsumer in project httpcomponents-core by apache.

the class AsyncFileServerExample method main.

/**
 * Example command line args: {@code "c:\temp" 8080}
 */
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 = AsyncServerBootstrap.bootstrap().setIOReactorConfig(config).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()) {
                final String msg = "File " + file.getPath() + " not found";
                println(msg);
                responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_NOT_FOUND).setEntity("<html><body><h1>" + msg + "</h1></body></html>", ContentType.TEXT_HTML).build(), context);
            } else if (!file.canRead() || file.isDirectory()) {
                final String msg = "Cannot read file " + file.getPath();
                println(msg);
                responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_FORBIDDEN).setEntity("<html><body><h1>" + msg + "</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();
                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(() -> {
        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();
    println("Listening on " + listenerEndpoint.getAddress());
    server.awaitShutdown(TimeValue.MAX_VALUE);
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) ProtocolException(org.apache.hc.core5.http.ProtocolException) Message(org.apache.hc.core5.http.Message) ContentType(org.apache.hc.core5.http.ContentType) BasicRequestConsumer(org.apache.hc.core5.http.nio.support.BasicRequestConsumer) InetSocketAddress(java.net.InetSocketAddress) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) URISyntaxException(java.net.URISyntaxException) EndpointDetails(org.apache.hc.core5.http.EndpointDetails) URI(java.net.URI) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) 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) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) File(java.io.File)

Aggregations

InetSocketAddress (java.net.InetSocketAddress)6 EntityDetails (org.apache.hc.core5.http.EntityDetails)6 HttpRequest (org.apache.hc.core5.http.HttpRequest)6 Message (org.apache.hc.core5.http.Message)6 AsyncServerRequestHandler (org.apache.hc.core5.http.nio.AsyncServerRequestHandler)6 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)6 BasicRequestConsumer (org.apache.hc.core5.http.nio.support.BasicRequestConsumer)4 ListenerEndpoint (org.apache.hc.core5.reactor.ListenerEndpoint)4 IOException (java.io.IOException)3 HttpException (org.apache.hc.core5.http.HttpException)3 HttpResponse (org.apache.hc.core5.http.HttpResponse)3 HttpAsyncServer (org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer)3 DiscardingEntityConsumer (org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer)3 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)3 IOReactorConfig (org.apache.hc.core5.reactor.IOReactorConfig)3 File (java.io.File)2 InterruptedIOException (java.io.InterruptedIOException)2 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 HashMap (java.util.HashMap)2