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.jboss.as.test.clustering.cluster.web.DistributableTestCase.java

private void testGracefulServe(URL baseURL, Lifecycle lifecycle)
        throws URISyntaxException, IOException, InterruptedException {

    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
        URI uri = SimpleServlet.createURI(baseURL);

        // Make sure a normal request will succeed
        HttpResponse response = client.execute(new HttpGet(uri));
        try {/*  w  ww .j ava 2s  . c  o  m*/
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Send a long request - in parallel
        URI longRunningURI = SimpleServlet.createURI(baseURL, REQUEST_DURATION);
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<HttpResponse> future = executor.submit(new RequestTask(client, longRunningURI));

        // Make sure long request has started
        Thread.sleep(1000);

        lifecycle.stop(NODE_1);

        // Get result of long request
        // This request should succeed since it initiated before server shutdown
        try {
            response = future.get();
            try {
                Assert.assertEquals("Request should succeed since it initiated before undeply or shutdown.",
                        HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            } finally {
                HttpClientUtils.closeQuietly(response);
            }
        } catch (ExecutionException e) {
            e.printStackTrace(System.err);
            Assert.fail(e.getCause().getMessage());
        }
    }
}

From source file:dk.dbc.opensearch.datadock.DatadockPool.java

/**
 * Checks the jobs submitted for execution
 * /* ww w  .j a v  a  2 s. c  om*/
 * if a Job throws an exception it is written to the log and the
 * datadock continues.
 *
 * @throws InterruptedException if the job.get() call is interrupted (by kill or otherwise).
 */
public void checkJobs() throws InterruptedException {
    log.debug("DatadockPool method checkJobs called");

    log.debug(String.format("job size = %s", jobs.size()));

    Set<IIdentifier> finishedJobs = new HashSet<IIdentifier>();
    for (IIdentifier id : jobs.keySet()) {
        FutureTask<Boolean> job = jobs.get(id);
        log.debug(String.format("job is done: %s", job.isDone()));
        if (job.isDone()) {
            Boolean success = Boolean.FALSE;

            try {
                log.debug("DatadockPool checking job");
                success = job.get();
            } catch (ExecutionException ee) {
                // getting exception from thread
                Throwable cause = ee.getCause();
                log.error(String.format("Exception caught for identifier: %s, from thread: '%s'", id, cause),
                        cause);

                log.info(String.format("Setting status to FAILURE for identifier: %s with message: '%s'", id,
                        cause.getMessage()));
                try {
                    String msg = cause.getMessage() == null ? cause.toString() : cause.getMessage(); // avoid giving null to setStatusFailure
                    harvester.setStatusFailure(id, msg);
                } catch (HarvesterUnknownIdentifierException ex) {
                    String error = String.format(
                            "Failed to set failure status for identifier: %s . Message: %s", id,
                            ex.getMessage());
                    log.error(error, ex);
                } catch (HarvesterInvalidStatusChangeException ex) {
                    String error = String.format(
                            "Failed to set failure status for identifier: %s . Message: %s", id,
                            ex.getMessage());
                    log.error(error, ex);
                } catch (HarvesterIOException ex) {
                    String error = String.format(
                            "Failed to set failure status for identifier: %s . Message: %s", id,
                            ex.getMessage());
                    log.error(error, ex);
                }
            }

            log.debug("DatadockPool adding to finished jobs");
            finishedJobs.add(id);
        }
    }

    for (IIdentifier finishedJobId : finishedJobs) {
        log.debug(String.format("Removing Job with id: %s. Remaining jobs: %s", finishedJobId, jobs.size()));
        jobs.remove(finishedJobId);
    }
}

From source file:org.opennms.core.rpc.camel.EchoRpcIT.java

/**
 * Verifies that the future fails with a {@code RequestRejectedException} when
 * when the client context is stopped./* w ww  .  j  a  v  a 2  s .c o  m*/
 */
@Test(timeout = 60000)
public void futureFailsWithRequestRejectedExceptionWhenClientContextIsStopped() throws Exception {
    assertNotEquals(REMOTE_LOCATION_NAME, identity.getLocation());

    // Stop the client context, this will happen when OpenNMS is shutting down
    rpcClientContext.stop();

    // Now issue an RPC
    EchoRequest request = new EchoRequest("Hell");
    request.setLocation(REMOTE_LOCATION_NAME);
    try {
        echoClient.execute(request).get();
        fail();
    } catch (ExecutionException e) {
        assertEquals(RequestRejectedException.class, e.getCause().getClass());
    }
}

From source file:gov.va.isaac.mojos.profileSync.ProfilesMojoBase.java

protected String getUsername() throws MojoExecutionException {
    if (username == null) {
        username = System.getProperty(PROFILE_SYNC_USERNAME_PROPERTY);

        //still blank, try property
        if (StringUtils.isBlank(username)) {
            username = profileSyncUsername;
        }//from  w  w  w.  ja v  a 2  s .c  om

        //still no username, prompt if allowed
        if (StringUtils.isBlank(username) && !Boolean.getBoolean(PROFILE_SYNC_NO_PROMPTS)) {
            Callable<Void> callable = new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    if (!disableHintGiven) {
                        System.out.println("To disable remote sync during build, add '-D" + PROFILE_SYNC_DISABLE
                                + "=true' to your maven command");
                        disableHintGiven = true;
                    }

                    try {
                        System.out.println("Enter the " + config_.getChangeSetUrlType().name()
                                + " username for the Profiles/Changset remote store ("
                                + config_.getChangeSetUrl() + "):");
                        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                        username = br.readLine();
                    } catch (IOException e) {
                        throw new MojoExecutionException("Error reading username from console");
                    }
                    return null;
                }
            };

            try {
                Executors.newSingleThreadExecutor(new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r, "User Prompt Thread");
                        t.setDaemon(true);
                        return t;
                    }
                }).submit(callable).get(2, TimeUnit.MINUTES);
            } catch (TimeoutException | InterruptedException e) {
                throw new MojoExecutionException("Username not provided within timeout");
            } catch (ExecutionException ee) {
                throw (ee.getCause() instanceof MojoExecutionException ? (MojoExecutionException) ee.getCause()
                        : new MojoExecutionException("Unexpected", ee.getCause()));
            }
        }
    }
    return username;
}

From source file:org.apache.tajo.master.GlobalEngine.java

public Expr buildExpressionFromSql(String sql, Session session) throws TajoException {
    try {//from w w w.  j  av  a 2s. c o m

        if (session.getQueryCache() == null) {
            return analyzer.parse(sql);

        } else {
            try {
                return (Expr) session.getQueryCache().get(sql.trim()).clone();
            } catch (ExecutionException e) {
                throw e.getCause();
            }
        }

    } catch (Throwable t) {
        if (t instanceof TajoException) {
            throw (TajoException) t;
        } else if (t instanceof TajoRuntimeException) {
            throw (TajoException) t.getCause();
        } else {
            throw new TajoInternalError(t);
        }
    }
}

From source file:org.apache.hcatalog.common.HiveClientCache.java

/**
 * Return from cache if exists else create/cache and return
 * @param cacheKey/* w  w w . j a  v a2 s . c o  m*/
 * @return
 * @throws IOException
 * @throws MetaException
 * @throws LoginException
 */
private CacheableHiveMetaStoreClient getOrCreate(final HiveClientCacheKey cacheKey)
        throws IOException, MetaException, LoginException {
    try {
        return hiveCache.get(cacheKey, new Callable<CacheableHiveMetaStoreClient>() {
            @Override
            public CacheableHiveMetaStoreClient call() throws MetaException {
                return new CacheableHiveMetaStoreClient(cacheKey.getHiveConf(), timeout);
            }
        });
    } catch (ExecutionException e) {
        Throwable t = e.getCause();
        if (t instanceof IOException) {
            throw (IOException) t;
        } else if (t instanceof MetaException) {
            throw (MetaException) t;
        } else if (t instanceof LoginException) {
            throw (LoginException) t;
        } else {
            throw new IOException("Error creating hiveMetaStoreClient", t);
        }
    }
}

From source file:gov.va.isaac.mojos.profileSync.ProfilesMojoBase.java

protected String getPassword() throws MojoExecutionException {
    if (password == null) {
        password = System.getProperty(PROFILE_SYNC_PASSWORD_PROPERTY);

        //still blank, try the passed in param
        if (StringUtils.isBlank(password)) {
            password = profileSyncPassword;
        }// ww  w.j  a v a2s.  c  o m

        //still no password, prompt if allowed
        if (StringUtils.isBlank(password) && !Boolean.getBoolean(PROFILE_SYNC_NO_PROMPTS)) {
            Callable<Void> callable = new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    try {
                        if (!disableHintGiven) {
                            System.out.println("To disable remote sync during build, add '-D"
                                    + PROFILE_SYNC_DISABLE + "=true' to your maven command");
                            disableHintGiven = true;
                        }
                        System.out.println("Enter the " + config_.getChangeSetUrlType().name()
                                + " password for the Profiles/Changset remote store: ("
                                + config_.getChangeSetUrl() + "):");

                        //Use console if available, for password masking
                        Console console = System.console();
                        if (console != null) {
                            password = new String(console.readPassword());
                        } else {
                            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                            password = br.readLine();
                        }
                    } catch (IOException e) {
                        throw new MojoExecutionException("Error reading password from console");
                    }
                    return null;
                }
            };

            try {
                Executors.newSingleThreadExecutor(new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r, "User Password Prompt Thread");
                        t.setDaemon(true);
                        return t;
                    }
                }).submit(callable).get(2, TimeUnit.MINUTES);
            } catch (TimeoutException | InterruptedException e) {
                throw new MojoExecutionException("Password not provided within timeout");
            } catch (ExecutionException ee) {
                throw (ee.getCause() instanceof MojoExecutionException ? (MojoExecutionException) ee.getCause()
                        : new MojoExecutionException("Unexpected", ee.getCause()));
            }
        }
    }
    return password;
}

From source file:de.metas.procurement.webui.event.MFEventBus.java

public void register(final IApplicationEventListener listener) {
    EventBusSubscriber subscriber = listener2subscribers.getIfPresent(listener);
    if (subscriber != null) {
        // already registered
        return;/*from   www. ja v a2 s.  c o m*/
    }

    try {
        subscriber = listener2subscribers.get(listener);
        eventBus.register(subscriber);
    } catch (final ExecutionException e) {
        throw new RuntimeException("Failed creating subscriber for " + listener, e.getCause());
    }
}

From source file:org.apache.http.impl.conn.FixedPoolingClientConnectionManager.java

ManagedClientConnection leaseConnection(final Future<HttpPoolEntry> future, final long timeout,
        final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException {
    HttpPoolEntry entry;/*  w w  w  .  j  a  va  2s. c  o  m*/
    try {
        entry = future.get(timeout, tunit);
        if (entry == null || future.isCancelled()) {
            throw new InterruptedException();
        }
        if (entry.getConnection() == null) {
            throw new IllegalStateException("Pool entry with no connection");
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connection leased: " + format(entry) + formatStats(entry.getRoute()));
        }
        return new ManagedClientConnectionImpl(this, this.operator, entry);
    } catch (ExecutionException ex) {
        Throwable cause = ex.getCause();
        if (cause == null) {
            cause = ex;
        }
        this.log.error("Unexpected exception leasing connection from pool", cause);
        // Should never happen
        throw new InterruptedException();
    } catch (TimeoutException ex) {
        throw new ConnectionPoolTimeoutException("Timeout waiting for connection");
    }
}

From source file:com.epam.reportportal.apache.http.impl.execchain.MinimalClientExec.java

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");

    rewriteRequestURI(request, route);//from w w  w.j a  v  a2s.c  om

    final ConnectionRequest connRequest = connManager.requestConnection(route, null);
    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);
    }

    final ConnectionHolder releaseTrigger = new ConnectionHolder(log, connManager, managedConn);
    try {
        if (execAware != null) {
            if (execAware.isAborted()) {
                releaseTrigger.close();
                throw new RequestAbortedException("Request aborted");
            } else {
                execAware.setCancellable(releaseTrigger);
            }
        }

        if (!managedConn.isOpen()) {
            final int timeout = config.getConnectTimeout();
            this.connManager.connect(managedConn, route, timeout > 0 ? timeout : 0, context);
            this.connManager.routeComplete(managedConn, route, context);
        }
        final int timeout = config.getSocketTimeout();
        if (timeout >= 0) {
            managedConn.setSocketTimeout(timeout);
        }

        HttpHost target = null;
        final HttpRequest original = request.getOriginal();
        if (original instanceof HttpUriRequest) {
            final URI uri = ((HttpUriRequest) original).getURI();
            if (uri.isAbsolute()) {
                target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
            }
        }
        if (target == null) {
            target = route.getTargetHost();
        }

        context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
        context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
        context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn);
        context.setAttribute(HttpClientContext.HTTP_ROUTE, route);

        httpProcessor.process(request, context);
        final HttpResponse response = requestExecutor.execute(request, managedConn, context);
        httpProcessor.process(response, 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);
            releaseTrigger.setValidFor(duration, TimeUnit.MILLISECONDS);
            releaseTrigger.markReusable();
        } else {
            releaseTrigger.markNonReusable();
        }

        // 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
            releaseTrigger.releaseConnection();
            return Proxies.enhanceResponse(response, null);
        } else {
            return Proxies.enhanceResponse(response, releaseTrigger);
        }
    } catch (final ConnectionShutdownException ex) {
        final InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down");
        ioex.initCause(ex);
        throw ioex;
    } catch (final HttpException ex) {
        releaseTrigger.abortConnection();
        throw ex;
    } catch (final IOException ex) {
        releaseTrigger.abortConnection();
        throw ex;
    } catch (final RuntimeException ex) {
        releaseTrigger.abortConnection();
        throw ex;
    }
}