Search in sources :

Example 1 with SimpleHttpResponse

use of org.apache.hc.client5.http.async.methods.SimpleHttpResponse 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 SimpleHttpResponse

use of org.apache.hc.client5.http.async.methods.SimpleHttpResponse 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 SimpleHttpResponse

use of org.apache.hc.client5.http.async.methods.SimpleHttpResponse in project weicoder by wdcode.

the class HttpAsyncClient method post.

/**
 * 模拟post提交
 *
 * @param url      post提交地址
 * @param data     提交参数
 * @param callback 回调结果
 * @param charset  编码
 */
public static void post(String url, Map<String, Object> data, CallbackVoid<String> callback, String charset) {
    // 声明HttpPost
    HttpPost post = null;
    try {
        // 获得HttpPost
        post = new HttpPost(url);
        post.addHeader(new BasicHeader(HttpConstants.CONTENT_TYPE_KEY, HttpConstants.CONTENT_TYPE_VAL));
        // 如果参数列表为空 data为空map
        if (U.E.isNotEmpty(data)) {
            // 声明参数列表
            List<NameValuePair> list = Lists.newList(data.size());
            // 设置参数
            data.forEach((k, v) -> list.add(new BasicNameValuePair(k, W.C.toString(v))));
            // 设置参数与 编码格式
            post.setEntity(new UrlEncodedFormEntity(list));
        }
        // 执行POST
        CLIENT.execute(SimpleRequestBuilder.copy(post).build(), new FutureCallback<SimpleHttpResponse>() {

            @Override
            public void failed(Exception ex) {
                LOG.error(ex);
            }

            @Override
            public void completed(SimpleHttpResponse result) {
                if (callback != null)
                    callback.callback(result.getBodyText());
            }

            @Override
            public void cancelled() {
            }
        });
    } catch (Exception e) {
        LOG.error(e);
    }
}
Also used : HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) NameValuePair(org.apache.hc.core5.http.NameValuePair) BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) UrlEncodedFormEntity(org.apache.hc.client5.http.entity.UrlEncodedFormEntity) BasicHeader(org.apache.hc.core5.http.message.BasicHeader) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse)

Example 4 with SimpleHttpResponse

use of org.apache.hc.client5.http.async.methods.SimpleHttpResponse 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 5 with SimpleHttpResponse

use of org.apache.hc.client5.http.async.methods.SimpleHttpResponse 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

SimpleHttpResponse (org.apache.hc.client5.http.async.methods.SimpleHttpResponse)7 SimpleHttpRequest (org.apache.hc.client5.http.async.methods.SimpleHttpRequest)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 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)2 Timer (com.codahale.metrics.Timer)1 CallExecutor (com.evanlennick.retry4j.CallExecutor)1 RetryConfig (com.evanlennick.retry4j.RetryConfig)1 RetryConfigBuilder (com.evanlennick.retry4j.RetryConfigBuilder)1 RetriesExhaustedException (com.evanlennick.retry4j.exception.RetriesExhaustedException)1 UnexpectedException (com.evanlennick.retry4j.exception.UnexpectedException)1 TransportException (com.nextdoor.bender.ipc.TransportException)1 HttpExchange (com.sun.net.httpserver.HttpExchange)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 SimpleRequestBuilder (org.apache.hc.client5.http.async.methods.SimpleRequestBuilder)1 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)1