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:com.teradata.benchto.driver.jdbc.ConnectionPoolTest.java

private void openGivenConnectionsAmountSimultaneously(String dataSourceName, int connectionsCount)
        throws SQLException, InterruptedException, TimeoutException {
    ExecutorService executorService = newFixedThreadPool(connectionsCount);
    ExecutorCompletionService<?> completionService = new ExecutorCompletionService(executorService);
    CountDownLatch countDownLatch = new CountDownLatch(connectionsCount);
    DataSource dataSource = applicationContext.getBean(dataSourceName, DataSource.class);

    range(0, connectionsCount).mapToObj(i -> createQueryRunnable(dataSource, countDownLatch))
            .forEach(completionService::submit);

    try {/*w ww .ja v  a  2  s . co  m*/
        for (int i = 0; i < connectionsCount; i++) {
            try {
                Future<?> future = completionService.take();
                future.get(1, MINUTES);
            } catch (ExecutionException e) {
                rethrowException(e.getCause());
            }
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } finally {
        executorService.shutdownNow();
        executorService.awaitTermination(1, MINUTES);
    }
}

From source file:org.terracotta.management.registry.ManagementRegistryTest.java

@Test
public void test_management_registry_exposes() throws IOException {
    ManagementRegistry registry = new AbstractManagementRegistry() {
        @Override/*from w w  w.  j  a v a2  s .c o  m*/
        public ContextContainer getContextContainer() {
            return new ContextContainer("cacheManagerName", "my-cm-name");
        }
    };

    registry.addManagementProvider(new MyManagementProvider());

    registry.register(new MyObject("myCacheManagerName", "myCacheName1"));
    registry.register(new MyObject("myCacheManagerName", "myCacheName2"));

    Scanner scanner = new Scanner(ManagementRegistryTest.class.getResourceAsStream("/capabilities.json"),
            "UTF-8").useDelimiter("\\A");
    String expectedJson = scanner.next();
    scanner.close();

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    mapper.addMixIn(CapabilityContext.class, CapabilityContextMixin.class);

    String actual = mapper.writeValueAsString(registry.getCapabilities());
    System.out.println(expectedJson);
    System.out.println(actual);
    assertEquals(expectedJson, actual);

    ContextualReturn<?> cr = registry.withCapability("TheActionProvider")
            .call("incr", int.class, new Parameter(Integer.MAX_VALUE, "int")).on(Context.empty()
                    .with("cacheManagerName", "myCacheManagerName").with("cacheName", "myCacheName1"))
            .build().execute().getSingleResult();

    try {
        cr.getValue();
        fail();
    } catch (ExecutionException e) {
        assertEquals(IllegalArgumentException.class, e.getCause().getClass());
    }
}

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

@Test
public void testTimeout() throws InterruptedException, ExecutionException {
    SLEEP_MS = 1000;//from w  w w  .j av a 2 s  .  c  om
    long startNs = System.nanoTime();
    try {
        LOCATOR.getRegionLocation(TABLE_NAME, EMPTY_START_ROW, RegionLocateType.CURRENT,
                TimeUnit.MILLISECONDS.toNanos(500)).get();
        fail();
    } catch (ExecutionException e) {
        assertThat(e.getCause(), instanceOf(TimeoutIOException.class));
    }
    long costMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    assertTrue(costMs >= 500);
    assertTrue(costMs < 1000);
    // wait for the background task finish
    Thread.sleep(2000);
    // Now the location should be in cache, so we will not visit meta again.
    HRegionLocation loc = LOCATOR.getRegionLocation(TABLE_NAME, EMPTY_START_ROW, RegionLocateType.CURRENT,
            TimeUnit.MILLISECONDS.toNanos(500)).get();
    assertEquals(loc.getServerName(), TEST_UTIL.getHBaseCluster().getRegionServer(0).getServerName());
}

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

public EvaluationResult evaluate(final MyrrixRecommender recommender, final FastByIDMap<FastIDSet> testData)
        throws TasteException {

    final AtomicInteger underCurve = new AtomicInteger(0);
    final AtomicInteger total = new AtomicInteger(0);

    final long[] allItemIDs = recommender.getAllItemIDs().toArray();

    Processor<Long> processor = new Processor<Long>() {
        private final RandomGenerator random = RandomManager.getRandom();

        @Override//w  w w.  j  a v a2s .  co  m
        public void process(Long userID, long count) throws ExecutionException {
            FastIDSet testItemIDs = testData.get(userID);
            int numTest = testItemIDs.size();
            for (int i = 0; i < numTest; i++) {

                long randomTestItemID;
                long randomTrainingItemID;
                synchronized (random) {
                    randomTestItemID = RandomUtils.randomFrom(testItemIDs, random);
                    do {
                        randomTrainingItemID = allItemIDs[random.nextInt(allItemIDs.length)];
                    } while (testItemIDs.contains(randomTrainingItemID));
                }

                float relevantEstimate;
                float nonRelevantEstimate;
                try {
                    relevantEstimate = recommender.estimatePreference(userID, randomTestItemID);
                    nonRelevantEstimate = recommender.estimatePreference(userID, randomTrainingItemID);
                } catch (NoSuchItemException nsie) {
                    // OK; it's possible item only showed up in test split
                    continue;
                } catch (NoSuchUserException nsie) {
                    // OK; it's possible user only showed up in test split
                    continue;
                } catch (TasteException te) {
                    throw new ExecutionException(te);
                }

                if (relevantEstimate > nonRelevantEstimate) {
                    underCurve.incrementAndGet();
                }
                total.incrementAndGet();

                if (count % 100000 == 0) {
                    log.info("AUC: {}", (double) underCurve.get() / total.get());
                }
            }
        }
    };

    try {
        new Paralleler<Long>(testData.keySetIterator(), processor, "AUCEval").runInParallel();
    } catch (InterruptedException ie) {
        throw new TasteException(ie);
    } catch (ExecutionException e) {
        throw new TasteException(e.getCause());
    }

    double score = (double) underCurve.get() / total.get();
    log.info("AUC: {}", score);
    return new EvaluationResultImpl(score);
}

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

@Test
public void test() throws InterruptedException, ExecutionException {
    SLEEP_MS = 1000;/*from  w w w.ja va 2s.  co m*/
    long startNs = System.nanoTime();
    try {
        LOCATOR.getRegionLocation(TABLE_NAME, EMPTY_START_ROW, RegionLocateType.CURRENT,
                TimeUnit.MILLISECONDS.toNanos(500)).get();
        fail();
    } catch (ExecutionException e) {
        e.printStackTrace();
        assertThat(e.getCause(), instanceOf(TimeoutIOException.class));
    }
    long costMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    assertTrue(costMs >= 500);
    assertTrue(costMs < 1000);
    // wait for the background task finish
    Thread.sleep(2000);
    // Now the location should be in cache, so we will not visit meta again.
    HRegionLocation loc = LOCATOR.getRegionLocation(TABLE_NAME, EMPTY_START_ROW, RegionLocateType.CURRENT,
            TimeUnit.MILLISECONDS.toNanos(500)).get();
    assertEquals(loc.getServerName(), TEST_UTIL.getHBaseCluster().getRegionServer(0).getServerName());
}

From source file:com.collective.celos.ci.mode.TestTask.java

void waitForCompletion(List<Future> futures) throws Throwable {
    List<Throwable> throwables = Lists.newArrayList();
    for (Future future : futures) {
        try {/*from  www . ja  v  a 2 s . co m*/
            future.get();
        } catch (ExecutionException ee) {
            throwables.add(ee.getCause());
        }
    }
    if (!throwables.isEmpty()) {
        List<Throwable> throwablesWOLast = throwables.subList(0, throwables.size() - 1);
        for (Throwable t : throwablesWOLast) {
            t.printStackTrace();
        }
        Throwable lastThrowable = throwables.get(throwables.size() - 1);
        throw lastThrowable;
    }
}

From source file:com.github.fge.jsonschema.load.SchemaLoader.java

/**
 * Get a schema tree from the given URI/* w ww .j  a v  a 2  s  .c o  m*/
 *
 * <p>Note that if the URI is relative, it will be resolved against this
 * registry's namespace, if any.</p>
 *
 * @param uri the URI
 * @return a schema tree
 * @throws ProcessingException URI is not an absolute JSON reference, or
 * failed to dereference this URI
 * @throws JsonReferenceError URI is null
 */
public SchemaTree get(final URI uri) throws ProcessingException {
    final JsonRef ref = namespace.resolve(JsonRef.fromURI(uri));

    if (!ref.isAbsolute())
        throw new ProcessingException(BUNDLE.message("uriNotAbsolute").put("uri", ref));

    final URI realURI = ref.toURI();

    try {
        final JsonNode node = cache.get(realURI);
        return dereferencing.newTree(ref, node);
    } catch (ExecutionException e) {
        throw (ProcessingException) e.getCause();
    }
}

From source file:org.apache.cassandra.service.StorageProxy.java

public static List<Row> getRangeSlice(RangeSliceCommand command, ConsistencyLevel consistency_level)
        throws IOException, UnavailableException, TimeoutException {
    if (logger.isDebugEnabled())
        logger.debug(command.toString());
    long startTime = System.nanoTime();
    List<Row> rows;//from   w w  w.j a v a 2s. c  o m
    // now scan until we have enough results
    try {
        rows = new ArrayList<Row>(command.max_keys);
        List<AbstractBounds> ranges = getRestrictedRanges(command.range);
        for (AbstractBounds range : ranges) {
            List<InetAddress> liveEndpoints = StorageService.instance.getLiveNaturalEndpoints(command.keyspace,
                    range.right);
            DatabaseDescriptor.getEndpointSnitch().sortByProximity(FBUtilities.getLocalAddress(),
                    liveEndpoints);

            if (consistency_level == ConsistencyLevel.ONE && !liveEndpoints.isEmpty()
                    && liveEndpoints.get(0).equals(FBUtilities.getLocalAddress())) {
                if (logger.isDebugEnabled())
                    logger.debug("local range slice");
                ColumnFamilyStore cfs = Table.open(command.keyspace)
                        .getColumnFamilyStore(command.column_family);
                try {
                    rows.addAll(cfs.getRangeSlice(command.super_column, range, command.max_keys,
                            QueryFilter.getFilter(command.predicate, cfs.getComparator())));
                } catch (ExecutionException e) {
                    throw new RuntimeException(e.getCause());
                } catch (InterruptedException e) {
                    throw new AssertionError(e);
                }
            } else {
                RangeSliceCommand c2 = new RangeSliceCommand(command.keyspace, command.column_family,
                        command.super_column, command.predicate, range, command.max_keys);

                // collect replies and resolve according to consistency level
                RangeSliceResponseResolver resolver = new RangeSliceResponseResolver(command.keyspace,
                        liveEndpoints);
                ReadCallback<Iterable<Row>> handler = getReadCallback(resolver, command, consistency_level,
                        liveEndpoints);
                handler.assureSufficientLiveNodes();
                for (InetAddress endpoint : liveEndpoints) {
                    MessagingService.instance().sendRR(c2, endpoint, handler);
                    if (logger.isDebugEnabled())
                        logger.debug("reading " + c2 + " from " + endpoint);
                }

                try {
                    for (Row row : handler.get()) {
                        rows.add(row);
                        logger.debug("range slices read {}", row.key);
                    }
                } catch (TimeoutException ex) {
                    if (logger.isDebugEnabled())
                        logger.debug("Range slice timeout: {}", ex.toString());
                    throw ex;
                } catch (DigestMismatchException e) {
                    throw new AssertionError(e); // no digests in range slices yet
                }
            }

            // if we're done, great, otherwise, move to the next range
            if (rows.size() >= command.max_keys)
                break;
        }
    } finally {
        rangeStats.addNano(System.nanoTime() - startTime);
    }
    return rows.size() > command.max_keys ? rows.subList(0, command.max_keys) : rows;
}

From source file:android.support.test.espresso.base.ThreadPoolExecutorExtractor.java

public Optional<ThreadPoolExecutor> getCompatAsyncTaskThreadPool() {
    try {/*www .j ava  2 s  .c o  m*/
        return runOnMainThread(new FutureTask<Optional<ThreadPoolExecutor>>(MODERN_ASYNC_TASK_EXTRACTOR)).get();
    } catch (InterruptedException ie) {
        throw new RuntimeException("Interrupted while trying to get the compat async executor!", ie);
    } catch (ExecutionException ee) {
        throw new RuntimeException(ee.getCause());
    }
}

From source file:org.apache.hadoop.hdfs.server.datanode.web.webhdfs.DataNodeUGIProvider.java

UserGroupInformation ugi() throws IOException {
    UserGroupInformation ugi;/*  www  . j  ava  2 s  .  c om*/

    try {
        if (UserGroupInformation.isSecurityEnabled()) {
            final Token<DelegationTokenIdentifier> token = params.delegationToken();

            ugi = ugiCache.get(buildTokenCacheKey(token), new Callable<UserGroupInformation>() {
                @Override
                public UserGroupInformation call() throws Exception {
                    return tokenUGI(token);
                }
            });
        } else {
            final String usernameFromQuery = params.userName();
            final String doAsUserFromQuery = params.doAsUser();
            final String remoteUser = usernameFromQuery == null ? JspHelper.getDefaultWebUserName(params.conf()) // not specified in request
                    : usernameFromQuery;

            ugi = ugiCache.get(buildNonTokenCacheKey(doAsUserFromQuery, remoteUser),
                    new Callable<UserGroupInformation>() {
                        @Override
                        public UserGroupInformation call() throws Exception {
                            return nonTokenUGI(usernameFromQuery, doAsUserFromQuery, remoteUser);
                        }
                    });
        }
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        } else {
            throw new IOException(cause);
        }
    }

    return ugi;
}