Search in sources :

Example 16 with AsyncEntityProducer

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

the class H2CompatibilityTest method executeHttpBin.

void executeHttpBin(final HttpHost target) throws Exception {
    {
        System.out.println("*** httpbin.org HTTP/1.1 simple request execution ***");
        final List<Message<HttpRequest, AsyncEntityProducer>> requestMessages = Arrays.asList(new Message<>(new BasicHttpRequest(Method.GET, target, "/headers"), null), new Message<>(new BasicHttpRequest(Method.POST, target, "/anything"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), new Message<>(new BasicHttpRequest(Method.PUT, target, "/anything"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), new Message<>(new BasicHttpRequest(Method.GET, target, "/drip"), null), new Message<>(new BasicHttpRequest(Method.GET, target, "/bytes/20000"), null), new Message<>(new BasicHttpRequest(Method.GET, target, "/delay/2"), null), new Message<>(new BasicHttpRequest(Method.POST, target, "/delay/2"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), new Message<>(new BasicHttpRequest(Method.PUT, target, "/delay/2"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)));
        for (final Message<HttpRequest, AsyncEntityProducer> message : requestMessages) {
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            final HttpRequest request = message.getHead();
            final AsyncEntityProducer entityProducer = message.getBody();
            client.execute(new BasicRequestProducer(request, entityProducer), new BasicResponseConsumer<>(new StringAsyncEntityConsumer(CharCodingConfig.custom().setCharset(StandardCharsets.US_ASCII).setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.REPLACE).build())), TIMEOUT, new FutureCallback<Message<HttpResponse, String>>() {

                @Override
                public void completed(final Message<HttpResponse, String> responseMessage) {
                    final HttpResponse response = responseMessage.getHead();
                    final int code = response.getCode();
                    if (code == HttpStatus.SC_OK) {
                        logResult(TestResult.OK, target, request, response, Objects.toString(response.getFirstHeader("server")));
                    } else {
                        logResult(TestResult.NOK, target, request, response, "(status " + code + ")");
                    }
                    countDownLatch.countDown();
                }

                @Override
                public void failed(final Exception ex) {
                    logResult(TestResult.NOK, target, request, null, "(" + ex.getMessage() + ")");
                    countDownLatch.countDown();
                }

                @Override
                public void cancelled() {
                    logResult(TestResult.NOK, target, request, null, "(cancelled)");
                    countDownLatch.countDown();
                }
            });
            if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
                logResult(TestResult.NOK, target, null, null, "(httpbin.org tests failed to complete in time)");
            }
        }
    }
    {
        System.out.println("*** httpbin.org HTTP/1.1 pipelined request execution ***");
        final Future<AsyncClientEndpoint> connectFuture = client.connect(target, TIMEOUT);
        final AsyncClientEndpoint streamEndpoint = connectFuture.get();
        final int n = 10;
        final CountDownLatch countDownLatch = new CountDownLatch(n);
        for (int i = 0; i < n; i++) {
            final HttpRequest request;
            final AsyncEntityProducer entityProducer;
            if (i % 2 == 0) {
                request = new BasicHttpRequest(Method.GET, target, "/headers");
                entityProducer = null;
            } else {
                request = new BasicHttpRequest(Method.POST, target, "/anything");
                entityProducer = new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN);
            }
            streamEndpoint.execute(new BasicRequestProducer(request, entityProducer), new BasicResponseConsumer<>(new StringAsyncEntityConsumer(CharCodingConfig.custom().setCharset(StandardCharsets.US_ASCII).setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.REPLACE).build())), new FutureCallback<Message<HttpResponse, String>>() {

                @Override
                public void completed(final Message<HttpResponse, String> responseMessage) {
                    final HttpResponse response = responseMessage.getHead();
                    final int code = response.getCode();
                    if (code == HttpStatus.SC_OK) {
                        logResult(TestResult.OK, target, request, response, "pipelined / " + response.getFirstHeader("server"));
                    } else {
                        logResult(TestResult.NOK, target, request, response, "(status " + code + ")");
                    }
                    countDownLatch.countDown();
                }

                @Override
                public void failed(final Exception ex) {
                    logResult(TestResult.NOK, target, request, null, "(" + ex.getMessage() + ")");
                    countDownLatch.countDown();
                }

                @Override
                public void cancelled() {
                    logResult(TestResult.NOK, target, request, null, "(cancelled)");
                    countDownLatch.countDown();
                }
            });
        }
        if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
            logResult(TestResult.NOK, target, null, null, "(httpbin.org tests failed to complete in time)");
        }
    }
}
Also used : BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Message(org.apache.hc.core5.http.Message) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) 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) CountDownLatch(java.util.concurrent.CountDownLatch) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) TimeoutException(java.util.concurrent.TimeoutException) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) Future(java.util.concurrent.Future) List(java.util.List) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback)

Example 17 with AsyncEntityProducer

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

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

the class TestFileAsyncEntityProducer method testTextContent.

@Test
public void testTextContent() throws Exception {
    final AsyncEntityProducer producer = new FileEntityProducer(tempFile, ContentType.TEXT_PLAIN);
    Assertions.assertEquals(6, producer.getContentLength());
    Assertions.assertEquals(ContentType.TEXT_PLAIN.toString(), producer.getContentType());
    Assertions.assertNull(producer.getContentEncoding());
    final WritableByteChannelMock byteChannel = new WritableByteChannelMock(1024);
    final DataStreamChannel streamChannel = new BasicDataStreamChannel(byteChannel);
    producer.produce(streamChannel);
    producer.produce(streamChannel);
    Assertions.assertFalse(byteChannel.isOpen());
    Assertions.assertEquals("abcdef", byteChannel.dump(StandardCharsets.US_ASCII));
}
Also used : AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) WritableByteChannelMock(org.apache.hc.core5.http.WritableByteChannelMock) BasicDataStreamChannel(org.apache.hc.core5.http.nio.BasicDataStreamChannel) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) BasicDataStreamChannel(org.apache.hc.core5.http.nio.BasicDataStreamChannel) Test(org.junit.jupiter.api.Test)

Example 19 with AsyncEntityProducer

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

the class TestPathAsyncEntityProducer method testTextContentRepeatable.

@Test
public void testTextContentRepeatable() throws Exception {
    final Path tempPath = tempFile.toPath();
    final AsyncEntityProducer producer = new PathEntityProducer(tempPath, ContentType.TEXT_PLAIN, StandardOpenOption.READ);
    Assertions.assertEquals(6, producer.getContentLength());
    Assertions.assertEquals(ContentType.TEXT_PLAIN.toString(), producer.getContentType());
    Assertions.assertNull(producer.getContentEncoding());
    for (int i = 0; i < 3; i++) {
        final WritableByteChannelMock byteChannel = new WritableByteChannelMock(1024);
        final DataStreamChannel streamChannel = new BasicDataStreamChannel(byteChannel);
        producer.produce(streamChannel);
        producer.produce(streamChannel);
        Assertions.assertFalse(byteChannel.isOpen());
        Assertions.assertEquals("abcdef", byteChannel.dump(StandardCharsets.US_ASCII));
        producer.releaseResources();
    }
}
Also used : Path(java.nio.file.Path) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) WritableByteChannelMock(org.apache.hc.core5.http.WritableByteChannelMock) BasicDataStreamChannel(org.apache.hc.core5.http.nio.BasicDataStreamChannel) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) BasicDataStreamChannel(org.apache.hc.core5.http.nio.BasicDataStreamChannel) Test(org.junit.jupiter.api.Test)

Example 20 with AsyncEntityProducer

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

the class TestStringAsyncEntityProducer method testTextContentRepeatable.

@Test
public void testTextContentRepeatable() throws Exception {
    final AsyncEntityProducer producer = new StringAsyncEntityProducer("abc", ContentType.TEXT_PLAIN);
    Assertions.assertEquals(-1, producer.getContentLength());
    Assertions.assertEquals(ContentType.TEXT_PLAIN.toString(), producer.getContentType());
    Assertions.assertNull(producer.getContentEncoding());
    for (int i = 0; i < 3; i++) {
        final WritableByteChannelMock byteChannel = new WritableByteChannelMock(1024);
        final DataStreamChannel streamChannel = new BasicDataStreamChannel(byteChannel);
        producer.produce(streamChannel);
        Assertions.assertFalse(byteChannel.isOpen());
        Assertions.assertEquals("abc", byteChannel.dump(StandardCharsets.US_ASCII));
        producer.releaseResources();
    }
}
Also used : AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) WritableByteChannelMock(org.apache.hc.core5.http.WritableByteChannelMock) BasicDataStreamChannel(org.apache.hc.core5.http.nio.BasicDataStreamChannel) BasicDataStreamChannel(org.apache.hc.core5.http.nio.BasicDataStreamChannel) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) Test(org.junit.jupiter.api.Test)

Aggregations

AsyncEntityProducer (org.apache.hc.core5.http.nio.AsyncEntityProducer)27 DataStreamChannel (org.apache.hc.core5.http.nio.DataStreamChannel)18 Test (org.junit.jupiter.api.Test)16 WritableByteChannelMock (org.apache.hc.core5.http.WritableByteChannelMock)14 BasicDataStreamChannel (org.apache.hc.core5.http.nio.BasicDataStreamChannel)14 IOException (java.io.IOException)8 HttpException (org.apache.hc.core5.http.HttpException)8 HttpResponse (org.apache.hc.core5.http.HttpResponse)8 HttpRequest (org.apache.hc.core5.http.HttpRequest)7 Header (org.apache.hc.core5.http.Header)6 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)6 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)6 EntityDetails (org.apache.hc.core5.http.EntityDetails)5 ByteBuffer (java.nio.ByteBuffer)4 Path (java.nio.file.Path)4 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)4 List (java.util.List)3 AsyncDataConsumer (org.apache.hc.core5.http.nio.AsyncDataConsumer)3 AsyncServerExchangeHandler (org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)3 CapacityChannel (org.apache.hc.core5.http.nio.CapacityChannel)3