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:voldemort.utils.impl.CommandLineRemoteOperation.java

/**
 * Executes the given commands in parallel on the remote hosts and
 * aggregates the results for the caller.
 * /*from   ww  w  . j  a  va 2  s . co 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 {
    CommandLineParser commandLineParser = new CommandLineParser();

    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 = commandLineParser.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 AdHocDataProvider getAdHocDataProvider(final String name, final AccessMode mode,
        final Configuration conf, final ProviderProperties props) throws DataProviderNotFound {
    try {//from ww w.  j a  v  a2 s . co m
        // Make sure that ad hoc resources are cached uniquely per user
        String cacheKey = getResourceCacheKey(name, conf, props);
        if (mode == AccessMode.OVERWRITE || mode == AccessMode.WRITE) {
            invalidateCache(cacheKey);
        }
        return adHocProviderCache.get(cacheKey, new AdHocLoader(name, mode, conf, props));
    } catch (ExecutionException e) {
        if (e.getCause() instanceof DataProviderNotFound) {
            throw (DataProviderNotFound) e.getCause();
        }
        throw new DataProviderNotFound(e);
    }
}

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

private static VectorDataProvider getVectorDataProvider(final String name, AccessMode accessMode,
        final Configuration conf, final ProviderProperties providerProperties) throws DataProviderNotFound {
    try {//  w w w  .j  a va  2s  .c  o  m
        // Make sure that vector 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) {
            vectorProviderCache.invalidate(cacheKey);
        }
        return vectorProviderCache.get(cacheKey, new VectorLoader(name, accessMode, conf, providerProperties));
    } catch (ExecutionException e) {
        if (e.getCause() instanceof DataProviderNotFound) {
            throw (DataProviderNotFound) e.getCause();
        }
        throw new DataProviderNotFound(e);
    }
}

From source file:com.ok2c.lightmtp.impl.protocol.PipeliningReceiveEnvelopCodec.java

private SMTPReply getReply(final Future<SMTPReply> future) {
    try {/*from  w  ww .jav a 2 s. c o  m*/
        return future.get();
    } catch (ExecutionException ex) {
        Throwable cause = ex.getCause();
        if (cause == null) {
            cause = ex;
        }
        return new SMTPReply(SMTPCodes.ERR_PERM_TRX_FAILED, new SMTPCode(5, 3, 0), cause.getMessage());
    } catch (InterruptedException ex) {
        return new SMTPReply(SMTPCodes.ERR_PERM_TRX_FAILED, new SMTPCode(5, 3, 0), ex.getMessage());
    }
}

From source file:net.myrrix.online.eval.PrecisionRecallEvaluator.java

@Override
public EvaluationResult evaluate(final MyrrixRecommender recommender, final RescorerProvider provider,
        final Multimap<Long, RecommendedItem> testData) throws TasteException {

    final Mean precision = new Mean();
    final Mean recall = new Mean();
    final Mean ndcg = new Mean();
    final Mean meanAveragePrecision = new Mean();

    Processor<Long> processor = new Processor<Long>() {
        @Override//from   ww w  . j  a v a  2s  .c  o  m
        public void process(Long userID, long count) {

            Collection<RecommendedItem> values = testData.get(userID);
            int numValues = values.size();
            if (numValues == 0) {
                return;
            }

            IDRescorer rescorer = provider == null ? null
                    : provider.getRecommendRescorer(new long[] { userID }, recommender);

            List<RecommendedItem> recs;
            try {
                recs = recommender.recommend(userID, numValues, rescorer);
            } catch (NoSuchUserException nsue) {
                // Probably OK, just removed all data for this user from training
                log.warn("User only in test data: {}", userID);
                return;
            } catch (TasteException te) {
                log.warn("Unexpected exception", te);
                return;
            }
            int numRecs = recs.size();

            Collection<Long> valueIDs = Sets.newHashSet();
            for (RecommendedItem rec : values) {
                valueIDs.add(rec.getItemID());
            }

            int intersectionSize = 0;
            double score = 0.0;
            double maxScore = 0.0;
            Mean precisionAtI = new Mean();
            double averagePrecision = 0.0;

            for (int i = 0; i < numRecs; i++) {
                RecommendedItem rec = recs.get(i);
                double value = LN2 / Math.log(2.0 + i); // 1 / log_2(1 + (i+1))
                if (valueIDs.contains(rec.getItemID())) {
                    intersectionSize++;
                    score += value;
                    precisionAtI.increment(1.0);
                    averagePrecision += precisionAtI.getResult();
                } else {
                    precisionAtI.increment(0.0);
                }
                maxScore += value;
            }
            averagePrecision /= numValues;

            synchronized (precision) {
                precision.increment(numRecs == 0 ? 0.0 : (double) intersectionSize / numRecs);
                recall.increment((double) intersectionSize / numValues);
                ndcg.increment(maxScore == 0.0 ? 0.0 : score / maxScore);
                meanAveragePrecision.increment(averagePrecision);
                if (count % 10000 == 0) {
                    log.info(new IRStatisticsImpl(precision.getResult(), recall.getResult(), ndcg.getResult(),
                            meanAveragePrecision.getResult()).toString());
                }
            }
        }
    };

    Paralleler<Long> paralleler = new Paralleler<Long>(testData.keySet().iterator(), processor, "PREval");
    try {
        if (Boolean.parseBoolean(System.getProperty("eval.parallel", "true"))) {
            paralleler.runInParallel();
        } else {
            paralleler.runInSerial();
        }
    } catch (InterruptedException ie) {
        throw new TasteException(ie);
    } catch (ExecutionException e) {
        throw new TasteException(e.getCause());
    }

    EvaluationResult result;
    if (precision.getN() > 0) {
        result = new IRStatisticsImpl(precision.getResult(), recall.getResult(), ndcg.getResult(),
                meanAveragePrecision.getResult());
    } else {
        result = null;
    }
    log.info(String.valueOf(result));
    return result;
}

From source file:org.shredzone.cilla.plugin.flattr.collector.CollectingClickExecutor.java

@Override
public synchronized void run() {
    final List<SomeThingId> thingCollection = new ArrayList<>();
    final Map<String, Thing> thingResult = new HashMap<>();

    while (true) {
        try {//from ww w .j a  va  2  s.  co m
            synchronized (this) {
                while (queue.isEmpty()) {
                    wait();
                }
                ;
            }

            if (collectDelay > 0) {
                Thread.sleep(collectDelay);
            }

            synchronized (this) {
                while (!queue.isEmpty() && processQueue.size() < collectMaxItems) {
                    processQueue.add(queue.remove());
                }
            }

            thingCollection.clear();
            thingCollection
                    .addAll(processQueue.stream().map(ClickFuture::getThingId).collect(Collectors.toList()));

            GetThingsFromCollectionMethod method = new GetThingsFromCollectionMethod(thingCollection);
            List<Thing> things = flattrQueue.submit(method).get();

            for (Thing t : things) {
                thingResult.put(t.getThingId(), t);
                thingCollection.remove(new SomeThingId(t));
            }

            if (!thingCollection.isEmpty()) {
                log.debug("Could not find some flattr counts");
                thingCollection.forEach(flattrPublicationService::unpublished);
            }

        } catch (ExecutionException ex) {
            Throwable t = ex.getCause();
            if (t instanceof NotFoundException) {
                log.debug("Could not find all flattr counts", t);
                for (SomeThingId tid : thingCollection) {
                    flattrPublicationService.unpublished(tid);
                }
            } else {
                log.error("Cound not bulk get flattr counts", ex);
            }

        } catch (InterruptedException ex) {
            log.error("Cound not bulk get flattr counts", ex);

        } finally {
            // Make sure all ClickCallables are going to be triggered...
            processQueue.forEach(c -> c.filterResult(thingResult));

            // ...and feed the GC
            thingCollection.clear();
            thingResult.clear();
            processQueue.clear();
        }
    }
}

From source file:org.openspaces.grid.gsm.strategy.ElasticMachineProvisioningDiscoveredMachinesCache.java

public Collection<GridServiceAgent> getDiscoveredAgents()
        throws WaitingForDiscoveredMachinesException, FailedToDiscoverMachinesException {

    if (futureAgents == null || !futureAgents.isDone()) {
        throw new WaitingForDiscoveredMachinesException(pu, "Need to wait until retrieved list of machines.");
    }//w w  w.j  a  v a  2 s .c o  m

    GridServiceAgent[] agents = admin.getGridServiceAgents().getAgents(); // default value
    try {
        agents = futureAgents.get();

    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof Error) {
            throw (Error) cause;
        }

        if (cause instanceof ElasticMachineProvisioningException
                || cause instanceof ElasticGridServiceAgentProvisioningException
                || cause instanceof AdminException) {
            if (!quiteMode) {
                throw new FailedToDiscoverMachinesException(pu, e);
            }
            logger.info("Failed to discover machines", e);
        }

        else {
            throw new IllegalStateException("Unexpected exception type", e);
        }

    } catch (TimeoutException e) {
        if (!quiteMode) {
            throw new FailedToDiscoverMachinesException(pu, e);
        }
        logger.info("Failed to discover machines", e);
    }

    return MachinesSlaUtils.sortAndFilterAgents(agents, machineProvisioning.getConfig(), logger);
}

From source file:org.apache.hadoop.hbase.client.TestAsyncSingleRequestRpcRetryingCaller.java

@Test
public void testOperationTimeout() throws IOException, InterruptedException {
    long startNs = System.nanoTime();
    try {/*from ww w  . j  ava  2  s . c o m*/
        CONN.callerFactory.single().table(TABLE_NAME).row(ROW).operationTimeout(1, TimeUnit.SECONDS)
                .pause(100, TimeUnit.MILLISECONDS).maxAttempts(Integer.MAX_VALUE)
                .action((controller, loc, stub) -> failedFuture()).call().get();
        fail();
    } catch (ExecutionException e) {
        e.printStackTrace();
        assertThat(e.getCause(), instanceOf(RetriesExhaustedException.class));
    }
    long costNs = System.nanoTime() - startNs;
    assertTrue(costNs >= TimeUnit.SECONDS.toNanos(1));
    assertTrue(costNs < TimeUnit.SECONDS.toNanos(2));
}

From source file:com.asakusafw.runtime.util.cache.ConcurrentBatchFileCacheRepository.java

private Path handleException(Path file, ExecutionException e) throws IOException {
    Throwable cause = e.getCause();
    if (cause instanceof Error) {
        throw (Error) cause;
    } else if (cause instanceof RuntimeException) {
        throw (RuntimeException) cause;
    } else if (cause instanceof IOException) {
        return exceptionHandler.handle(file, (IOException) cause);
    } else if (cause instanceof InterruptedException) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(MessageFormat.format("Processing cache is cancelled: {0}", //$NON-NLS-1$
                    file), e);//  w  ww .j  a va 2s .  c  om
        }
        return null;
    } else {
        throw new IllegalStateException(
                MessageFormat.format("Unhandled exception while processing cache: {0}", file), e);
    }
}

From source file:burstcoin.jminer.core.network.task.NetworkSubmitPoolNonceTask.java

@Override
public void run() {
    try {//from  w  w  w. ja v a 2s .  c o m
        long gb = totalCapacity / 1000 / 1000 / 1000;

        ContentResponse response = httpClient.POST(poolServer + "/burst").param("requestType", "submitNonce")
                .param("accountId", numericAccountId).param("nonce", Convert.toUnsignedLong(nonce))
                .header("X-Miner", HEADER_MINER_NAME).header("X-Capacity", String.valueOf(gb))
                .timeout(connectionTimeout, TimeUnit.MILLISECONDS).send();

        if (response.getContentAsString().contains("errorCode")) {
            LOG.warn("Error: Submit nonce to pool not successful: " + response.getContentAsString());
        } else {
            SubmitResultResponse result = objectMapper.readValue(response.getContentAsString(),
                    SubmitResultResponse.class);

            if (result.getResult().equals("success")) {
                if (calculatedDeadline == result.getDeadline()) {
                    publisher.publishEvent(new NetworkResultConfirmedEvent(blockNumber, result.getDeadline(),
                            nonce, chunkPartStartNonce));
                } else {
                    // todo re-commit
                    publisher.publishEvent(new NetworkResultErrorEvent(blockNumber, nonce, calculatedDeadline,
                            result.getDeadline(), chunkPartStartNonce));
                }
            } else {
                LOG.warn("Error: Submit nonce to pool not successful: " + response.getContentAsString());
            }
        }
    } catch (TimeoutException timeoutException) {
        LOG.warn("Nonce was committed to pool, but not confirmed ... caused by connectionTimeout,"
                + " currently '" + (connectionTimeout / 1000) + " sec.' try increasing it!");
    } catch (ExecutionException e) {
        // inform user about reward assignment issue
        if (e.getCause() instanceof HttpResponseException) {
            HttpResponseException responseException = (HttpResponseException) e.getCause();
            if (responseException.getResponse() instanceof HttpContentResponse) {
                HttpContentResponse httpContentResponse = (HttpContentResponse) responseException.getResponse();
                LOG.warn("Error: Failed to submit nonce to pool: " + httpContentResponse.getContentAsString());
            }
        } else {
            LOG.warn("Error: Failed to submit nonce to pool: " + e.getMessage());
        }
    } catch (Exception e) {
        LOG.warn("Error: Failed to submit nonce to pool: " + e.getMessage());
    }
}