List of usage examples for java.util.concurrent ExecutionException getCause
public synchronized Throwable getCause()
From source file:com.microsoft.azure.keyvault.extensions.test.KeyVaultKeyResolverDefaultProviderTest.java
@Test public void KeyVault_KeyVaultKeyResolver_Secret192Base64() throws InterruptedException, ExecutionException { // Arrange// w w w.j ava 2s .co m byte[] keyBytes = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 }; byte[] CEK = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF }; byte[] EK = { (byte) 0x96, 0x77, (byte) 0x8B, 0x25, (byte) 0xAE, 0x6C, (byte) 0xA4, 0x35, (byte) 0xF9, 0x2B, 0x5B, (byte) 0x97, (byte) 0xC0, 0x50, (byte) 0xAE, (byte) 0xD2, 0x46, (byte) 0x8A, (byte) 0xB8, (byte) 0xA1, 0x7A, (byte) 0xD8, 0x4E, 0x5D }; try { SetSecretRequest request = new SetSecretRequest.Builder(getVaultUri(), SECRET_NAME, _base64.encodeAsString(keyBytes)).withContentType("application/octet-stream").build(); SecretBundle secretBundle = keyVaultClient.setSecret(request); if (secretBundle != null) { try { // ctor with client KeyVaultKeyResolver resolver = new KeyVaultKeyResolver(keyVaultClient); IKey baseKey = resolver.resolveKeyAsync(secretBundle.secretIdentifier().baseIdentifier()).get(); IKey versionKey = resolver.resolveKeyAsync(secretBundle.secretIdentifier().identifier()).get(); // Check for correct key identifiers Assert.assertEquals(baseKey.getKid(), versionKey.getKid()); // Ensure key operations give the expected results byte[] encrypted = null; try { encrypted = baseKey.wrapKeyAsync(CEK, "A192KW").get().getLeft(); if (!_unlimited) fail("Expected ExecutionException"); } catch (ExecutionException e) { // In the limited case, the failure should be InvalidKeyException // In the unlimited case, this should not fail if (!_unlimited) { Throwable cause = e.getCause(); if (cause == null || !(cause instanceof InvalidKeyException)) fail("ExecutionException"); } else { fail("ExecutionException"); } } catch (Exception ex) { fail(ex.getMessage()); } if (_unlimited) { // Assert assertArrayEquals(EK, encrypted); try { encrypted = versionKey.wrapKeyAsync(CEK, "A192KW").get().getLeft(); } catch (Exception ex) { fail(ex.getMessage()); } // Assert assertArrayEquals(EK, encrypted); } } finally { // Delete the key keyVaultClient.deleteSecret(getVaultUri(), SECRET_NAME); } } } catch (Exception ex) { fail(ex.getMessage()); } }
From source file:com.xylocore.cassandra.query.PagedQuery.java
/** * FILLIN//from w w w . j a v a 2s .c om * * @param aQueryContext * @param aCassandraFuture */ private void processQueryCompletion(QueryContext aQueryContext, ResultSetFuture aCassandraFuture) { logger.debug("entering processQueryCompletion"); try { ResultSet myResultSet = aCassandraFuture.get(); aQueryContext.setResultSet(myResultSet); processResultSet(aQueryContext, (myNoResults) -> { resultSetComplete(aQueryContext, myNoResults); }); } catch (ExecutionException myExecutionException) { aQueryContext.getFuture().completeExceptionally(myExecutionException.getCause()); } catch (InterruptedException myInterruptedException) { aQueryContext.getFuture().completeExceptionally(myInterruptedException); } catch (CancellationException myCancellationException) { aQueryContext.getFuture().cancel(true); } catch (Exception myException) { aQueryContext.getFuture().completeExceptionally(myException); } finally { logger.debug("exiting processQueryCompletion"); } }
From source file:io.druid.query.lookup.LookupReferencesManager.java
/** * @return a map with successful lookups *//*from w w w . j ava 2s. co m*/ private Map<String, LookupExtractorFactoryContainer> startLookups(List<LookupBean> lookupBeans, CompletionService<Map.Entry<String, LookupExtractorFactoryContainer>> completionService) throws InterruptedException { for (LookupBean lookupBean : lookupBeans) { completionService.submit(() -> startLookup(lookupBean)); } Map<String, LookupExtractorFactoryContainer> successfulLookups = new HashMap<>(); for (int i = 0; i < lookupBeans.size(); i++) { Future<Map.Entry<String, LookupExtractorFactoryContainer>> completedFuture = completionService.take(); try { Map.Entry<String, LookupExtractorFactoryContainer> lookupResult = completedFuture.get(); if (lookupResult != null) { successfulLookups.put(lookupResult.getKey(), lookupResult.getValue()); } } catch (ExecutionException e) { LOG.error(e.getCause(), "Exception while starting a lookup"); // not adding to successfulLookups } } return successfulLookups; }
From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java
@Test public void invoke_onOkRequest_onIOException_futureCompletesExceptionally() throws IOException, TimeoutException, ExecutionException, InterruptedException { String instanceId = "123456789"; Req req = new Req(); Channel channel = mock(Channel.class); doAnswer(invocation -> {// w w w . jav a2s.c om throw new IOException("boom"); }).when(channel).basicPublish(anyString(), any(), any(), any()); CompletableFuture<Res> answer = new CompletableFuture<>(); ResponseReceiver receiver = mock(ResponseReceiver.class); doReturn(answer).when(receiver).put(anyString(), any()); ChannelProvider channelProvider = mock(ChannelProvider.class); doReturn(channel).when(channelProvider).provide(instanceId, receiver); doReturn(DEFAULT_RPC_EXCHANGE).when(channelProvider).rpcExchange(); RemoteInvoker invoker = new AmqpInvokerImpl(instanceId, channelProvider, receiver); CompletableFuture<Res> actual = invoker.invoke(req, Res.class); assertSame(answer, actual); assertTrue(actual.isDone()); assertTrue(actual.isCompletedExceptionally()); exception.expect(ExecutionException.class); try { actual.get(); } catch (ExecutionException ex) { assertTrue(ex.getCause() instanceof IOException); throw ex; } }
From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java
@Test public void invoke_onNokRequest_onIllegalArgEx_futureCompletesExceptionally() throws IOException, TimeoutException, ExecutionException, InterruptedException { String instanceId = "123456789"; Req req = new Req(); Channel channel = mock(Channel.class); CompletableFuture<Res> answer = new CompletableFuture<>(); ResponseReceiver receiver = mock(ResponseReceiver.class); doReturn(answer).when(receiver).put(anyString(), any()); ChannelProvider channelProvider = mock(ChannelProvider.class); doReturn(channel).when(channelProvider).provide(instanceId, receiver); ObjectMapper mapper = mock(ObjectMapper.class); doThrow(IllegalArgumentException.class).when(mapper).writeValueAsBytes(any()); RemoteInvoker invoker = new AmqpInvokerImpl(instanceId, channelProvider, receiver, new DefaultRequestRouter(), new UidGenerator() { }, new DefaultSerializer(mapper), Maps.newHashMap()); CompletableFuture<Res> actual = invoker.invoke(req, Res.class); assertSame(answer, actual);//w w w .ja v a 2 s . c o m assertTrue(actual.isDone()); assertTrue(actual.isCompletedExceptionally()); exception.expect(ExecutionException.class); try { actual.get(); } catch (ExecutionException ex) { assertTrue(ex.getCause() instanceof IllegalArgumentException); throw ex; } }
From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java
@Test public void invoke_onNokRequest_onEncodingEx_futureCompletesExceptionally() throws IOException, TimeoutException, ExecutionException, InterruptedException { String instanceId = "123456789"; Req req = new Req(); Channel channel = mock(Channel.class); CompletableFuture<Res> answer = new CompletableFuture<>(); ResponseReceiver receiver = mock(ResponseReceiver.class); doReturn(answer).when(receiver).put(anyString(), any()); ChannelProvider channelProvider = mock(ChannelProvider.class); doReturn(channel).when(channelProvider).provide(instanceId, receiver); ObjectMapper mapper = mock(ObjectMapper.class); doThrow(JsonProcessingException.class).when(mapper).writeValueAsBytes(any()); RemoteInvoker invoker = new AmqpInvokerImpl(instanceId, channelProvider, receiver, new DefaultRequestRouter(), new UidGenerator() { }, new DefaultSerializer(mapper), Maps.newHashMap()); CompletableFuture<Res> actual = invoker.invoke(req, Res.class); assertSame(answer, actual);//w w w. j a v a 2s. co m assertTrue(actual.isDone()); assertTrue(actual.isCompletedExceptionally()); exception.expect(ExecutionException.class); try { actual.get(); } catch (ExecutionException ex) { assertTrue(ex.getCause() instanceof EncodingException); throw ex; } }
From source file:org.grouplens.lenskit.eval.traintest.TrainTestEvalTask.java
private void runEvaluations(DAGNode<JobGraph.Node, JobGraph.Edge> graph) throws TaskExecutionException, InterruptedException { int nthreads = getProject().getConfig().getThreadCount(); TaskGraphExecutor exec;/*from ww w . j ava 2 s .com*/ logger.info("Running evaluator with {} threads", nthreads); if (nthreads == 1) { exec = TaskGraphExecutor.singleThreaded(); } else { exec = TaskGraphExecutor.create(nthreads); } try { exec.execute(graph); } catch (ExecutionException e) { Throwables.propagateIfInstanceOf(e.getCause(), TaskExecutionException.class); throw new TaskExecutionException("error in evaluation job task", e.getCause()); } }
From source file:annis.gui.resultfetch.ResultFetchJob.java
@Override public void run() { WebResource subgraphRes = Helper.getAnnisWebResource().path("query/search/subgraph"); // holds the ids of the matches. MatchGroup result;/*from w w w . j a va 2s . co m*/ try { if (Thread.interrupted()) { return; } // set the the progress bar, for given the user some information about the loading process ui.accessSynchronously(new Runnable() { @Override public void run() { resultPanel.showMatchSearchInProgress(query); } }); // get the matches result = futureMatches.get(); // get the subgraph for each match, when the result is not empty if (result.getMatches().isEmpty()) { // check if thread was interrupted if (Thread.interrupted()) { return; } // nothing found, so inform the user about this. ui.access(new Runnable() { @Override public void run() { resultPanel.showNoResult(); } }); } else { if (Thread.interrupted()) { return; } // since annis found something, inform the user that subgraphs are created ui.access(new Runnable() { @Override public void run() { resultPanel.showSubgraphSearchInProgress(query, 0.0f); } }); // prepare fetching subgraphs final int totalResultSize = result.getMatches().size(); final BlockingQueue<SaltProject> queue = new ArrayBlockingQueue<>(totalResultSize); int current = 0; for (Match m : result.getMatches()) { if (Thread.interrupted()) { return; } List<Match> subList = new LinkedList<>(); subList.add(m); final SaltProject p = executeQuery(subgraphRes, new MatchGroup(subList), query.getLeftContext(), query.getRightContext(), query.getSegmentation(), SubgraphFilter.all); queue.put(p); log.debug("added match {} to queue", current + 1); if (current == 0) { PollControl.changePollingTime(ui, PollControl.DEFAULT_TIME); ui.access(new Runnable() { @Override public void run() { resultPanel.setQueryResultQueue(queue, query, totalResultSize); } }); } if (Thread.interrupted()) { return; } current++; } } // end if no results } catch (InterruptedException ex) { // just return } catch (final ExecutionException root) { ui.accessSynchronously(new Runnable() { @Override public void run() { if (resultPanel != null && resultPanel.getPaging() != null) { PagingComponent paging = resultPanel.getPaging(); Throwable cause = root.getCause(); if (cause instanceof UniformInterfaceException) { UniformInterfaceException ex = (UniformInterfaceException) cause; if (ex.getResponse().getStatus() == 400) { List<AqlParseError> errors = ex.getResponse() .getEntity(new GenericType<List<AqlParseError>>() { }); String errMsg = Joiner.on(" | ").join(errors); paging.setInfo("parsing error: " + errMsg); } else if (ex.getResponse().getStatus() == 504) { paging.setInfo("Timeout: query exeuction took too long"); } else if (ex.getResponse().getStatus() == 403) { paging.setInfo("Not authorized to query this corpus."); } else { paging.setInfo("unknown error: " + ex); } } else { log.error("Unexcepted ExecutionException cause", root); } resultPanel.showFinishedSubgraphSearch(); } } }); } // end catch }
From source file:com.netflix.dyno.queues.redis.RedisDynoQueue.java
private <R> R executeWithRetry(ExecutorService es, Callable<R> r, int retryCount) { try {/*from w w w.ja v a 2 s .com*/ return es.submit(r).get(1, TimeUnit.MINUTES); } catch (ExecutionException e) { if (e.getCause() instanceof DynoException) { if (retryCount < this.retryCount) { return executeWithRetry(es, r, ++retryCount); } } throw new RuntimeException(e.getCause()); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.geomajas.plugin.rasterizing.layer.RasterDirectLayer.java
@Override public void draw(Graphics2D graphics, MapContent map, MapViewport viewport) { try {// www . ja v a 2 s.c o m if (tiles.size() > 0) { Collection<Callable<ImageResult>> callables = new ArrayList<Callable<ImageResult>>(tiles.size()); // Build the image downloading threads for (RasterTile tile : tiles) { RasterImageDownloadCallable downloadThread = new RasterImageDownloadCallable( DOWNLOAD_MAX_ATTEMPTS, tile); callables.add(downloadThread); } // Loop until all images are downloaded or timeout is reached long totalTimeout = DOWNLOAD_TIMEOUT + DOWNLOAD_TIMEOUT_ONE_TILE * tiles.size(); log.debug("=== total timeout (millis): {}", totalTimeout); ExecutorService service = Executors.newFixedThreadPool(DOWNLOAD_MAX_THREADS); List<Future<ImageResult>> futures = service.invokeAll(callables, totalTimeout, TimeUnit.MILLISECONDS); // determine the pixel bounds of the mosaic Bbox pixelBounds = getPixelBounds(tiles); // create the images for the mosaic List<RenderedImage> images = new ArrayList<RenderedImage>(); for (Future<ImageResult> future : futures) { ImageResult result = null; if (future.isDone()) { try { result = future.get(); // create a rendered image if (result.getImage() != null && result.getImage().length > 0) { RenderedImage image = JAI.create("stream", new ByteArraySeekableStream(result.getImage())); // convert to common direct color model (some images have their own indexed color model) RenderedImage colored = toDirectColorModel(image); // translate to the correct position in the tile grid double xOffset = result.getRasterImage().getCode().getX() * tileWidth - pixelBounds.getX(); double yOffset; // TODO: in some cases, the y-index is up (e.g. WMS), should be down for // all layers !!!! if (isYIndexUp(tiles)) { yOffset = result.getRasterImage().getCode().getY() * tileHeight - pixelBounds.getY(); } else { yOffset = (pixelBounds.getMaxY() - (result.getRasterImage().getCode().getY() + 1) * tileHeight); } log.debug("adding to(" + xOffset + "," + yOffset + "), url = " + result.getRasterImage().getUrl()); RenderedImage translated = TranslateDescriptor.create(colored, (float) xOffset, (float) yOffset, new InterpolationNearest(), null); images.add(translated); } } catch (ExecutionException e) { addLoadError(graphics, (ImageException) (e.getCause()), viewport); log.warn(MISSING_TILE_IN_MOSAIC + e.getMessage()); } catch (Exception e) { log.warn("Missing tile " + result.getRasterImage().getUrl()); log.warn(MISSING_TILE_IN_MOSAIC + e.getMessage()); } } } if (images.size() > 0) { ImageLayout imageLayout = new ImageLayout(0, 0, (int) pixelBounds.getWidth(), (int) pixelBounds.getHeight()); imageLayout.setTileWidth(tileWidth); imageLayout.setTileHeight(tileHeight); // create the mosaic image ParameterBlock pbMosaic = new ParameterBlock(); pbMosaic.add(MosaicDescriptor.MOSAIC_TYPE_OVERLAY); for (RenderedImage renderedImage : images) { pbMosaic.addSource(renderedImage); } RenderedOp mosaic = JAI.create("mosaic", pbMosaic, new RenderingHints(JAI.KEY_IMAGE_LAYOUT, imageLayout)); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); log.debug("rendering to buffer..."); ImageIO.write(mosaic, "png", baos); log.debug("rendering done, size = " + baos.toByteArray().length); RasterTile mosaicTile = new RasterTile(); mosaicTile.setBounds(getWorldBounds(tiles)); log.info("application bounds = " + mosaicTile.getBounds()); ImageResult mosaicResult = new ImageResult(mosaicTile); mosaicResult.setImage(baos.toByteArray()); addImage(graphics, mosaicResult, viewport); } catch (IOException e) { log.warn("could not write mosaic image " + e.getMessage()); } } } } catch (InterruptedException e) { log.warn("rendering {} to {} failed : ", getTitle(), viewport.getBounds()); } }