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:kafka.deploy.utils.command.CommandRemoteOperation.java

/**
 * Executes the given commands in parallel on the remote hosts and
 * aggregates the results for the caller.
 * /* w  w w .  j  av a 2s. c  o  m*/
 * @param hostNameCommandLineMap Map with a key is the external host name
 *        and the value is the command line to execute remotely on that host
 * 
 * @return List of result types as dictated by the subclass
 * 
 * @throws RemoteOperationException Thrown on error invoking the command on
 *         one or more clients.
 */
protected void execute(Map<String, String> hostNameCommandLineMap) throws RemoteOperationException {

    ExecutorService threadPool = Executors.newFixedThreadPool(hostNameCommandLineMap.size());
    List<Future<?>> futures = new ArrayList<Future<?>>();

    for (Map.Entry<String, String> entry : hostNameCommandLineMap.entrySet()) {
        String hostName = entry.getKey();
        String commandLine = entry.getValue();

        if (logger.isDebugEnabled())
            logger.debug("Command to execute: " + commandLine);

        List<String> commandArgs = parse(commandLine);
        UnixCommand command = new UnixCommand(hostName, commandArgs);
        Callable<?> callable = getCallable(command);
        Future<?> future = threadPool.submit(callable);
        futures.add(future);
    }

    // Build up a list of all the results and/or capture the errors as they
    // occur.
    try {
        StringBuilder errors = new StringBuilder();

        for (Future<?> future : futures) {
            Throwable t = null;

            try {
                future.get();
            } catch (ExecutionException ex) {
                t = ex.getCause();
            } catch (Exception e) {
                t = e;
            }

            if (t != null) {
                if (logger.isWarnEnabled())
                    logger.warn(t, t);

                if (errors.length() > 0)
                    errors.append("; ");

                errors.append(t.getMessage());
            }
        }

        if (errors.length() > 0)
            throw new RemoteOperationException(errors.toString());
    } finally {
        threadPool.shutdown();

        try {
            threadPool.awaitTermination(60, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            if (logger.isWarnEnabled())
                logger.warn(e, e);
        }
    }
}

From source file:org.mrgeo.data.DataProviderFactory.java

private static MrsImageDataProvider getMrsImageDataProvider(final String name, AccessMode accessMode,
        final Configuration conf, final ProviderProperties providerProperties) throws DataProviderNotFound {
    try {/*from  www .  ja v  a 2  s . c om*/
        // Make sure that image resources are cached uniquely by user
        String cacheKey = getResourceCacheKey(name, conf, providerProperties);
        // If a resource was already accessed in read mode, and then again in
        // OVERWRITE or WRITE mode, then force the cache to re-load the resource
        // to execute validation beforehand
        if (accessMode == AccessMode.OVERWRITE || accessMode == AccessMode.WRITE) {
            mrsImageProviderCache.invalidate(cacheKey);
        }
        if (log.isDebugEnabled()) {
            log.debug("Loading from mrsImageProviderCache");
            log.debug("   cacheKey: {}", cacheKey);
            log.debug("   name: {}", name);
            log.debug("   accessMode: {}", accessMode.name());
            log.debug("   conf: {}", conf);
            log.debug("   provider properties: {}", providerProperties);
        }

        MrsImageLoader loader = new MrsImageLoader(name, accessMode, conf, providerProperties);

        return mrsImageProviderCache.get(cacheKey, loader);

        //    return mrsImageProviderCache.get(cacheKey,
        //        new MrsImageLoader(name, accessMode, conf, providerProperties));
    } catch (ExecutionException e) {
        if (e.getCause() instanceof DataProviderNotFound) {
            throw (DataProviderNotFound) e.getCause();
        }
        throw new DataProviderNotFound(e);
    }
}

From source file:ome.server.utests.MTPixelDataTest.java

public void testBasic() throws Exception {

    final AtomicInteger pixelsId = new AtomicInteger();
    final int numThreads = 4;

    // MT items/*from   ww  w.  ja  v a 2s  .  co m*/
    ExecutorService threads = Executors.newFixedThreadPool(numThreads);

    // nio mocks
    Mock boMock = mock(BackOff.class);
    BackOff backOff = (BackOff) boMock.proxy();
    Mock fprMock = mock(FilePathResolver.class);
    FilePathResolver resolver = (FilePathResolver) fprMock.proxy();
    fprMock.expects(atLeastOnce()).method("getOriginalFilePath").will(returnValue(tiny()));
    fprMock.expects(atLeastOnce()).method("getPixelsParams").will(returnValue(new HashMap<String, String>()));

    // nio settings
    String path = dir(uuid);
    TileSizes tileSizes = new ConfiguredTileSizes(5, 5, 10, 10);
    PixelsService service = new PixelsService(path, resolver, backOff, tileSizes);

    // session mocks
    Mock mgrMock = mock(SessionManager.class);
    Mock sqlMock = mock(SqlAction.class);
    SessionManager mgr = (SessionManager) mgrMock.proxy();
    Executor ex = new DummyExecutor(null, null, threads);
    SqlAction sql = (SqlAction) sqlMock.proxy();
    sqlMock.expects(atLeastOnce()).method("setStatsInfo").will(returnValue(1L));

    // pixeldata
    PersistentEventLogLoader loader = new PersistentEventLogLoader("REPO", numThreads) {
        @Override
        protected EventLog query() {
            long id = (long) pixelsId.incrementAndGet();
            EventLog log = new EventLog();
            log.setEntityId(id);
            return log;
        }
    };

    PixelDataHandler handler = new PixelDataHandler(loader, service) {
        @Override
        protected Pixels getPixels(Long id, ServiceFactory sf) {
            Pixels pix = new Pixels(id, true);
            pix.setSizeX(20);
            pix.setSizeY(20);
            pix.setSizeZ(5);
            pix.setSizeC(1);
            pix.setSizeT(6);
            pix.setDimensionOrder(new DimensionOrder("XYZCT"));
            pix.setPixelsType(new PixelsType("int16"));
            pix.addChannel(new Channel());
            return pix;
        }
    };
    handler.setSqlAction(sql);

    PixelDataThread thread = new PixelDataThread(true, mgr, ex, handler, new Principal("test"), uuid,
            numThreads) {
        @Override
        protected void onExecutionException(ExecutionException ee) {
            Throwable t = ee.getCause();
            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t);
            }
        }
    };

    // test
    thread.doRun();
}

From source file:com.example.AzureADResponseFilter.java

private AuthenticationResult getAccessToken(AuthorizationCode authorizationCode, String currentUri)
        throws Throwable {
    String authCode = authorizationCode.getValue();
    ClientCredential credential = new ClientCredential(clientId, clientSecret);
    AuthenticationContext context = null;
    AuthenticationResult result = null;//from ww w.  j a  v  a  2 s.  c  o  m
    ExecutorService service = null;
    try {
        service = Executors.newFixedThreadPool(1);
        context = new AuthenticationContext(authority + tenant + "/", true, service);
        Future<AuthenticationResult> future = context.acquireTokenByAuthorizationCode(authCode,
                new URI(currentUri), credential, null);
        result = future.get();
    } catch (ExecutionException e) {
        throw e.getCause();
    } finally {
        service.shutdown();
    }

    if (result == null) {
        throw new ServiceUnavailableException("authentication result was null");
    }
    return result;
}

From source file:org.smartfrog.test.system.projects.alpine.remote.RemoteTestBase.java

protected Transmission send(Transmission tx, long timeout)
        throws InterruptedException, TimeoutException, IOException, ExecutionException {
    getQueue().transmit(tx);/*w ww .j  ava 2 s .c  o m*/
    Future<?> result = tx.getResult();
    try {
        result.get(timeout, TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        //nested ioes are rethrown
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        //runtime exceptions are stripped out and rethrown
        if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
        }
        //anything else is sent nested.
        throw e;
    }
    return tx;
}

From source file:org.apache.hadoop.hbase.util.TestDrainableQueue.java

@Test(timeout = 30 * 1000)
public void testDrainableQueue() throws Exception {
    for (int attempt = 0; attempt < NUM_ATTEMPTS; ++attempt) {
        final int totalEvents = NUM_PRODUCERS * NUM_EVENTS_PER_BATCH;
        final int drainAfterNEvents = totalEvents / 2;
        shouldDrain = new CountDownLatch(drainAfterNEvents);
        numEnqueued.set(0);//from   w w  w.j ava 2  s  .  co m
        q = new DrainableQueue<Integer>("queue");
        ExecutorService exec = Executors.newFixedThreadPool(NUM_PRODUCERS);
        CompletionService<Void> cs = new ExecutorCompletionService<Void>(exec);
        List<Future<Void>> futures = new ArrayList<Future<Void>>();
        for (int producer = 0; producer < NUM_PRODUCERS; ++producer) {
            futures.add(cs.submit(new Producer(producer)));
        }
        shouldDrain.await();
        eventsProcessed = 0;
        LOG.info("Starting draining the queue");
        q.drain(this);
        LOG.info("Finished draining the queue");
        assertEquals(numEnqueued.get(), eventsProcessed);
        LOG.info("Events processed: " + eventsProcessed + ", drainAfterNEvents: " + drainAfterNEvents);
        assertTrue(eventsProcessed >= drainAfterNEvents);
        for (Future<Void> f : futures) {
            try {
                f.get();
            } catch (ExecutionException ex) {
                LOG.error("Exception from producer thread", ex);
                if (ex.getCause() instanceof AssertionError) {
                    throw (AssertionError) ex.getCause();
                }
                throw ex;
            }
        }
        exec.shutdown();
        assertTrue(exec.awaitTermination(5, TimeUnit.SECONDS));
    }
}

From source file:org.apache.oozie.tools.OozieSharelibCLI.java

private void checkCopyResults(List<Future<Void>> futures) throws IOException {
    Throwable t = null;// w w  w .  j a v a 2s  . c om
    for (Future<Void> future : futures) {
        try {
            future.get();
        } catch (CancellationException ce) {
            t = ce;
            logError("Copy task was cancelled", ce);
        } catch (ExecutionException ee) {
            t = ee.getCause();
            logError("Copy task failed with exception", t);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
    }
    if (t != null) {
        throw new IOException("At least one copy task failed with exception", t);
    }
}

From source file:at.molindo.notify.channel.mail.DirectMailClient.java

@Override
protected Session getSmtpSession(String recipient) throws MailException {
    try {/*from ww w  .j a va2 s. com*/
        return _sessionCache.get(MailUtils.domainFromAddress(recipient));
    } catch (ExecutionException e) {
        if (e.getCause() instanceof MailException) {
            throw (MailException) e.getCause();
        } else {
            throw new RuntimeException("unexpected exception while getting SMTP session for " + recipient, e);
        }
    }
}

From source file:och.util.socket.server.SocketServer.java

public void runWait() throws IOException {
    init();/*  ww w. j ava 2 s  . c o  m*/
    try {
        endFuture.get();
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof IOException)
            throw (IOException) cause;
        else
            log.error("error while " + name + " work", cause);
    } catch (Exception e) {
        //ok
    }
}

From source file:de.blizzy.documentr.markdown.macro.impl.NeighborsMacro.java

private Page getPage(String path) throws IOException {
    try {/* ww  w  .jav a  2  s. c o  m*/
        return pageCache.get(path);
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        } else {
            throw new RuntimeException(cause);
        }
    }
}