Example usage for java.util.concurrent ExecutionException getCause

List of usage examples for java.util.concurrent ExecutionException getCause

Introduction

In this page you can find the example usage for java.util.concurrent ExecutionException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:org.apache.http.HC4.impl.execchain.MainClientExec.java

@Override
public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");

    AuthState targetAuthState = context.getTargetAuthState();
    if (targetAuthState == null) {
        targetAuthState = new AuthState();
        context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, targetAuthState);
    }//from ww  w  .j  a  v  a  2s  . c  o m
    AuthState proxyAuthState = context.getProxyAuthState();
    if (proxyAuthState == null) {
        proxyAuthState = new AuthState();
        context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxyAuthState);
    }

    if (request instanceof HttpEntityEnclosingRequest) {
        RequestEntityProxy.enhance((HttpEntityEnclosingRequest) request);
    }

    Object userToken = context.getUserToken();

    final ConnectionRequest connRequest = connManager.requestConnection(route, userToken);
    if (execAware != null) {
        if (execAware.isAborted()) {
            connRequest.cancel();
            throw new RequestAbortedException("Request aborted");
        } else {
            execAware.setCancellable(connRequest);
        }
    }

    final RequestConfig config = context.getRequestConfig();

    final HttpClientConnection managedConn;
    try {
        final int timeout = config.getConnectionRequestTimeout();
        managedConn = connRequest.get(timeout > 0 ? timeout : 0, TimeUnit.MILLISECONDS);
    } catch (final InterruptedException interrupted) {
        Thread.currentThread().interrupt();
        throw new RequestAbortedException("Request aborted", interrupted);
    } catch (final ExecutionException ex) {
        Throwable cause = ex.getCause();
        if (cause == null) {
            cause = ex;
        }
        throw new RequestAbortedException("Request execution failed", cause);
    }

    context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn);

    if (config.isStaleConnectionCheckEnabled()) {
        // validate connection
        if (managedConn.isOpen()) {
            this.log.debug("Stale connection check");
            if (managedConn.isStale()) {
                this.log.debug("Stale connection detected");
                managedConn.close();
            }
        }
    }

    final ConnectionHolder connHolder = new ConnectionHolder(this.log, this.connManager, managedConn);
    try {
        if (execAware != null) {
            execAware.setCancellable(connHolder);
        }

        HttpResponse response;
        for (int execCount = 1;; execCount++) {

            if (execCount > 1 && !RequestEntityProxy.isRepeatable(request)) {
                throw new NonRepeatableRequestException(
                        "Cannot retry request " + "with a non-repeatable request entity.");
            }

            if (execAware != null && execAware.isAborted()) {
                throw new RequestAbortedException("Request aborted");
            }

            if (!managedConn.isOpen()) {
                this.log.debug("Opening connection " + route);
                try {
                    establishRoute(proxyAuthState, managedConn, route, request, context);
                } catch (final TunnelRefusedException ex) {
                    if (this.log.isDebugEnabled()) {
                        this.log.debug(ex.getMessage());
                    }
                    response = ex.getResponse();
                    break;
                }
            }
            final int timeout = config.getSocketTimeout();
            if (timeout >= 0) {
                managedConn.setSocketTimeout(timeout);
            }

            if (execAware != null && execAware.isAborted()) {
                throw new RequestAbortedException("Request aborted");
            }

            if (this.log.isDebugEnabled()) {
                this.log.debug("Executing request " + request.getRequestLine());
            }

            if (!request.containsHeader(AUTH.WWW_AUTH_RESP)) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug("Target auth state: " + targetAuthState.getState());
                }
                this.authenticator.generateAuthResponse(request, targetAuthState, context);
            }
            if (!request.containsHeader(AUTH.PROXY_AUTH_RESP) && !route.isTunnelled()) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug("Proxy auth state: " + proxyAuthState.getState());
                }
                this.authenticator.generateAuthResponse(request, proxyAuthState, context);
            }

            response = requestExecutor.execute(request, managedConn, context);

            // The connection is in or can be brought to a re-usable state.
            if (reuseStrategy.keepAlive(response, context)) {
                // Set the idle duration of this connection
                final long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
                if (this.log.isDebugEnabled()) {
                    final String s;
                    if (duration > 0) {
                        s = "for " + duration + " " + TimeUnit.MILLISECONDS;
                    } else {
                        s = "indefinitely";
                    }
                    this.log.debug("Connection can be kept alive " + s);
                }
                connHolder.setValidFor(duration, TimeUnit.MILLISECONDS);
                connHolder.markReusable();
            } else {
                connHolder.markNonReusable();
            }

            if (needAuthentication(targetAuthState, proxyAuthState, route, response, context)) {
                // Make sure the response body is fully consumed, if present
                final HttpEntity entity = response.getEntity();
                if (connHolder.isReusable()) {
                    EntityUtils.consume(entity);
                } else {
                    managedConn.close();
                    if (proxyAuthState.getState() == AuthProtocolState.SUCCESS
                            && proxyAuthState.getAuthScheme() != null
                            && proxyAuthState.getAuthScheme().isConnectionBased()) {
                        this.log.debug("Resetting proxy auth state");
                        proxyAuthState.reset();
                    }
                    if (targetAuthState.getState() == AuthProtocolState.SUCCESS
                            && targetAuthState.getAuthScheme() != null
                            && targetAuthState.getAuthScheme().isConnectionBased()) {
                        this.log.debug("Resetting target auth state");
                        targetAuthState.reset();
                    }
                }
                // discard previous auth headers
                final HttpRequest original = request.getOriginal();
                if (!original.containsHeader(AUTH.WWW_AUTH_RESP)) {
                    request.removeHeaders(AUTH.WWW_AUTH_RESP);
                }
                if (!original.containsHeader(AUTH.PROXY_AUTH_RESP)) {
                    request.removeHeaders(AUTH.PROXY_AUTH_RESP);
                }
            } else {
                break;
            }
        }

        if (userToken == null) {
            userToken = userTokenHandler.getUserToken(context);
            context.setAttribute(HttpClientContext.USER_TOKEN, userToken);
        }
        if (userToken != null) {
            connHolder.setState(userToken);
        }

        // check for entity, release connection if possible
        final HttpEntity entity = response.getEntity();
        if (entity == null || !entity.isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            connHolder.releaseConnection();
            return new HttpResponseProxy(response, null);
        } else {
            return new HttpResponseProxy(response, connHolder);
        }
    } catch (final ConnectionShutdownException ex) {
        final InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down");
        ioex.initCause(ex);
        throw ioex;
    } catch (final HttpException ex) {
        connHolder.abortConnection();
        throw ex;
    } catch (final IOException ex) {
        connHolder.abortConnection();
        throw ex;
    } catch (final RuntimeException ex) {
        connHolder.abortConnection();
        throw ex;
    }
}

From source file:voldemort.restclient.R2Store.java

@Override
public boolean delete(ByteArray key, Version version) throws VoldemortException {
    try {//from  w ww . j ava  2 s .  co  m
        // Create the REST request with this byte array
        String base64Key = RestUtils.encodeVoldemortKey(key.get());
        RestRequestBuilder rb = new RestRequestBuilder(
                new URI(this.restBootstrapURL + "/" + getName() + "/" + base64Key));
        // Create a HTTP POST request
        rb.setMethod(DELETE);
        rb.setHeader(CONTENT_LENGTH, "0");
        String timeoutStr = Long
                .toString(this.config.getTimeoutConfig().getOperationTimeout(VoldemortOpCode.DELETE_OP_CODE));
        rb.setHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, timeoutStr);
        rb.setHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS,
                String.valueOf(System.currentTimeMillis()));
        if (this.routingTypeCode != null) {
            rb.setHeader(RestMessageHeaders.X_VOLD_ROUTING_TYPE_CODE, this.routingTypeCode);
        }
        if (this.zoneId != INVALID_ZONE_ID) {
            rb.setHeader(RestMessageHeaders.X_VOLD_ZONE_ID, String.valueOf(this.zoneId));
        }
        // Serialize the Vector clock
        VectorClock vc = (VectorClock) version;

        // If the given Vector clock is empty, we'll let the receiver of
        // this request fetch the existing vector clock and increment
        // before
        // doing the put.
        if (vc != null && vc.getEntries().size() != 0) {
            String serializedVC = null;
            if (!vc.getEntries().isEmpty()) {
                serializedVC = RestUtils.getSerializedVectorClock(vc);
            }

            if (serializedVC != null && serializedVC.length() > 0) {
                rb.setHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, serializedVC);
            }
        }

        RestRequest request = rb.build();
        Future<RestResponse> f = client.restRequest(request);

        // This will block
        RestResponse response = f.get();
        final ByteString entity = response.getEntity();
        if (entity == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Empty response !");
            }
        }

    } catch (ExecutionException e) {
        if (e.getCause() instanceof RestException) {
            RestException exception = (RestException) e.getCause();
            if (logger.isDebugEnabled()) {
                logger.debug("REST EXCEPTION STATUS : " + exception.getResponse().getStatus());
            }
            if (exception.getResponse().getStatus() == NOT_FOUND.getCode()) {
                return false;
            }
        } else {
            throw new VoldemortException("Unknown HTTP request execution exception: " + e.getMessage(), e);
        }
    } catch (InterruptedException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Operation interrupted : " + e.getMessage());
        }
        throw new VoldemortException("Operation Interrupted: " + e.getMessage(), e);
    } catch (URISyntaxException e) {
        throw new VoldemortException("Illegal HTTP URL" + e.getMessage(), e);
    }
    return true;
}

From source file:com.connectsdk.service.FireTVService.java

private <Response, Result> void handleAsyncFutureWithConversion(final ResponseListener<Response> listener,
        final RemoteMediaPlayer.AsyncFuture<Result> asyncFuture,
        final ConvertResult<Response, Result> conversion, final String errorMessage) {
    if (asyncFuture != null) {
        asyncFuture.getAsync(new RemoteMediaPlayer.FutureListener<Result>() {
            @Override//  w w  w.  j  a  v  a  2 s.c  om
            public void futureIsNow(Future<Result> future) {
                try {
                    Result result = future.get();
                    Util.postSuccess(listener, conversion.convert(result));
                } catch (ExecutionException e) {
                    Util.postError(listener, new FireTVServiceError(errorMessage, e.getCause()));
                } catch (Exception e) {
                    Util.postError(listener, new FireTVServiceError(errorMessage, e));
                }
            }
        });
    } else {
        Util.postError(listener, new FireTVServiceError(errorMessage));
    }
}

From source file:com.gc.iotools.stream.os.OutputStreamToInputStream.java

private void internalClose(final boolean join, final TimeUnit timeUnit, final long timeout) throws IOException {
    if (!this.closeCalled) {
        initializeIfNecessary();//from  www. ja va  2  s  . c  o  m
        this.closeCalled = true;
        super.close();
        if (join) {
            // waiting for thread to finish..
            try {
                this.writingResult.get(timeout, timeUnit);
            } catch (final ExecutionException e) {
                final IOException e1 = new IOException(
                        "The doRead() threw exception. Use " + "getCause() for details.");
                e1.initCause(e.getCause());
                throw e1;
            } catch (final InterruptedException e) {
                final IOException e1 = new IOException("Waiting of the thread has been interrupted");
                e1.initCause(e);
                throw e1;
            } catch (final TimeoutException e) {
                if (!this.writingResult.isDone()) {
                    this.writingResult.cancel(true);
                }
                final IOException e1 = new IOException("Waiting for the internal "
                        + "thread to finish took more than [" + timeout + "] " + timeUnit);
                e1.initCause(e);
                throw e1;
            }
        }
        afterClose();
    }
}

From source file:com.microsoft.alm.plugin.idea.git.ui.pullrequest.CreatePullRequestModel.java

/**
 * This method calculates the commits and diff information against the tip of current branch and
 * the common ancestor of source branch (current branch) and target branch (selected remote branch).
 * <p/>// w  ww.java2  s.c  o m
 * If there is no common parent (two branches are parallel), return an empty GitCommitCompareInfo
 * <p/>
 * This is potentially an expensive calculation, probably should do it on a background thread.
 * We will also attempt to cache the result
 * <p/>
 * default access for testing so we bypass UI code,
 * TODO: reevaluate the testing to properly shutoff the access level
 *
 * @return gitChangesContainer on what has changed on source branch
 */
GitChangesContainer getMyChangesCompareInfo() throws VcsException {

    final GitBranch currBranch = this.getSourceBranch();

    final GitRemoteBranch selectedRemoteBranch = this.getTargetBranch();

    // if source branch or currentBranch isn't set, just return empty diff
    if (selectedRemoteBranch == null || currBranch == null) {
        return GitChangesContainer.createChangesContainer(null, null, null, null,
                getDiffCompareInfoProvider().getEmptyDiff(this.gitRepository), this.gitRepository);
    }

    // get hash of last commit for each branch
    final String remoteBranchHash = GeneralGitHelper.getLastCommitHash(project, gitRepository,
            selectedRemoteBranch);
    final String currBranchHash = GeneralGitHelper.getLastCommitHash(project, gitRepository, currBranch);

    try {
        GitCommitCompareInfo changes = this.diffCache
                .get(new Pair<String, String>(currBranchHash, remoteBranchHash));

        return GitChangesContainer.createChangesContainer(currBranch.getName(), selectedRemoteBranch.getName(),
                currBranchHash, remoteBranchHash, changes, this.gitRepository);
    } catch (ExecutionException e) {
        throw new VcsException(e.getCause());
    }
}

From source file:voldemort.restclient.R2Store.java

@Override
public void put(ByteArray key, Versioned<byte[]> value, byte[] transform) throws VoldemortException {
    RestResponse response = null;// www .j  a  v  a  2s . c o  m

    try {
        byte[] payload = value.getValue();

        // Create the REST request with this byte array
        String base64Key = RestUtils.encodeVoldemortKey(key.get());
        RestRequestBuilder rb = new RestRequestBuilder(
                new URI(this.restBootstrapURL + "/" + getName() + "/" + base64Key));

        // Create a HTTP POST request
        rb.setMethod(POST);
        rb.setEntity(payload);
        rb.setHeader(CONTENT_TYPE, "binary");
        rb.setHeader(CONTENT_LENGTH, "" + payload.length);
        String timeoutStr = Long
                .toString(this.config.getTimeoutConfig().getOperationTimeout(VoldemortOpCode.PUT_OP_CODE));
        rb.setHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, timeoutStr);
        rb.setHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS,
                String.valueOf(System.currentTimeMillis()));
        if (this.routingTypeCode != null) {
            rb.setHeader(RestMessageHeaders.X_VOLD_ROUTING_TYPE_CODE, this.routingTypeCode);
        }
        if (this.zoneId != INVALID_ZONE_ID) {
            rb.setHeader(RestMessageHeaders.X_VOLD_ZONE_ID, String.valueOf(this.zoneId));
        }

        // Serialize the Vector clock
        VectorClock vc = (VectorClock) value.getVersion();

        // If the given Vector clock is empty, we'll let the receiver of
        // this request fetch the existing vector clock and increment before
        // doing the put.
        if (vc != null) {
            String serializedVC = null;
            if (!vc.getEntries().isEmpty()) {
                serializedVC = RestUtils.getSerializedVectorClock(vc);
            }

            if (serializedVC != null && serializedVC.length() > 0) {
                rb.setHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, serializedVC);
            }
        }

        RestRequest request = rb.build();
        Future<RestResponse> f = client.restRequest(request);

        // This will block
        response = f.get();

        String serializedUpdatedVC = response.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK);
        if (serializedUpdatedVC == null || serializedUpdatedVC.length() == 0) {
            if (logger.isDebugEnabled()) {
                logger.debug("Received empty vector clock in the response");
            }
        } else {
            VectorClock updatedVC = RestUtils.deserializeVectorClock(serializedUpdatedVC);
            VectorClock originalVC = (VectorClock) value.getVersion();
            originalVC.copyFromVectorClock(updatedVC);
        }

        final ByteString entity = response.getEntity();
        if (entity == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Empty response !");
            }
        }
    } catch (ExecutionException e) {
        if (e.getCause() instanceof RestException) {
            RestException exception = (RestException) e.getCause();
            if (logger.isDebugEnabled()) {
                logger.debug("REST EXCEPTION STATUS : " + exception.getResponse().getStatus());
            }

            int httpErrorStatus = exception.getResponse().getStatus();
            if (httpErrorStatus == BAD_REQUEST.getCode()) {
                throw new VoldemortException("Bad request: " + e.getMessage(), e);
            } else if (httpErrorStatus == PRECONDITION_FAILED.getCode()) {
                throw new ObsoleteVersionException(e.getMessage());
            } else if (httpErrorStatus == REQUEST_TIMEOUT.getCode()
                    || httpErrorStatus == INTERNAL_SERVER_ERROR.getCode()) {
                throw new InsufficientOperationalNodesException(e.getMessage());
            }
        }
        throw new VoldemortException("Unknown HTTP request execution exception: " + e.getMessage(), e);

    } catch (InterruptedException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Operation interrupted : " + e.getMessage());
        }
        throw new VoldemortException("Unknown Voldemort exception: " + e.getMessage());
    } catch (URISyntaxException e) {
        throw new VoldemortException("Illegal HTTP URL" + e.getMessage());
    }
}

From source file:voldemort.restclient.R2Store.java

@Override
public Map<ByteArray, List<Versioned<byte[]>>> getAll(Iterable<ByteArray> keys,
        Map<ByteArray, byte[]> transforms) throws VoldemortException {

    Map<ByteArray, List<Versioned<byte[]>>> resultMap = new HashMap<ByteArray, List<Versioned<byte[]>>>();
    int numberOfKeys = 0;

    try {/*from   w  ww. ja  v a  2 s  .  c o m*/
        Iterator<ByteArray> it = keys.iterator();
        StringBuilder keyArgs = null;

        while (it.hasNext()) {
            ByteArray key = it.next();
            String base64Key = RestUtils.encodeVoldemortKey(key.get());
            if (keyArgs == null) {
                keyArgs = new StringBuilder();
                keyArgs.append(base64Key);
            } else {
                keyArgs.append("," + base64Key);
            }
            numberOfKeys++;
        }

        // Rerouting getall() requests with single key to get(). This is a
        // temporary fix to handle the NPE when getAll requests are made
        // with single key.
        // TODO a common way to handle getAll with any number of keys
        if (numberOfKeys == 1) {
            List<Versioned<byte[]>> resultList = new ArrayList<Versioned<byte[]>>();
            it = keys.iterator();
            ByteArray key = it.next();
            byte[] singleKeyTransforms = null;
            if (transforms != null) {
                singleKeyTransforms = transforms.get(key);
            }
            resultList = this.get(key, singleKeyTransforms);
            resultMap.put(key, resultList);
        } else {

            RestRequestBuilder rb = new RestRequestBuilder(
                    new URI(this.restBootstrapURL + "/" + getName() + "/" + keyArgs.toString()));

            rb.setMethod(GET);
            rb.setHeader("Accept", MULTIPART_CONTENT_TYPE);
            String timeoutStr = Long.toString(
                    this.config.getTimeoutConfig().getOperationTimeout(VoldemortOpCode.GET_ALL_OP_CODE));
            rb.setHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, timeoutStr);
            rb.setHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS,
                    String.valueOf(System.currentTimeMillis()));
            if (this.routingTypeCode != null) {
                rb.setHeader(RestMessageHeaders.X_VOLD_ROUTING_TYPE_CODE, this.routingTypeCode);
            }
            if (this.zoneId != INVALID_ZONE_ID) {
                rb.setHeader(RestMessageHeaders.X_VOLD_ZONE_ID, String.valueOf(this.zoneId));
            }

            RestRequest request = rb.build();
            Future<RestResponse> f = client.restRequest(request);

            // This will block
            RestResponse response = f.get();

            // Parse the response
            final ByteString entity = response.getEntity();

            String contentType = response.getHeader(CONTENT_TYPE);
            if (entity != null) {
                if (contentType.equalsIgnoreCase(MULTIPART_CONTENT_TYPE)) {

                    resultMap = parseGetAllResults(entity);
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Did not receive a multipart response");
                    }
                }

            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Did not get any response!");
                }
            }
        }
    } catch (ExecutionException e) {
        if (e.getCause() instanceof RestException) {
            RestException exception = (RestException) e.getCause();
            if (logger.isDebugEnabled()) {
                logger.debug("REST EXCEPTION STATUS : " + exception.getResponse().getStatus());
            }
        } else {
            throw new VoldemortException("Unknown HTTP request execution exception: " + e.getMessage(), e);
        }
    } catch (InterruptedException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Operation interrupted : " + e.getMessage(), e);
        }
        throw new VoldemortException("Operation interrupted exception: " + e.getMessage(), e);
    } catch (URISyntaxException e) {
        throw new VoldemortException("Illegal HTTP URL" + e.getMessage(), e);
    }

    return resultMap;
}

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

@Test
public void testMessageQueryCancelled() {
    MessageQuery mqb = getMessageQueryForTest();
    testMessageQueryUrlAndHeaders(mqb);//from   w ww.ja  v  a2s.com

    doAnswer(new Answer<Future<HttpResponse>>() {
        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocation) {
            @SuppressWarnings("unchecked")
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
            responseCallback.cancelled();
            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(), "Cancelled message Query");
    } catch (Exception e) {
        Assert.assertTrue(false);
    }
}

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

@Test
public void testMessageQueryFailedInCallback() {
    MessageQuery mqb = getMessageQueryForTest();
    testMessageQueryUrlAndHeaders(mqb);// ww w. j ava2s.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 testAggregateQueryCancelled() {
    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/*www .j  a v a 2  s  . co m*/
        public Future<HttpResponse> answer(InvocationOnMock invocation) {
            @SuppressWarnings("unchecked")
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
            responseCallback.cancelled();
            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(), "Cancelled message Query");
    } catch (Exception e) {
        Assert.assertTrue(false);
    }
}