List of usage examples for java.util.concurrent ExecutionException getCause
public synchronized Throwable getCause()
From source file:com.lithium.flow.filer.CachedReadFiler.java
@Override @Nonnull// w w w . j a va2 s . co m public InputStream readFile(@Nonnull String path) throws IOException { checkNotNull(path); Pair<Long, byte[]> pair = cache.getIfPresent(path); if (pair != null && pair.getLeft().equals(super.getRecord(path).getTime())) { return new ByteArrayInputStream(pair.getRight()); } try { return new ByteArrayInputStream(cache.get(path).getRight()); } catch (ExecutionException e) { if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } else { throw new IOException(e); } } }
From source file:org.ownchan.server.joint.scheduler.service.SchedulerService.java
private Throwable unwrapExecutionExceptionIfPossible(Exception ex) { if (ex instanceof ExecutionException) { ExecutionException execEx = (ExecutionException) ex; return execEx.getCause(); }//from ww w .j av a 2s . co m return ex; }
From source file:com.github.tomakehurst.wiremock.ResponseDelaySynchronousFailureAcceptanceTest.java
@Test public void requestIsFailedWhenMultipleRequestsHitSynchronousServer() throws Exception { stubFor(get(urlEqualTo("/delayed")) .willReturn(aResponse().withStatus(200).withFixedDelay(SHORTER_THAN_SOCKET_TIMEOUT))); List<Future<HttpResponse>> responses = httpClientExecutor.invokeAll(getHttpRequestCallables(10)); try {//w ww . jav a 2 s. c o m for (Future<HttpResponse> response : responses) { assertThat(response.get().getStatusLine().getStatusCode(), is(200)); } fail("A timeout exception expected reading multiple responses from synchronous WireMock server"); } catch (ExecutionException e) { assertThat(e.getCause(), instanceOf(SocketTimeoutException.class)); assertThat(e.getCause().getMessage(), is("Read timed out")); } }
From source file:com.github.jknack.handlebars.cache.GuavaTemplateCache.java
@Override public Template get(final TemplateSource source, final Parser parser) throws IOException { notNull(source, "The source is required."); notNull(parser, "The parser is required."); try {//from w w w.j av a 2s. c om return cache.get(source, new Callable<Template>() { @Override public Template call() throws IOException { return parser.parse(source); } }); } catch (ExecutionException ex) { throw launderThrowable(source, ex.getCause()); } }
From source file:com.streamsets.pipeline.stage.destination.hdfs.writer.DefaultFsHelper.java
@Override public Path getPath(FileSystem fs, Date recordDate, Record record) throws StageException, IOException { // runUuid is fixed for the current pipeline run. it avoids collisions with other SDCs running the same/similar // pipeline/*from w ww .j av a 2s . co m*/ try { return dirPathCache.get(recordWriterManager.getDirPath(recordDate, record)); } catch (ExecutionException ex) { if (ex.getCause() instanceof StageException) { throw (StageException) ex.getCause(); } else { throw new StageException(Errors.HADOOPFS_24, ex.toString(), ex); } } }
From source file:com.cloudera.oryx.kmeans.computation.local.KMeansLocalGenerationRunner.java
@Override protected void runSteps() throws IOException, InterruptedException, JobException { String instanceDir = getInstanceDir(); int generationID = getGenerationID(); String generationPrefix = Namespaces.getInstanceGenerationPrefix(instanceDir, generationID); File currentInboundDir = Files.createTempDir(); currentInboundDir.deleteOnExit();//from ww w .j av a2s. co m File tempOutDir = Files.createTempDir(); tempOutDir.deleteOnExit(); try { Store store = Store.get(); store.downloadDirectory(generationPrefix + "inbound/", currentInboundDir); Summary summary = new Summarize(currentInboundDir).call(); if (summary == null) { // No summary created, bail out. return; } List<List<RealVector>> foldVecs = new Standarize(currentInboundDir, summary).call(); List<List<WeightedRealVector>> weighted = new WeightedPointsByFold(foldVecs).call(); List<KMeansEvaluationData> evalData = new ClusteringEvaluation(weighted).call(); ClusteringModelBuilder b = new ClusteringModelBuilder(summary); DataDictionary dictionary = b.getDictionary(); List<Model> models = Lists.newArrayList(); List<String> stats = Lists.newArrayList(); for (KMeansEvaluationData data : evalData) { stats.add(data.getClusterValidityStatistics().toString()); ClusteringModel cm = b.build(data.getName(generationPrefix), data.getBest()); models.add(cm); } Files.write(Joiner.on("\n").join(stats) + '\n', new File(tempOutDir, "cluster_stats.csv"), Charsets.UTF_8); KMeansPMML.write(new File(tempOutDir, "model.pmml.gz"), dictionary, models); store.uploadDirectory(generationPrefix, tempOutDir, false); } catch (ExecutionException ee) { throw new JobException(ee.getCause()); } finally { IOUtils.deleteRecursively(tempOutDir); } }
From source file:com.couchbase.client.internal.HttpFutureTest.java
@Test public void testCancellation() throws Exception { CountDownLatch latch = new CountDownLatch(1); long timeout = 1000; HttpFuture<CancellableOperation> future = new HttpFuture<CancellableOperation>(latch, timeout); HttpOperation op = new CancellableOperation(); latch.countDown();/* w w w .ja v a2 s.com*/ future.setOperation(op); future.cancel(true); try { future.get(); assertTrue("Future did not throw ExecutionException", false); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof CancellationException); assertEquals("Cancelled", e.getCause().getMessage()); } catch (Exception e) { assertTrue(e.getMessage(), false); } }
From source file:org.springframework.batch.integration.async.AsyncItemWriter.java
/** * In the processing of the {@link java.util.concurrent.Future}s passed, nulls are <em>not</em> passed to the * delegate since they are considered filtered out by the {@link org.springframework.batch.integration.async.AsyncItemProcessor}'s * delegated {@link org.springframework.batch.item.ItemProcessor}. If the unwrapping * of the {@link Future} results in an {@link ExecutionException}, that will be * unwrapped and the cause will be thrown. * * @param items {@link java.util.concurrent.Future}s to be upwrapped and passed to the delegate * @throws Exception/*from w w w .jav a 2s . c om*/ */ public void write(List<? extends Future<T>> items) throws Exception { List<T> list = new ArrayList<T>(); for (Future<T> future : items) { try { T item = future.get(); if (item != null) { list.add(future.get()); } } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause != null && cause instanceof Exception) { logger.debug("An exception was thrown while processing an item", e); throw (Exception) cause; } else { throw e; } } } delegate.write(list); }
From source file:org.gss_project.gss.server.ejb.TransactionHelper.java
/** * Execute the supplied command until it completes, ignoring transaction * rollbacks. Try at least TRANSACTION_RETRIES times before giving up, * each time waiting a random amount of time, using an exponential * backoff scheme. See http://en.wikipedia.org/wiki/Exponential_backoff * for the basic idea./*from w ww . jav a 2s . c o m*/ * * @param command the command to execute * @return the value returned by the command * @throws Exception any other exception thrown by the command */ public T tryExecute(final Callable<T> command) throws Exception { T returnValue = null; // Schedule a Future task to call the command after delay milliseconds. int delay = 0; ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); for (int i = 0; i < TRANSACTION_RETRIES; i++) { final int retry = i; ScheduledFuture<T> future = executor.schedule(new Callable<T>() { @Override public T call() throws Exception { return command.call(); } }, delay, TimeUnit.MILLISECONDS); try { returnValue = future.get(); break; } catch (ExecutionException e) { Throwable cause = e.getCause(); if (!(cause instanceof EJBTransactionRolledbackException) || retry == TRANSACTION_RETRIES - 1) { logger.info("Transaction retry #" + (i + 1) + " failed due to " + cause); executor.shutdownNow(); if (cause instanceof Exception) throw (Exception) cause; if (cause instanceof Error) throw (Error) cause; } delay = MIN_TIMEOUT + (int) (MIN_TIMEOUT * Math.random() * (i + 1)); String origCause = cause.getCause() == null ? cause.getClass().getName() : cause.getCause().getClass().getName(); logger.info( "Transaction retry #" + (i + 1) + " scheduled in " + delay + " msec due to " + origCause); } } executor.shutdownNow(); return returnValue; }
From source file:org.codehaus.httpcache4j.cache.ConcurrentCacheStorageAbstractTest.java
@Test public void test1000InsertsOfSameURI() throws InterruptedException { final HTTPRequest request = new HTTPRequest(URI.create("GET")); List<Callable<HTTPResponse>> calls = new ArrayList<Callable<HTTPResponse>>(); for (int i = 0; i < 1000; i++) { calls.add(new Callable<HTTPResponse>() { public HTTPResponse call() throws Exception { return cacheStorage.insert(request, createCacheResponse()); }/*ww w . jav a 2s .c om*/ }); } List<Future<HTTPResponse>> responses = service.invokeAll(calls); for (Future<HTTPResponse> response : responses) { try { HTTPResponse real = response.get(); assertResponse(real); } catch (ExecutionException e) { fail(e.getCause().getMessage()); } } assertEquals(1, cacheStorage.size()); }