Search in sources :

Example 1 with AsyncResponseConsumer

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

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

the class H2MultiplexingRequester method execute.

public final <T> Future<T> execute(final AsyncRequestProducer requestProducer, final AsyncResponseConsumer<T> responseConsumer, final HandlerFactory<AsyncPushConsumer> pushHandlerFactory, final Timeout timeout, final HttpContext context, final FutureCallback<T> callback) {
    Args.notNull(requestProducer, "Request producer");
    Args.notNull(responseConsumer, "Response consumer");
    Args.notNull(timeout, "Timeout");
    final ComplexFuture<T> future = new ComplexFuture<>(callback);
    final AsyncClientExchangeHandler exchangeHandler = new BasicClientExchangeHandler<>(requestProducer, responseConsumer, new FutureContribution<T>(future) {

        @Override
        public void completed(final T result) {
            future.completed(result);
        }
    });
    execute(exchangeHandler, pushHandlerFactory, future, timeout, context != null ? context : HttpCoreContext.create());
    return future;
}
Also used : AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) BasicClientExchangeHandler(org.apache.hc.core5.http.nio.support.BasicClientExchangeHandler) ComplexFuture(org.apache.hc.core5.concurrent.ComplexFuture)

Example 3 with AsyncResponseConsumer

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

the class HttpAsyncRequester method execute.

public final <T> Future<T> execute(final AsyncRequestProducer requestProducer, final AsyncResponseConsumer<T> responseConsumer, final HandlerFactory<AsyncPushConsumer> pushHandlerFactory, final Timeout timeout, final HttpContext context, final FutureCallback<T> callback) {
    Args.notNull(requestProducer, "Request producer");
    Args.notNull(responseConsumer, "Response consumer");
    Args.notNull(timeout, "Timeout");
    final BasicFuture<T> future = new BasicFuture<>(callback);
    final AsyncClientExchangeHandler exchangeHandler = new BasicClientExchangeHandler<>(requestProducer, responseConsumer, new FutureContribution<T>(future) {

        @Override
        public void completed(final T result) {
            future.completed(result);
        }
    });
    execute(exchangeHandler, pushHandlerFactory, timeout, context != null ? context : HttpCoreContext.create());
    return future;
}
Also used : AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) BasicFuture(org.apache.hc.core5.concurrent.BasicFuture) BasicClientExchangeHandler(org.apache.hc.core5.http.nio.support.BasicClientExchangeHandler)

Example 4 with AsyncResponseConsumer

use of org.apache.hc.core5.http.nio.AsyncResponseConsumer in project skywalking-java by apache.

the class HttpAsyncClientDoExecuteInterceptor method beforeMethod.

@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable {
    AsyncResponseConsumer consumer = (AsyncResponseConsumer) allArguments[2];
    HttpContext context = (HttpContext) allArguments[4];
    FutureCallback callback = (FutureCallback) allArguments[5];
    allArguments[2] = new AsyncResponseConsumerWrapper(consumer);
    allArguments[5] = new FutureCallbackWrapper(callback);
    if (ContextManager.isActive()) {
        context.setAttribute(Constants.SKYWALKING_CONTEXT_SNAPSHOT, ContextManager.capture());
    }
}
Also used : HttpContext(org.apache.hc.core5.http.protocol.HttpContext) AsyncResponseConsumerWrapper(org.apache.skywalking.apm.plugin.httpclient.v5.wrapper.AsyncResponseConsumerWrapper) FutureCallbackWrapper(org.apache.skywalking.apm.plugin.httpclient.v5.wrapper.FutureCallbackWrapper) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback) AsyncResponseConsumer(org.apache.hc.core5.http.nio.AsyncResponseConsumer)

Example 5 with AsyncResponseConsumer

use of org.apache.hc.core5.http.nio.AsyncResponseConsumer in project httpcomponents-jackson by ok2c.

the class JsonResponseConsumerTest method testJsonErrorResponseBodyNotMatchingResponseClass.

@Test
void testJsonErrorResponseBodyNotMatchingResponseClass() throws Exception {
    String errorBody = "{\"code\": 500, \"message\": \"Unexpected internal failure\"}";
    AsyncResponseConsumer<Message<HttpResponse, RequestData>> consumer = JsonResponseConsumers.create(objectMapper, RequestData.class);
    CompletableFuture<RequestData> resultFuture = new CompletableFuture<>();
    consumer.consumeResponse(new BasicHttpResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR), new BasicEntityDetails(errorBody.length(), ContentType.APPLICATION_JSON), HttpClientContext.create(), new FutureCallback<Message<HttpResponse, RequestData>>() {

        @Override
        public void completed(Message<HttpResponse, RequestData> result) {
            // NOTE: The error body is lost, we would need a custom consumer to retrieve that. Actually
            // it might also be mapped accidentally to the response class.
            handleResponseResult(result, resultFuture);
        }

        @Override
        public void failed(Exception ex) {
            resultFuture.completeExceptionally(ex);
        }

        @Override
        public void cancelled() {
            resultFuture.cancel(false);
        }
    });
    consumer.consume(ByteBuffer.wrap(errorBody.getBytes(StandardCharsets.UTF_8)));
    consumer.streamEnd(null);
    // FAILS: consumer attempts to parse the error body as it was a successful response and throws a parsing error
    assertThat(resultFuture).hasFailedWithThrowableThat().isInstanceOf(HttpResponseException.class);
}
Also used : Message(org.apache.hc.core5.http.Message) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) HttpResponseException(org.apache.hc.client5.http.HttpResponseException) CompletableFuture(java.util.concurrent.CompletableFuture) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) BasicEntityDetails(org.apache.hc.core5.http.impl.BasicEntityDetails) Test(org.junit.jupiter.api.Test)

Aggregations

HttpResponse (org.apache.hc.core5.http.HttpResponse)7 Test (org.junit.jupiter.api.Test)5 CompletableFuture (java.util.concurrent.CompletableFuture)4 BasicEntityDetails (org.apache.hc.core5.http.impl.BasicEntityDetails)4 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)4 HttpResponseException (org.apache.hc.client5.http.HttpResponseException)3 FutureCallback (org.apache.hc.core5.concurrent.FutureCallback)3 EntityDetails (org.apache.hc.core5.http.EntityDetails)3 Message (org.apache.hc.core5.http.Message)3 AsyncResponseConsumer (org.apache.hc.core5.http.nio.AsyncResponseConsumer)3 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)3 JsonFactory (com.fasterxml.jackson.core.JsonFactory)2 IOException (java.io.IOException)2 ByteBuffer (java.nio.ByteBuffer)2 SimpleHttpRequest (org.apache.hc.client5.http.async.methods.SimpleHttpRequest)2 SimpleRequestProducer (org.apache.hc.client5.http.async.methods.SimpleRequestProducer)2 ComplexFuture (org.apache.hc.core5.concurrent.ComplexFuture)2 ContentType (org.apache.hc.core5.http.ContentType)2 HttpException (org.apache.hc.core5.http.HttpException)2 AsyncClientExchangeHandler (org.apache.hc.core5.http.nio.AsyncClientExchangeHandler)2