Search in sources :

Example 1 with EntityDetails

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

the class BenchmarkWorker method createResponseConsumer.

private AsyncResponseConsumer<Void> createResponseConsumer() {
    return new AsyncResponseConsumer<Void>() {

        volatile int status;

        volatile Charset charset;

        final AtomicLong contentLength = new AtomicLong();

        final AtomicReference<FutureCallback<Void>> resultCallbackRef = new AtomicReference<>();

        @Override
        public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext context, final FutureCallback<Void> resultCallback) throws HttpException, IOException {
            status = response.getCode();
            resultCallbackRef.set(resultCallback);
            stats.setVersion(response.getVersion());
            final Header serverHeader = response.getFirstHeader(HttpHeaders.SERVER);
            if (serverHeader != null) {
                stats.setServerName(serverHeader.getValue());
            }
            if (config.getVerbosity() >= 2) {
                System.out.println(response.getCode());
            }
            if (entityDetails != null) {
                if (config.getVerbosity() >= 6) {
                    if (entityDetails.getContentType() != null) {
                        final ContentType contentType = ContentType.parseLenient(entityDetails.getContentType());
                        charset = ContentType.getCharset(contentType, null);
                    }
                }
            } else {
                streamEnd(null);
            }
        }

        @Override
        public void informationResponse(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
        }

        @Override
        public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
            capacityChannel.update(Integer.MAX_VALUE);
        }

        @Override
        public void consume(final ByteBuffer src) throws IOException {
            final int n = src.remaining();
            contentLength.addAndGet(n);
            stats.incTotalContentLength(n);
            if (config.getVerbosity() >= 6) {
                final CharsetDecoder decoder = (charset != null ? charset : StandardCharsets.US_ASCII).newDecoder();
                System.out.print(decoder.decode(src));
            }
        }

        @Override
        public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
            if (status == HttpStatus.SC_OK) {
                stats.incSuccessCount();
            } else {
                stats.incFailureCount();
            }
            stats.setContentLength(contentLength.get());
            final FutureCallback<Void> resultCallback = resultCallbackRef.getAndSet(null);
            if (resultCallback != null) {
                resultCallback.completed(null);
            }
            if (config.getVerbosity() >= 6) {
                System.out.println();
                System.out.println();
            }
        }

        @Override
        public void failed(final Exception cause) {
            stats.incFailureCount();
            final FutureCallback<Void> resultCallback = resultCallbackRef.getAndSet(null);
            if (resultCallback != null) {
                resultCallback.failed(cause);
            }
            if (config.getVerbosity() >= 1) {
                System.out.println("HTTP response error: " + cause.getMessage());
            }
        }

        @Override
        public void releaseResources() {
        }
    };
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder) ContentType(org.apache.hc.core5.http.ContentType) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) Charset(java.nio.charset.Charset) HttpResponse(org.apache.hc.core5.http.HttpResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuffer(java.nio.ByteBuffer) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) AsyncResponseConsumer(org.apache.hc.core5.http.nio.AsyncResponseConsumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) BasicHeader(org.apache.hc.core5.http.message.BasicHeader) Header(org.apache.hc.core5.http.Header) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) List(java.util.List) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback)

Example 2 with EntityDetails

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

the class EchoHandler method handleRequest.

@Override
public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
    final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK);
    responseChannel.sendResponse(response, entityDetails, context);
}
Also used : BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse)

Example 3 with EntityDetails

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

the class H2IntegrationTest method testPrematureResponse.

@Test
public void testPrematureResponse() throws Exception {
    server.register("*", new Supplier<AsyncServerExchangeHandler>() {

        @Override
        public AsyncServerExchangeHandler get() {
            return new AsyncServerExchangeHandler() {

                private final AtomicReference<AsyncResponseProducer> responseProducer = new AtomicReference<>();

                @Override
                public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
                    capacityChannel.update(Integer.MAX_VALUE);
                }

                @Override
                public void consume(final ByteBuffer src) throws IOException {
                }

                @Override
                public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
                }

                @Override
                public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
                    final AsyncResponseProducer producer;
                    final Header h = request.getFirstHeader("password");
                    if (h != null && "secret".equals(h.getValue())) {
                        producer = new BasicResponseProducer(HttpStatus.SC_OK, "All is well");
                    } else {
                        producer = new BasicResponseProducer(HttpStatus.SC_UNAUTHORIZED, "You shall not pass");
                    }
                    responseProducer.set(producer);
                    producer.sendResponse(responseChannel, context);
                }

                @Override
                public int available() {
                    final AsyncResponseProducer producer = this.responseProducer.get();
                    return producer.available();
                }

                @Override
                public void produce(final DataStreamChannel channel) throws IOException {
                    final AsyncResponseProducer producer = this.responseProducer.get();
                    producer.produce(channel);
                }

                @Override
                public void failed(final Exception cause) {
                }

                @Override
                public void releaseResources() {
                }
            };
        }
    });
    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.POST, createRequestURI(serverEndpoint, "/echo"));
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, new MultiLineEntityProducer("0123456789abcdef", 5000)), 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(HttpStatus.SC_UNAUTHORIZED, response1.getCode());
    Assertions.assertNotNull("You shall not pass", result1.getBody());
}
Also used : Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpException(org.apache.hc.core5.http.HttpException) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) URISyntaxException(java.net.URISyntaxException) H2StreamResetException(org.apache.hc.core5.http2.H2StreamResetException) HttpException(org.apache.hc.core5.http.HttpException) ProtocolException(org.apache.hc.core5.http.ProtocolException) Header(org.apache.hc.core5.http.Header) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer) Test(org.junit.Test)

Example 4 with EntityDetails

use of org.apache.hc.core5.http.EntityDetails 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 5 with EntityDetails

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

the class ReactiveEchoProcessor method processRequest.

@Override
public void processRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context, final Publisher<ByteBuffer> requestBody, final Callback<Publisher<ByteBuffer>> responseBodyFuture) throws HttpException, IOException {
    if (new BasicHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE).equals(request.getHeader(HttpHeaders.EXPECT))) {
        responseChannel.sendInformation(new BasicHttpResponse(100), context);
    }
    responseChannel.sendResponse(new BasicHttpResponse(200), new BasicEntityDetails(-1, ContentType.APPLICATION_OCTET_STREAM), context);
    responseBodyFuture.execute(requestBody);
}
Also used : BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) BasicEntityDetails(org.apache.hc.core5.http.impl.BasicEntityDetails) BasicHeader(org.apache.hc.core5.http.message.BasicHeader)

Aggregations

EntityDetails (org.apache.hc.core5.http.EntityDetails)32 HttpResponse (org.apache.hc.core5.http.HttpResponse)29 HttpException (org.apache.hc.core5.http.HttpException)28 HttpRequest (org.apache.hc.core5.http.HttpRequest)25 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)25 IOException (java.io.IOException)24 Header (org.apache.hc.core5.http.Header)21 ProtocolException (org.apache.hc.core5.http.ProtocolException)19 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)18 ByteBuffer (java.nio.ByteBuffer)17 InetSocketAddress (java.net.InetSocketAddress)16 ProtocolVersion (org.apache.hc.core5.http.ProtocolVersion)16 CapacityChannel (org.apache.hc.core5.http.nio.CapacityChannel)15 DataStreamChannel (org.apache.hc.core5.http.nio.DataStreamChannel)14 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)11 IOReactorConfig (org.apache.hc.core5.reactor.IOReactorConfig)11 Message (org.apache.hc.core5.http.Message)10 AsyncServerExchangeHandler (org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)10 URI (java.net.URI)9 URISyntaxException (java.net.URISyntaxException)9