Search in sources :

Example 91 with Response

use of org.asynchttpclient.Response in project wildfly-camel by wildfly-extras.

the class AhcIntegrationTest method testAsyncHttpClient.

@Test
public void testAsyncHttpClient() throws Exception {
    try (AsyncHttpClient client = new DefaultAsyncHttpClient()) {
        Future<Response> f = client.prepareGet(HTTP_URL).execute();
        Response res = f.get();
        Assert.assertEquals(200, res.getStatusCode());
        Assert.assertTrue(res.getResponseBody().contains("Welcome to WildFly 11"));
    }
}
Also used : Response(org.asynchttpclient.Response) DefaultAsyncHttpClient(org.asynchttpclient.DefaultAsyncHttpClient) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient) DefaultAsyncHttpClient(org.asynchttpclient.DefaultAsyncHttpClient) Test(org.junit.Test)

Example 92 with Response

use of org.asynchttpclient.Response in project tutorials by eugenp.

the class AsyncHttpClientTestCase method givenHttpClient_executeSyncGetRequest.

@Test
public void givenHttpClient_executeSyncGetRequest() {
    BoundRequestBuilder boundGetRequest = HTTP_CLIENT.prepareGet("http://www.baeldung.com");
    Future<Response> responseFuture = boundGetRequest.execute();
    try {
        Response response = responseFuture.get(5000, TimeUnit.MILLISECONDS);
        assertNotNull(response);
        assertEquals(200, response.getStatusCode());
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        e.printStackTrace();
    }
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
Also used : Response(org.asynchttpclient.Response) BoundRequestBuilder(org.asynchttpclient.BoundRequestBuilder) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Example 93 with Response

use of org.asynchttpclient.Response in project tutorials by eugenp.

the class AsyncHttpClientTestCase method givenHttpClient_executeAsyncGetRequest.

@Test
public void givenHttpClient_executeAsyncGetRequest() {
    // execute an unbound GET request
    Request unboundGetRequest = Dsl.get("http://www.baeldung.com").build();
    HTTP_CLIENT.executeRequest(unboundGetRequest, new AsyncCompletionHandler<Integer>() {

        @Override
        public Integer onCompleted(Response response) {
            int resposeStatusCode = response.getStatusCode();
            assertEquals(200, resposeStatusCode);
            return resposeStatusCode;
        }
    });
    // execute a bound GET request
    BoundRequestBuilder boundGetRequest = HTTP_CLIENT.prepareGet("http://www.baeldung.com");
    boundGetRequest.execute(new AsyncCompletionHandler<Integer>() {

        @Override
        public Integer onCompleted(Response response) {
            int resposeStatusCode = response.getStatusCode();
            assertEquals(200, resposeStatusCode);
            return resposeStatusCode;
        }
    });
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
Also used : Response(org.asynchttpclient.Response) BoundRequestBuilder(org.asynchttpclient.BoundRequestBuilder) Request(org.asynchttpclient.Request) Test(org.junit.Test)

Example 94 with Response

use of org.asynchttpclient.Response in project incubator-pulsar by apache.

the class HttpClient method get.

public <T> CompletableFuture<T> get(String path, Class<T> clazz) {
    final CompletableFuture<T> future = new CompletableFuture<>();
    try {
        String requestUrl = new URL(url, path).toString();
        AuthenticationDataProvider authData = authentication.getAuthData();
        BoundRequestBuilder builder = httpClient.prepareGet(requestUrl);
        // Add headers for authentication if any
        if (authData.hasDataForHttp()) {
            for (Map.Entry<String, String> header : authData.getHttpHeaders()) {
                builder.setHeader(header.getKey(), header.getValue());
            }
        }
        final ListenableFuture<Response> responseFuture = builder.setHeader("Accept", "application/json").execute(new AsyncCompletionHandler<Response>() {

            @Override
            public Response onCompleted(Response response) throws Exception {
                return response;
            }

            @Override
            public void onThrowable(Throwable t) {
                log.warn("[{}] Failed to perform http request: {}", requestUrl, t.getMessage());
                future.completeExceptionally(new PulsarClientException(t));
            }
        });
        responseFuture.addListener(() -> {
            try {
                Response response = responseFuture.get();
                if (response.getStatusCode() != HttpURLConnection.HTTP_OK) {
                    log.warn("[{}] HTTP get request failed: {}", requestUrl, response.getStatusText());
                    future.completeExceptionally(new PulsarClientException("HTTP get request failed: " + response.getStatusText()));
                    return;
                }
                T data = ObjectMapperFactory.getThreadLocal().readValue(response.getResponseBodyAsBytes(), clazz);
                future.complete(data);
            } catch (Exception e) {
                log.warn("[{}] Error during HTTP get request: {}", requestUrl, e.getMessage());
                future.completeExceptionally(new PulsarClientException(e));
            }
        }, MoreExecutors.directExecutor());
    } catch (Exception e) {
        log.warn("[{}] Failed to get authentication data for lookup: {}", path, e.getMessage());
        if (e instanceof PulsarClientException) {
            future.completeExceptionally(e);
        } else {
            future.completeExceptionally(new PulsarClientException(e));
        }
    }
    return future;
}
Also used : AuthenticationDataProvider(org.apache.pulsar.client.api.AuthenticationDataProvider) URL(java.net.URL) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) Response(org.asynchttpclient.Response) HttpResponse(io.netty.handler.codec.http.HttpResponse) BoundRequestBuilder(org.asynchttpclient.BoundRequestBuilder) CompletableFuture(java.util.concurrent.CompletableFuture) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) Map(java.util.Map)

Example 95 with Response

use of org.asynchttpclient.Response in project druid by druid-io.

the class EmitterTest method testTimeBasedEmission.

@Test
public void testTimeBasedEmission() throws Exception {
    final int timeBetweenEmissions = 100;
    emitter = timeBasedEmitter(timeBetweenEmissions);
    final CountDownLatch latch = new CountDownLatch(1);
    httpClient.setGoHandler(new GoHandler() {

        @Override
        protected ListenableFuture<Response> go(Request request) {
            latch.countDown();
            return GoHandlers.immediateFuture(okResponse());
        }
    }.times(1));
    long emitTime = System.currentTimeMillis();
    emitter.emit(new UnitEvent("test", 1));
    latch.await();
    long timeWaited = System.currentTimeMillis() - emitTime;
    Assert.assertTrue(StringUtils.format("timeWaited[%s] !< %s", timeWaited, timeBetweenEmissions * 2), timeWaited < timeBetweenEmissions * 2);
    waitForEmission(emitter, 1);
    final CountDownLatch thisLatch = new CountDownLatch(1);
    httpClient.setGoHandler(new GoHandler() {

        @Override
        protected ListenableFuture<Response> go(Request request) {
            thisLatch.countDown();
            return GoHandlers.immediateFuture(okResponse());
        }
    }.times(1));
    emitTime = System.currentTimeMillis();
    emitter.emit(new UnitEvent("test", 2));
    thisLatch.await();
    timeWaited = System.currentTimeMillis() - emitTime;
    Assert.assertTrue(StringUtils.format("timeWaited[%s] !< %s", timeWaited, timeBetweenEmissions * 2), timeWaited < timeBetweenEmissions * 2);
    waitForEmission(emitter, 2);
    closeNoFlush(emitter);
    Assert.assertTrue("httpClient.succeeded()", httpClient.succeeded());
}
Also used : Response(org.asynchttpclient.Response) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) Request(org.asynchttpclient.Request) UnitEvent(org.apache.druid.java.util.emitter.service.UnitEvent) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Aggregations

Response (org.asynchttpclient.Response)142 Test (org.testng.annotations.Test)85 AsyncHttpClient (org.asynchttpclient.AsyncHttpClient)79 AbstractBasicTest (org.asynchttpclient.AbstractBasicTest)55 HttpServletResponse (javax.servlet.http.HttpServletResponse)42 BoundRequestBuilder (org.asynchttpclient.BoundRequestBuilder)32 Request (org.asynchttpclient.Request)29 IOException (java.io.IOException)21 Test (org.junit.Test)20 ExecutionException (java.util.concurrent.ExecutionException)16 PubSubMessage (com.yahoo.bullet.pubsub.PubSubMessage)14 RESTPubSubTest.getOkResponse (com.yahoo.bullet.pubsub.rest.RESTPubSubTest.getOkResponse)11 TimeoutException (java.util.concurrent.TimeoutException)11 RequestBuilder (org.asynchttpclient.RequestBuilder)11 UnitEvent (org.apache.druid.java.util.emitter.service.UnitEvent)10 RESTPubSubTest.getNotOkResponse (com.yahoo.bullet.pubsub.rest.RESTPubSubTest.getNotOkResponse)9 UnsupportedEncodingException (java.io.UnsupportedEncodingException)9 Map (java.util.Map)9 AuthorizationException (org.apache.shiro.authz.AuthorizationException)9 TestUtils.createTempFile (org.asynchttpclient.test.TestUtils.createTempFile)9