Example usage for org.apache.http.concurrent FutureCallback failed

List of usage examples for org.apache.http.concurrent FutureCallback failed

Introduction

In this page you can find the example usage for org.apache.http.concurrent FutureCallback failed.

Prototype

void failed(Exception exception);

Source Link

Usage

From source file:co.paralleluniverse.fibers.httpasyncclient.FiberCloseableHttpAsyncClient.java

private static <T> FutureCallback<T> wrapCallbackWithFuture(final SettableFuture<T> future,
        final FutureCallback<T> callback) {
    return new FutureCallback<T>() {

        @Override/*  www. j  av  a2 s.c  om*/
        public void completed(T result) {
            future.set(result);
            callback.completed(result);
        }

        @Override
        public void failed(Exception ex) {
            future.setException(ex);
            callback.failed(ex);
        }

        @Override
        public void cancelled() {
            future.cancel(true);
            callback.cancelled();
        }
    };
}

From source file:com.clxcommunications.xms.CallbackWrapperTest.java

@Test
public void dropperLogsFailed() throws Exception {
    FutureCallback<Integer> wrapped = CallbackWrapper.exceptionDropper.wrap(exceptionalCallback);

    wrapped.failed(null);

    assertThat(logger.getLoggingEvents(), is(Arrays.asList(LoggingEvent.error(FAILED_EXCEPTION,
            "caught and dropped exception in callback: {}", FAILED_EXCEPTION.getMessage()))));
}

From source file:com.ysheng.auth.common.restful.BaseClient.java

/**
 * Performs an asynchronous DELETE operation.
 *
 * @param path The path of the RESTful operation.
 * @param expectedHttpStatus The expected HTTP status of the operation.
 * @param responseHandler The asynchronous response handler.
 * @throws IOException The error that contains detail information.
 *///from   w ww  .  ja v a  2s.  c  o m
public final void deleteAsync(final String path, final int expectedHttpStatus,
        final FutureCallback<Void> responseHandler) throws IOException {
    restClient.performAsync(RestClient.Method.DELETE, path, null, new FutureCallback<HttpResponse>() {
        @Override
        public void completed(HttpResponse httpResponse) {
            try {
                restClient.checkResponse(httpResponse, expectedHttpStatus);
            } catch (Exception e) {
                responseHandler.failed(e);
            }

            responseHandler.completed(null);
        }

        @Override
        public void failed(Exception e) {
            responseHandler.failed(e);
        }

        @Override
        public void cancelled() {
            responseHandler.cancelled();
        }
    });
}

From source file:org.elasticsearch.client.RestClientMultipleHostsTests.java

@Before
@SuppressWarnings("unchecked")
public void createRestClient() throws IOException {
    CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class);
    when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class),
            any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class)))
                    .thenAnswer(new Answer<Future<HttpResponse>>() {
                        @Override
                        public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
                            HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock
                                    .getArguments()[0];
                            HttpUriRequest request = (HttpUriRequest) requestProducer.generateRequest();
                            HttpHost httpHost = requestProducer.getTarget();
                            HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2];
                            assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class));
                            FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock
                                    .getArguments()[3];
                            //return the desired status code or exception depending on the path
                            if (request.getURI().getPath().equals("/soe")) {
                                futureCallback.failed(new SocketTimeoutException(httpHost.toString()));
                            } else if (request.getURI().getPath().equals("/coe")) {
                                futureCallback.failed(new ConnectTimeoutException(httpHost.toString()));
                            } else if (request.getURI().getPath().equals("/ioe")) {
                                futureCallback.failed(new IOException(httpHost.toString()));
                            } else {
                                int statusCode = Integer.parseInt(request.getURI().getPath().substring(1));
                                StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1),
                                        statusCode, "");
                                futureCallback.completed(new BasicHttpResponse(statusLine));
                            }/*from   w ww .j  av a 2  s  . c  om*/
                            return null;
                        }
                    });
    int numHosts = RandomNumbers.randomIntBetween(getRandom(), 2, 5);
    httpHosts = new HttpHost[numHosts];
    for (int i = 0; i < numHosts; i++) {
        httpHosts[i] = new HttpHost("localhost", 9200 + i);
    }
    failureListener = new HostsTrackingFailureListener();
    restClient = new RestClient(httpClient, 10000, new Header[0], httpHosts, null, failureListener);
}

From source file:com.ysheng.auth.common.restful.BaseClient.java

/**
 * Performs an asynchronous GET operation.
 *
 * @param path The path of the RESTful operation.
 * @param expectedHttpStatus The expected HTTP status of the operation.
 * @param responseHandler The asynchronous response handler.
 * @param <T> The type of the response.
 * @throws IOException The error that contains detail information.
 *//* w ww  . j a  va  2s.co m*/
public final <T> void getAsync(final String path, final int expectedHttpStatus,
        final FutureCallback<T> responseHandler) throws IOException {
    restClient.performAsync(RestClient.Method.GET, path, null, new FutureCallback<HttpResponse>() {
        @Override
        public void completed(HttpResponse httpResponse) {
            T response = null;
            try {
                restClient.checkResponse(httpResponse, expectedHttpStatus);
                response = JsonSerializer.deserialize(httpResponse.getEntity(), new TypeReference<T>() {
                });
            } catch (Exception e) {
                responseHandler.failed(e);
            }

            responseHandler.completed(response);
        }

        @Override
        public void failed(Exception e) {
            responseHandler.failed(e);
        }

        @Override
        public void cancelled() {
            responseHandler.cancelled();
        }
    });
}

From source file:com.vmware.loginsightapi.LogInsightClientMockTest.java

@Test
public void testIngestionFailedInCallback() {
    Message msg1 = new Message("Testing the ingestion");
    msg1.addField("vclap_test_id", "11111");
    IngestionRequest request = new IngestionRequest();
    request.addMessage(msg1);/*  www . j  a  v  a  2  s . c o  m*/
    testIngestionQueryUrlAndHeaders(request);

    doAnswer(new Answer<Future<HttpResponse>>() {
        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocation) {
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
            responseCallback.failed(new Exception());
            return null;
        }
    }).when(asyncHttpClient).execute(any(HttpUriRequest.class), any(FutureCallback.class));

    try {
        CompletableFuture<IngestionResponse> responseFuture = client.ingest(request);
        responseFuture.get(0, TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(e.getCause() instanceof LogInsightApiException);
        Assert.assertEquals(e.getCause().getMessage(), "Ingestion failed");
    } catch (Exception e) {
        Assert.assertTrue(false);
    }
}

From source file:com.vmware.loginsightapi.LogInsightClientMockTest.java

@Test
public void testMessageQueryFailedInCallback() {
    MessageQuery mqb = getMessageQueryForTest();
    testMessageQueryUrlAndHeaders(mqb);//from www .j  a  v  a2s  .c o  m

    doAnswer(new Answer<Future<HttpResponse>>() {
        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocation) {
            @SuppressWarnings("unchecked")
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
            responseCallback.failed(new Exception());
            return null;
        }
    }).when(asyncHttpClient).execute(any(HttpUriRequest.class), any(FutureCallback.class));

    try {
        CompletableFuture<MessageQueryResponse> responseFuture = client.messageQuery(mqb.toUrlString());
        responseFuture.get(0, TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(e.getCause() instanceof LogInsightApiException);
        Assert.assertEquals(e.getCause().getMessage(), "Failed message Query");
    } catch (Exception e) {
        Assert.assertTrue(false);
    }
}

From source file:com.vmware.loginsightapi.LogInsightClientMockTest.java

@Test
public void testAggregateQueryFailedInCallback() {
    List<FieldConstraint> constraints = new ConstraintBuilder().eq("vclap_caseid", "1423244")
            .gt("timestamp", "0").build();
    AggregateQuery aqb = (AggregateQuery) new AggregateQuery().limit(100).setConstraints(constraints);
    testAggregateQueryUrlAndHeaders(aqb);

    doAnswer(new Answer<Future<HttpResponse>>() {
        @Override//from  ww  w  . j  a v a 2s  . co m
        public Future<HttpResponse> answer(InvocationOnMock invocation) {
            @SuppressWarnings("unchecked")
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
            responseCallback.failed(new Exception());
            return null;
        }
    }).when(asyncHttpClient).execute(any(HttpUriRequest.class), any(FutureCallback.class));

    try {
        CompletableFuture<AggregateResponse> responseFuture = client.aggregateQuery(aqb.toUrlString());
        responseFuture.get(0, TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(e.getCause() instanceof LogInsightApiException);
        Assert.assertEquals(e.getCause().getMessage(), "Failed message Query");
    } catch (Exception e) {
        Assert.assertTrue(false);
    }
}

From source file:com.polydeucesys.eslogging.testutils.MockClosableHttpAsyncClient.java

@Override
public <T> Future<T> execute(final HttpAsyncRequestProducer requestProducer,
        final HttpAsyncResponseConsumer<T> responseConsumer, final HttpContext context,
        final FutureCallback<T> callback) {
    try {//from  w ww .j  av  a 2s . com
        @SuppressWarnings({ "rawtypes", "unchecked" })
        final MockHttpFuture future = new MockHttpFuture(nextResponse == null ? defaultResponse : nextResponse,
                nextResponseException, throwExceptionInsteadOfCallbackError, callback, testCallback,
                requestTime);
        fakesecutor.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    future.get();
                } catch (InterruptedException e) {
                    callback.failed(e);
                } catch (ExecutionException e) {
                    callback.failed(e);
                }
            }

        });
        return future;
    } finally {
        nextResponse = null;
        nextResponseException = null;
    }
}

From source file:com.ysheng.auth.common.restful.BaseClient.java

/**
 * Performs an asynchronous POST operation.
 *
 * @param path The path of the RESTful operation.
 * @param payload The payload of the RESTful operation.
 * @param expectedHttpStatus The expected HTTP status of the operation.
 * @param responseHandler The asynchronous response handler.
 * @param <T> The type of the response.
 * @throws IOException The error that contains detail information.
 *///  w  ww .  j  ava2s.  co  m
public final <T> void postAsync(final String path, final Object payload, final int expectedHttpStatus,
        final FutureCallback<T> responseHandler) throws IOException {
    restClient.performAsync(RestClient.Method.POST, path, JsonSerializer.serialize(payload),
            new FutureCallback<HttpResponse>() {
                @Override
                public void completed(HttpResponse httpResponse) {
                    T response = null;

                    try {
                        restClient.checkResponse(httpResponse, expectedHttpStatus);
                        response = JsonSerializer.deserialize(httpResponse.getEntity(), new TypeReference<T>() {
                        });
                    } catch (Exception e) {
                        responseHandler.failed(e);
                    }

                    responseHandler.completed(response);
                }

                @Override
                public void failed(Exception e) {
                    responseHandler.failed(e);
                }

                @Override
                public void cancelled() {
                    responseHandler.cancelled();
                }
            });
}