Search in sources :

Example 66 with BasicResponseConsumer

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

the class H2IntegrationTest method testSlowResponseProducer.

@Test
public void testSlowResponseProducer() throws Exception {
    server.register("*", () -> new AbstractClassicServerExchangeHandler(2048, Executors.newSingleThreadExecutor()) {

        @Override
        protected void handle(final HttpRequest request, final InputStream requestStream, final HttpResponse response, final OutputStream responseStream, final HttpContext context) throws IOException, HttpException {
            if (!"/hello".equals(request.getPath())) {
                response.setCode(HttpStatus.SC_NOT_FOUND);
                return;
            }
            if (!Method.POST.name().equalsIgnoreCase(request.getMethod())) {
                response.setCode(HttpStatus.SC_NOT_IMPLEMENTED);
                return;
            }
            if (requestStream == null) {
                return;
            }
            final Header h1 = request.getFirstHeader(HttpHeaders.CONTENT_TYPE);
            final ContentType contentType = h1 != null ? ContentType.parse(h1.getValue()) : null;
            final Charset charset = ContentType.getCharset(contentType, StandardCharsets.US_ASCII);
            response.setCode(HttpStatus.SC_OK);
            response.setHeader(h1);
            try (final BufferedReader reader = new BufferedReader(new InputStreamReader(requestStream, charset));
                final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(responseStream, charset))) {
                try {
                    String l;
                    int count = 0;
                    while ((l = reader.readLine()) != null) {
                        writer.write(l);
                        writer.write("\r\n");
                        count++;
                        if (count % 500 == 0) {
                            Thread.sleep(500);
                        }
                    }
                    writer.flush();
                } catch (final InterruptedException ex) {
                    Thread.currentThread().interrupt();
                    throw new InterruptedIOException(ex.getMessage());
                }
            }
        }
    });
    final InetSocketAddress serverEndpoint = server.start();
    client.start(H2Config.custom().setInitialWindowSize(512).build());
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final HttpRequest request1 = new BasicHttpRequest(Method.POST, createRequestURI(serverEndpoint, "/hello"));
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, new MultiLineEntityProducer("0123456789abcd", 2000)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
    final Message<HttpResponse, String> result1 = future1.get(LONG_TIMEOUT.getDuration(), LONG_TIMEOUT.getTimeUnit());
    Assertions.assertNotNull(result1);
    final HttpResponse response1 = result1.getHead();
    Assertions.assertNotNull(response1);
    Assertions.assertEquals(200, response1.getCode());
    final String s1 = result1.getBody();
    Assertions.assertNotNull(s1);
    final StringTokenizer t1 = new StringTokenizer(s1, "\r\n");
    while (t1.hasMoreTokens()) {
        Assertions.assertEquals("0123456789abcd", t1.nextToken());
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) ContentType(org.apache.hc.core5.http.ContentType) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) OutputStream(java.io.OutputStream) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) BufferedWriter(java.io.BufferedWriter) 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) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) Charset(java.nio.charset.Charset) AbstractClassicServerExchangeHandler(org.apache.hc.core5.http.nio.support.classic.AbstractClassicServerExchangeHandler) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) StringTokenizer(java.util.StringTokenizer) Header(org.apache.hc.core5.http.Header) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) Test(org.junit.Test)

Example 67 with BasicResponseConsumer

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

the class H2IntegrationTest method testPush.

@Test
public void testPush() throws Exception {
    final InetSocketAddress serverEndpoint = server.start();
    server.register("/hello", () -> new MessageExchangeHandler<Void>(new DiscardingEntityConsumer<>()) {

        @Override
        protected void handle(final Message<HttpRequest, Void> request, final AsyncServerRequestHandler.ResponseTrigger responseTrigger, final HttpContext context) throws IOException, HttpException {
            responseTrigger.pushPromise(new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/stuff")), context, new BasicPushProducer(new MultiLineEntityProducer("Pushing lots of stuff", 500)));
            responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_OK).setEntity("Hi there", ContentType.TEXT_PLAIN).build(), context);
        }
    });
    client.start(H2Config.custom().setPushEnabled(true).build());
    final BlockingQueue<Message<HttpResponse, String>> pushMessageQueue = new LinkedBlockingDeque<>();
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(Method.GET, createRequestURI(serverEndpoint, "/hello")), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), (request, context) -> new AbstractAsyncPushHandler<Message<HttpResponse, String>>(new BasicResponseConsumer<>(new StringAsyncEntityConsumer())) {

        @Override
        protected void handleResponse(final HttpRequest promise, final Message<HttpResponse, String> responseMessage) throws IOException, HttpException {
            try {
                pushMessageQueue.put(responseMessage);
            } catch (final InterruptedException ex) {
                Thread.currentThread().interrupt();
                throw new InterruptedIOException(ex.getMessage());
            }
        }
    }, null, null);
    final Message<HttpResponse, String> result1 = future1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    Assertions.assertNotNull(result1);
    final HttpResponse response1 = result1.getHead();
    final String entity1 = result1.getBody();
    Assertions.assertNotNull(response1);
    Assertions.assertEquals(200, response1.getCode());
    Assertions.assertEquals("Hi there", entity1);
    final Message<HttpResponse, String> result2 = pushMessageQueue.poll(5, TimeUnit.SECONDS);
    Assertions.assertNotNull(result2);
    final HttpResponse response2 = result2.getHead();
    final String entity2 = result2.getBody();
    Assertions.assertEquals(200, response2.getCode());
    Assertions.assertNotNull(entity2);
    final StringTokenizer t1 = new StringTokenizer(entity2, "\r\n");
    while (t1.hasMoreTokens()) {
        Assertions.assertEquals("Pushing lots of stuff", t1.nextToken());
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) 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) BasicPushProducer(org.apache.hc.core5.http.nio.support.BasicPushProducer) 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) DiscardingEntityConsumer(org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) StringTokenizer(java.util.StringTokenizer) Test(org.junit.Test)

Example 68 with BasicResponseConsumer

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

the class H2IntegrationTest method testHeaderTooLarge.

@Test
public void testHeaderTooLarge() throws Exception {
    server.register("/hello", () -> new SingleLineResponseHandler("Hi there"));
    final InetSocketAddress serverEndpoint = server.start(H2Config.custom().setMaxHeaderListSize(100).build());
    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"));
    request1.setHeader("big-f-header", "1234567890123456789012345678901234567890123456789012345678901234567890" + "1234567890123456789012345678901234567890");
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, null), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), 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(431, response1.getCode());
    Assertions.assertEquals("Maximum header list size exceeded", result1.getBody());
}
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) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) Test(org.junit.Test)

Example 69 with BasicResponseConsumer

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

the class H2IntegrationTest method testConnectionPing.

@Test
public void testConnectionPing() throws Exception {
    server.register("/hello", () -> new SingleLineResponseHandler("Hi there"));
    final InetSocketAddress serverEndpoint = server.start();
    client.start();
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final int n = 10;
    final CountDownLatch latch = new CountDownLatch(n);
    final AtomicInteger count = new AtomicInteger(0);
    for (int i = 0; i < n; i++) {
        streamEndpoint.execute(new BasicRequestProducer(Method.GET, createRequestURI(serverEndpoint, "/hello")), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
        streamEndpoint.execute(new PingCommand(new BasicPingHandler(result -> {
            if (result) {
                count.incrementAndGet();
            }
            latch.countDown();
        })), Command.Priority.NORMAL);
    }
    Assertions.assertTrue(latch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit()));
    Assertions.assertEquals(n, count.get());
}
Also used : StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) BasicPingHandler(org.apache.hc.core5.http2.nio.support.BasicPingHandler) CountDownLatch(java.util.concurrent.CountDownLatch) PingCommand(org.apache.hc.core5.http2.nio.command.PingCommand) Test(org.junit.Test)

Example 70 with BasicResponseConsumer

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

the class H2IntegrationTest method testRequestWithInvalidConnectionHeader.

@Test
public void testRequestWithInvalidConnectionHeader() throws Exception {
    server.register("/hello", () -> new SingleLineResponseHandler("Hi there"));
    final InetSocketAddress serverEndpoint = server.start();
    client.start();
    final Future<IOSession> sessionFuture = client.requestSession(new HttpHost("localhost", serverEndpoint.getPort()), TIMEOUT, null);
    final IOSession session = sessionFuture.get();
    final ClientSessionEndpoint streamEndpoint = new ClientSessionEndpoint(session);
    final HttpRequest request = new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/hello"));
    request.addHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE);
    final HttpCoreContext coreContext = HttpCoreContext.create();
    final Future<Message<HttpResponse, String>> future = streamEndpoint.execute(new BasicRequestProducer(request, null), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), coreContext, null);
    final ExecutionException exception = Assertions.assertThrows(ExecutionException.class, () -> future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit()));
    assertThat(exception.getCause(), CoreMatchers.instanceOf(ProtocolException.class));
    final EndpointDetails endpointDetails = coreContext.getEndpointDetails();
    assertThat(endpointDetails.getRequestCount(), CoreMatchers.equalTo(0L));
}
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) ProtocolException(org.apache.hc.core5.http.ProtocolException) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) EndpointDetails(org.apache.hc.core5.http.EndpointDetails) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpHost(org.apache.hc.core5.http.HttpHost) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) IOSession(org.apache.hc.core5.reactor.IOSession) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Aggregations

StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)94 Message (org.apache.hc.core5.http.Message)93 HttpResponse (org.apache.hc.core5.http.HttpResponse)92 BasicRequestProducer (org.apache.hc.core5.http.nio.support.BasicRequestProducer)86 InetSocketAddress (java.net.InetSocketAddress)84 Test (org.junit.Test)73 HttpRequest (org.apache.hc.core5.http.HttpRequest)41 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)40 HttpHost (org.apache.hc.core5.http.HttpHost)38 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)36 StringAsyncEntityProducer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer)30 IOException (java.io.IOException)27 ListenerEndpoint (org.apache.hc.core5.reactor.ListenerEndpoint)26 HttpException (org.apache.hc.core5.http.HttpException)25 BasicResponseConsumer (org.apache.hc.core5.http.nio.support.BasicResponseConsumer)23 InterruptedIOException (java.io.InterruptedIOException)22 Header (org.apache.hc.core5.http.Header)20 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)20 Future (java.util.concurrent.Future)18 ExecutionException (java.util.concurrent.ExecutionException)17