Search in sources :

Example 1 with SimpleHttpRequest

use of org.apache.hc.client5.http.async.methods.SimpleHttpRequest in project metrics by dropwizard.

the class InstrumentedHttpAsyncClientsTest method registersExpectedMetricsGivenNameStrategy.

@Test
public void registersExpectedMetricsGivenNameStrategy() throws Exception {
    client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build();
    client.start();
    final SimpleHttpRequest request = SimpleHttpRequests.get("http://localhost:" + httpServer.getAddress().getPort() + "/");
    final String metricName = "some.made.up.metric.name";
    httpServer.createContext("/", exchange -> {
        exchange.sendResponseHeaders(200, 0L);
        exchange.setStreams(null, null);
        exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII));
        exchange.close();
    });
    httpServer.start();
    when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName);
    final Future<SimpleHttpResponse> responseFuture = client.execute(request, new FutureCallback<SimpleHttpResponse>() {

        @Override
        public void completed(SimpleHttpResponse result) {
            assertThat(result.getBodyText()).isEqualTo("TEST");
        }

        @Override
        public void failed(Exception ex) {
            fail();
        }

        @Override
        public void cancelled() {
            fail();
        }
    });
    responseFuture.get(1L, TimeUnit.SECONDS);
    verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class));
}
Also used : SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) Timer(com.codahale.metrics.Timer) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) IOException(java.io.IOException) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Example 2 with SimpleHttpRequest

use of org.apache.hc.client5.http.async.methods.SimpleHttpRequest in project metrics by dropwizard.

the class InstrumentedHttpAsyncClientsTest method usesCustomClientConnectionManager.

@Test
public void usesCustomClientConnectionManager() throws Exception {
    try (PoolingAsyncClientConnectionManager clientConnectionManager = spy(new PoolingAsyncClientConnectionManager())) {
        client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy, clientConnectionManager).disableAutomaticRetries().build();
        client.start();
        final SimpleHttpRequest request = SimpleHttpRequests.get("http://localhost:" + httpServer.getAddress().getPort() + "/");
        final String metricName = "some.made.up.metric.name";
        httpServer.createContext("/", exchange -> {
            exchange.sendResponseHeaders(200, 0L);
            exchange.setStreams(null, null);
            exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII));
            exchange.close();
        });
        httpServer.start();
        when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName);
        final Future<SimpleHttpResponse> responseFuture = client.execute(request, new FutureCallback<SimpleHttpResponse>() {

            @Override
            public void completed(SimpleHttpResponse result) {
                assertThat(result.getCode()).isEqualTo(200);
            }

            @Override
            public void failed(Exception ex) {
                fail();
            }

            @Override
            public void cancelled() {
                fail();
            }
        });
        responseFuture.get(1L, TimeUnit.SECONDS);
        verify(clientConnectionManager, atLeastOnce()).connect(any(), any(), any(), any(), any(), any());
    }
}
Also used : SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) PoolingAsyncClientConnectionManager(org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) IOException(java.io.IOException) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Example 3 with SimpleHttpRequest

use of org.apache.hc.client5.http.async.methods.SimpleHttpRequest in project metrics by dropwizard.

the class InstrumentedHttpAsyncClientsTest method registersExpectedExceptionMetrics.

@Test
public void registersExpectedExceptionMetrics() throws Exception {
    client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build();
    client.start();
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final SimpleHttpRequest request = SimpleHttpRequests.get("http://localhost:" + httpServer.getAddress().getPort() + "/");
    final String requestMetricName = "request";
    final String exceptionMetricName = "exception";
    httpServer.createContext("/", HttpExchange::close);
    httpServer.start();
    when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(requestMetricName);
    when(metricNameStrategy.getNameFor(any(), any(Exception.class))).thenReturn(exceptionMetricName);
    try {
        final Future<SimpleHttpResponse> responseFuture = client.execute(request, new FutureCallback<SimpleHttpResponse>() {

            @Override
            public void completed(SimpleHttpResponse result) {
                fail();
            }

            @Override
            public void failed(Exception ex) {
                countDownLatch.countDown();
            }

            @Override
            public void cancelled() {
                fail();
            }
        });
        countDownLatch.await(5, TimeUnit.SECONDS);
        responseFuture.get(5, TimeUnit.SECONDS);
        fail();
    } catch (ExecutionException e) {
        assertThat(e).hasCauseInstanceOf(ConnectionClosedException.class);
        await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> assertThat(metricRegistry.getMeters()).containsKey("exception"));
    }
}
Also used : SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpExchange(com.sun.net.httpserver.HttpExchange) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) CountDownLatch(java.util.concurrent.CountDownLatch) ExecutionException(java.util.concurrent.ExecutionException) IOException(java.io.IOException) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) ExecutionException(java.util.concurrent.ExecutionException) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) Test(org.junit.Test)

Example 4 with SimpleHttpRequest

use of org.apache.hc.client5.http.async.methods.SimpleHttpRequest in project feign by OpenFeign.

the class AsyncApacheHttp5Client method toClassicHttpRequest.

SimpleHttpRequest toClassicHttpRequest(Request request, Request.Options options) {
    final SimpleHttpRequest httpRequest = new SimpleHttpRequest(request.httpMethod().name(), request.url());
    // request headers
    boolean hasAcceptHeader = false;
    for (final Map.Entry<String, Collection<String>> headerEntry : request.headers().entrySet()) {
        final String headerName = headerEntry.getKey();
        if (headerName.equalsIgnoreCase(ACCEPT_HEADER_NAME)) {
            hasAcceptHeader = true;
        }
        if (headerName.equalsIgnoreCase(Util.CONTENT_LENGTH)) {
            // doesn't like us to set it as well.
            continue;
        }
        for (final String headerValue : headerEntry.getValue()) {
            httpRequest.addHeader(headerName, headerValue);
        }
    }
    // some servers choke on the default accept string, so we'll set it to anything
    if (!hasAcceptHeader) {
        httpRequest.addHeader(ACCEPT_HEADER_NAME, "*/*");
    }
    // request body
    // final Body requestBody = request.requestBody();
    final byte[] data = request.body();
    if (data != null) {
        httpRequest.setBody(data, getContentType(request));
    }
    return httpRequest;
}
Also used : SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest)

Example 5 with SimpleHttpRequest

use of org.apache.hc.client5.http.async.methods.SimpleHttpRequest in project feign by OpenFeign.

the class AsyncApacheHttp5Client method execute.

@Override
public CompletableFuture<Response> execute(Request request, Options options, Optional<HttpClientContext> requestContext) {
    final SimpleHttpRequest httpUriRequest = toClassicHttpRequest(request, options);
    final CompletableFuture<Response> result = new CompletableFuture<>();
    final FutureCallback<SimpleHttpResponse> callback = new FutureCallback<SimpleHttpResponse>() {

        @Override
        public void completed(SimpleHttpResponse httpResponse) {
            result.complete(toFeignResponse(httpResponse, request));
        }

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

        @Override
        public void cancelled() {
            result.cancel(false);
        }
    };
    client.execute(httpUriRequest, configureTimeouts(options, requestContext.orElseGet(HttpClientContext::new)), callback);
    return result;
}
Also used : SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) CompletableFuture(java.util.concurrent.CompletableFuture) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback)

Aggregations

SimpleHttpRequest (org.apache.hc.client5.http.async.methods.SimpleHttpRequest)5 SimpleHttpResponse (org.apache.hc.client5.http.async.methods.SimpleHttpResponse)4 IOException (java.io.IOException)3 ExecutionException (java.util.concurrent.ExecutionException)3 ConnectionClosedException (org.apache.hc.core5.http.ConnectionClosedException)3 HttpRequest (org.apache.hc.core5.http.HttpRequest)3 Test (org.junit.Test)3 Timer (com.codahale.metrics.Timer)1 HttpExchange (com.sun.net.httpserver.HttpExchange)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 PoolingAsyncClientConnectionManager (org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager)1 HttpClientContext (org.apache.hc.client5.http.protocol.HttpClientContext)1 FutureCallback (org.apache.hc.core5.concurrent.FutureCallback)1