Search in sources :

Example 1 with Request

use of org.apache.hc.client5.http.fluent.Request in project feign by OpenFeign.

the class AsyncApacheHttp5ClientTest method throwsFeignExceptionIncludingBody.

@Test
public void throwsFeignExceptionIncludingBody() throws Throwable {
    server.enqueue(new MockResponse().setBody("success!"));
    final TestInterfaceAsync api = AsyncFeign.asyncBuilder().decoder((response, type) -> {
        throw new IOException("timeout");
    }).target(TestInterfaceAsync.class, "http://localhost:" + server.getPort());
    final CompletableFuture<?> cf = api.body("Request body");
    server.takeRequest();
    try {
        unwrap(cf);
    } catch (final FeignException e) {
        assertThat(e.getMessage()).isEqualTo("timeout reading POST http://localhost:" + server.getPort() + "/");
        assertThat(e.contentUTF8()).isEqualTo("Request body");
        return;
    }
    fail();
}
Also used : java.util(java.util) TypeToken(com.google.gson.reflect.TypeToken) CoreMatchers.isA(org.hamcrest.CoreMatchers.isA) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) AtomicReference(java.util.concurrent.atomic.AtomicReference) ResponseMappingDecoder(feign.Feign.ResponseMappingDecoder) feign.codec(feign.codec) FieldQueryMapEncoder(feign.querymap.FieldQueryMapEncoder) HttpMethod(feign.Request.HttpMethod) Gson(com.google.gson.Gson) MockWebServer(okhttp3.mockwebserver.MockWebServer) Assert.fail(org.junit.Assert.fail) URI(java.net.URI) ExpectedException(org.junit.rules.ExpectedException) BeanQueryMapEncoder(feign.querymap.BeanQueryMapEncoder) Buffer(okio.Buffer) java.util.concurrent(java.util.concurrent) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) HardCodedTarget(feign.Target.HardCodedTarget) Rule(org.junit.Rule) Type(java.lang.reflect.Type) MockWebServerAssertions.assertThat(feign.assertj.MockWebServerAssertions.assertThat) MockResponse(okhttp3.mockwebserver.MockResponse) MapEntry.entry(org.assertj.core.data.MapEntry.entry) feign(feign) Assert.assertEquals(org.junit.Assert.assertEquals) MockResponse(okhttp3.mockwebserver.MockResponse) IOException(java.io.IOException) Test(org.junit.Test)

Example 2 with Request

use of org.apache.hc.client5.http.fluent.Request in project feign by OpenFeign.

the class ApacheHttp5Client method execute.

@Override
public Response execute(Request request, Request.Options options) throws IOException {
    ClassicHttpRequest httpUriRequest;
    try {
        httpUriRequest = toClassicHttpRequest(request, options);
    } catch (final URISyntaxException e) {
        throw new IOException("URL '" + request.url() + "' couldn't be parsed into a URI", e);
    }
    final HttpHost target = HttpHost.create(URI.create(request.url()));
    final HttpClientContext context = configureTimeouts(options);
    final ClassicHttpResponse httpResponse = (ClassicHttpResponse) client.execute(target, httpUriRequest, context);
    return toFeignResponse(httpResponse, request);
}
Also used : HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) URISyntaxException(java.net.URISyntaxException)

Example 3 with Request

use of org.apache.hc.client5.http.fluent.Request in project feign by OpenFeign.

the class ApacheHttp5Client method configureTimeouts.

protected HttpClientContext configureTimeouts(Request.Options options) {
    final HttpClientContext context = new HttpClientContext();
    // per request timeouts
    final RequestConfig requestConfig = (client instanceof Configurable ? RequestConfig.copy(((Configurable) client).getConfig()) : RequestConfig.custom()).setConnectTimeout(options.connectTimeout(), options.connectTimeoutUnit()).setResponseTimeout(options.readTimeout(), options.readTimeoutUnit()).build();
    context.setRequestConfig(requestConfig);
    return context;
}
Also used : RequestConfig(org.apache.hc.client5.http.config.RequestConfig) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) Configurable(org.apache.hc.client5.http.config.Configurable)

Example 4 with Request

use of org.apache.hc.client5.http.fluent.Request 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 5 with Request

use of org.apache.hc.client5.http.fluent.Request 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)

Aggregations

IOException (java.io.IOException)8 HttpRequest (org.apache.hc.core5.http.HttpRequest)7 Test (org.junit.Test)7 SimpleHttpRequest (org.apache.hc.client5.http.async.methods.SimpleHttpRequest)5 HttpClientContext (org.apache.hc.client5.http.protocol.HttpClientContext)5 SimpleHttpResponse (org.apache.hc.client5.http.async.methods.SimpleHttpResponse)4 ExecutionException (java.util.concurrent.ExecutionException)3 HttpPost (org.apache.hc.client5.http.classic.methods.HttpPost)3 RequestConfig (org.apache.hc.client5.http.config.RequestConfig)3 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 HttpExchange (com.sun.net.httpserver.HttpExchange)2 ClientProtocolException (org.apache.hc.client5.http.ClientProtocolException)2 Configurable (org.apache.hc.client5.http.config.Configurable)2 BasicCookieStore (org.apache.hc.client5.http.cookie.BasicCookieStore)2 PoolingAsyncClientConnectionManager (org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager)2 ConnectionClosedException (org.apache.hc.core5.http.ConnectionClosedException)2 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)2 Timer (com.codahale.metrics.Timer)1 Gson (com.google.gson.Gson)1