List of usage examples for java.util.concurrent ExecutionException getCause
public synchronized Throwable getCause()
From source file:org.swiftshire.nifi.processors.kinesis.producer.PutKinesisStream.java
/** * {@inheritDoc}/*from ww w .jav a 2 s .co m*/ */ @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { final int batchSize = context.getProperty(BATCH_SIZE).asInteger(); List<FlowFile> flowFiles = session.get(batchSize); if (flowFiles == null || flowFiles.size() == 0) { return; } final String stream = context.getProperty(KINESIS_STREAM_NAME).getValue(); final ComponentLog log = getLogger(); try { List<Future<UserRecordResult>> addRecordFutures = new ArrayList<>(); // Prepare batch of records for (FlowFile flowFile1 : flowFiles) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile1, baos); String partitionKey = context.getProperty(KINESIS_PARTITION_KEY) .evaluateAttributeExpressions(flowFile1).getValue(); if (StringUtils.isBlank(partitionKey)) { partitionKey = Integer.toString(randomGenerator.nextInt()); } addRecordFutures.add( getProducer().addUserRecord(stream, partitionKey, ByteBuffer.wrap(baos.toByteArray()))); } // Apply attributes to flow files List<FlowFile> failedFlowFiles = new ArrayList<>(); List<FlowFile> successfulFlowFiles = new ArrayList<>(); for (int i = 0; i < addRecordFutures.size(); i++) { Future<UserRecordResult> future = addRecordFutures.get(i); FlowFile flowFile = flowFiles.get(i); UserRecordResult userRecordResult; try { userRecordResult = future.get(); } catch (ExecutionException ex) { // Handle exception from individual record Throwable cause = ex.getCause(); if (cause instanceof UserRecordFailedException) { UserRecordFailedException urfe = (UserRecordFailedException) cause; userRecordResult = urfe.getResult(); } else { session.transfer(flowFile, REL_FAILURE); log.error("Failed to publish to Kinesis {} record {}", new Object[] { stream, flowFile }); continue; } } Map<String, String> attributes = createAttributes(userRecordResult); flowFile = session.putAllAttributes(flowFile, attributes); if (!userRecordResult.isSuccessful()) { failedFlowFiles.add(flowFile); } else { successfulFlowFiles.add(flowFile); } } if (failedFlowFiles.size() > 0) { session.transfer(failedFlowFiles, REL_FAILURE); log.error("Failed to publish to {} records to Kinesis {}", new Object[] { failedFlowFiles.size(), stream }); } if (successfulFlowFiles.size() > 0) { session.transfer(successfulFlowFiles, REL_SUCCESS); if (log.isInfoEnabled()) { log.info("Successfully published {} records to Kinesis {}", new Object[] { successfulFlowFiles, stream }); } } } catch (final Exception ex) { log.error("Failed to publish to Kinesis {} with exception {}", new Object[] { stream, ex }); session.transfer(flowFiles, REL_FAILURE); context.yield(); } }
From source file:annis.gui.QueryController.java
private boolean checkFutureMatchesFinished() { List<Match> result = null; try {//from w ww . j a v a 2 s . c om result = futureMatches.get(100, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { log.warn(null, ex); } catch (ExecutionException root) { if (lastResultView != null && lastResultView.getPaging() != null) { PagingComponent paging = lastResultView.getPaging(); Throwable cause = root.getCause(); if (cause instanceof UniformInterfaceException) { UniformInterfaceException ex = (UniformInterfaceException) cause; if (ex.getResponse().getStatus() == 400) { paging.setInfo("parsing error: " + ex.getResponse().getEntity(String.class)); } else if (ex.getResponse().getStatus() == 504) // gateway timeout { paging.setInfo("Timeout: query exeuction took too long"); } else { paging.setInfo("unknown error: " + ex); } } else { log.error("Unexcepted ExecutionException cause", root); } } } catch (TimeoutException ex) { // we ignore this return false; } lastResultView.setResult(result, lastQuery.getContextLeft(), lastQuery.getContextRight(), lastQuery.getSegmentation(), lastQuery.getOffset()); futureMatches = null; return true; }
From source file:org.jodconverter.office.OfficeProcessManagerPoolEntryITest.java
/** * Tests that an office process is restarted successfully after a crash. * * @throws Exception if an error occurs. *//* www .ja v a 2 s.co m*/ @Test public void execute_WhenOfficeProcessCrash_ShouldRestartAfterCrash() throws Exception { final OfficeProcessManagerPoolEntry officeManager = new OfficeProcessManagerPoolEntry(CONNECT_URL); try { officeManager.start(); assertThat(officeManager.isRunning()).isTrue(); assertThat(officeManager) .extracting("officeProcessManager.process.running", "officeProcessManager.connection.connected") .containsExactly(true, true); // Submit the task to an executor final ExecutorService pool = Executors.newFixedThreadPool(1); try { final Callable<Boolean> task = new RestartAfterCrashTask(officeManager); final Future<Boolean> future = pool.submit(task); Thread.sleep(500); // NOSONAR // Simulate crash final Process underlyingProcess = (Process) FieldUtils.readField(getOfficeProcess(officeManager), "process", true); assertThat(underlyingProcess).isNotNull(); LOGGER.debug("Simulating the crash"); underlyingProcess.destroy(); // Wait until the task is completed try { future.get(); fail("Exception expected"); } catch (ExecutionException ex) { assertThat(ex.getCause()).isInstanceOf(OfficeException.class); assertThat(ex.getCause().getCause()).isInstanceOf(CancellationException.class); } } finally { pool.shutdownNow(); } assertRestartedAndReconnected(officeManager, RESTART_INITIAL_WAIT, RESTART_WAIT_TIMEOUT); final MockOfficeTask goodTask = new MockOfficeTask(); officeManager.execute(goodTask); assertThat(goodTask.isCompleted()).isTrue(); } finally { officeManager.stop(); assertThat(officeManager.isRunning()).isFalse(); assertThat(officeManager) .extracting("officeProcessManager.process.running", "officeProcessManager.connection.connected") .containsExactly(false, false); assertThat(getOfficeProcess(officeManager).getExitCode(0, 0)).isEqualTo(0); } }
From source file:fr.duminy.jbackup.core.JBackupImplTest.java
protected void waitResult(Future<Void> future) throws Throwable { assertThat(future).isNotNull();//from w w w . ja v a 2 s . c o m try { future.get(); // block until finished and maybe throw an Exception if task has thrown one. } catch (ExecutionException e) { throw e.getCause(); } }
From source file:org.apache.hadoop.hive.metastore.HiveClientCache.java
/** * Return from cache if exists else create/cache and return * @param cacheKey/* w w w .jav a 2s .c o m*/ * @return * @throws IOException * @throws MetaException * @throws LoginException */ private ICacheableMetaStoreClient getOrCreate(final HiveClientCacheKey cacheKey) throws IOException, MetaException, LoginException { try { return hiveCache.get(cacheKey, new Callable<ICacheableMetaStoreClient>() { @Override public ICacheableMetaStoreClient call() throws MetaException { // This is called from HCat, so always allow embedded metastore (as was the default). return (ICacheableMetaStoreClient) RetryingMetaStoreClient.getProxy(cacheKey.getHiveConf(), new Class<?>[] { HiveConf.class, Integer.class, Boolean.class }, new Object[] { cacheKey.getHiveConf(), timeout, true }, CacheableHiveMetaStoreClient.class.getName()); } }); } catch (ExecutionException e) { Throwable t = e.getCause(); if (t instanceof IOException) { throw (IOException) t; } else if (t instanceof MetaException) { throw (MetaException) t; } else if (t instanceof LoginException) { throw (LoginException) t; } else { throw new IOException("Error creating hiveMetaStoreClient", t); } } }
From source file:org.openhab.binding.gardena.internal.GardenaSmartImpl.java
/** * Communicates with Gardena Smart Home and parses the result. *//* w ww. j a v a 2s . c o m*/ private synchronized <T> T executeRequest(HttpMethod method, String url, Object contentObject, Class<T> result) throws GardenaException { try { if (logger.isTraceEnabled()) { logger.trace("{} request: {}", method, url); if (contentObject != null) { logger.trace("{} data : {}", method, gson.toJson(contentObject)); } } Request request = httpClient.newRequest(url).method(method) .timeout(config.getConnectionTimeout(), TimeUnit.SECONDS) .header(HttpHeader.CONTENT_TYPE, "application/json") .header(HttpHeader.ACCEPT, "application/json").header(HttpHeader.ACCEPT_ENCODING, "gzip"); if (contentObject != null) { StringContentProvider content = new StringContentProvider(gson.toJson(contentObject)); request.content(content); } if (!result.equals(SessionWrapper.class)) { verifySession(); request.header("X-Session", session.getToken()); } ContentResponse contentResponse = request.send(); int status = contentResponse.getStatus(); if (logger.isTraceEnabled()) { logger.trace("Status : {}", status); logger.trace("Response: {}", contentResponse.getContentAsString()); } if (status == 500) { throw new GardenaException( gson.fromJson(contentResponse.getContentAsString(), Errors.class).toString()); } else if (status != 200 && status != 204) { throw new GardenaException(String.format("Error %s %s", status, contentResponse.getReason())); } if (result == NoResult.class) { return null; } return gson.fromJson(contentResponse.getContentAsString(), result); } catch (ExecutionException ex) { Throwable cause = ex.getCause(); if (cause instanceof HttpResponseException) { HttpResponseException responseException = (HttpResponseException) ex.getCause(); int status = responseException.getResponse().getStatus(); if (status == 401) { throw new GardenaUnauthorizedException(ex.getCause()); } } throw new GardenaException(ex.getMessage(), ex); } catch (Exception ex) { throw new GardenaException(ex.getMessage(), ex); } }
From source file:com.streamsets.pipeline.stage.origin.tcp.TestTCPServerSource.java
@Test public void errorHandling() throws StageException, IOException, ExecutionException, InterruptedException { final Charset charset = Charsets.ISO_8859_1; final TCPServerSourceConfig configBean = createConfigBean(charset); configBean.dataFormat = DataFormat.JSON; configBean.tcpMode = TCPMode.DELIMITED_RECORDS; configBean.recordSeparatorStr = "\n"; configBean.ports = NetworkUtils.getRandomPorts(1); final TCPServerSource source = new TCPServerSource(configBean); final String outputLane = "lane"; final PushSourceRunner toErrorRunner = new PushSourceRunner.Builder(TCPServerDSource.class, source) .addOutputLane(outputLane).setOnRecordError(OnRecordError.TO_ERROR).build(); final List<Record> records = new LinkedList<>(); final List<Record> errorRecords = new LinkedList<>(); runAndCollectRecords(toErrorRunner, configBean, records, errorRecords, 1, outputLane, "{\"invalid_json\": yes}\n".getBytes(charset), true, false); assertThat(records, empty());/*ww w . jav a 2s . c o m*/ assertThat(errorRecords, hasSize(1)); assertThat(errorRecords.get(0).getHeader().getErrorCode(), equalTo(com.streamsets.pipeline.lib.parser.Errors.DATA_PARSER_04.getCode())); final PushSourceRunner discardRunner = new PushSourceRunner.Builder(TCPServerDSource.class, source) .addOutputLane(outputLane).setOnRecordError(OnRecordError.DISCARD).build(); records.clear(); errorRecords.clear(); configBean.ports = NetworkUtils.getRandomPorts(1); runAndCollectRecords(discardRunner, configBean, records, errorRecords, 1, outputLane, "{\"invalid_json\": yes}\n".getBytes(charset), true, false); assertThat(records, empty()); assertThat(errorRecords, empty()); configBean.ports = NetworkUtils.getRandomPorts(1); final PushSourceRunner stopPipelineRunner = new PushSourceRunner.Builder(TCPServerDSource.class, source) .addOutputLane(outputLane).setOnRecordError(OnRecordError.STOP_PIPELINE).build(); records.clear(); errorRecords.clear(); try { runAndCollectRecords(stopPipelineRunner, configBean, records, errorRecords, 1, outputLane, "{\"invalid_json\": yes}\n".getBytes(charset), true, true); Assert.fail("ExecutionException should have been thrown"); } catch (ExecutionException e) { assertThat(e.getCause(), instanceOf(RuntimeException.class)); final RuntimeException runtimeException = (RuntimeException) e.getCause(); assertThat(runtimeException.getCause(), instanceOf(StageException.class)); final StageException stageException = (StageException) runtimeException.getCause(); assertThat(stageException.getErrorCode().getCode(), equalTo(Errors.TCP_06.getCode())); } }
From source file:org.mrgeo.hdfs.tile.HdfsMrsTileReader.java
/** * This method will Get a MapFile.Reader for the partition specified * /*from w ww. j a v a2s . c om*/ * @param partition * is the particular reader being accessed * @return the reader for the partition specified * @throws IOException */ public MapFile.Reader getReader(final int partition) throws IOException { try { return readerCache.get(partition); } catch (ExecutionException e) { if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } throw new IOException(e); } // // get the reader from the LRU cache // MapFile.Reader reader = readers.get(partition); // // // set the cache if needed // if (reader == null) // { // final String part = partitions.get(partition); // final Path path = new Path(imagePath, part); // final FileSystem fs = path.getFileSystem(conf); // // reader = new MapFile.Reader(fs, path.toString(), conf); // readers.put(partition, reader); // // if (profile) // { // LeakChecker.instance().add( // reader, // ExceptionUtils.getFullStackTrace(new Throwable( // "HdfsMrsVectorReader creation stack(ignore the Throwable...)"))); // } // LOG.debug("opening (not in cache) partition: {} file: {}", partition, part); // } // // return reader; }
From source file:de.fiz.ddb.aas.auxiliaryoperations.ThreadOrganisationSetApprove.java
@PreAuthorize(privileges = { PrivilegeEnum.ADMIN }, scope = Scope.ORGANIZATION, cacheUpdate = true) public Organisation call() throws AASUnauthorizedException, ExecutionException, IllegalAccessException { if (ConstEnumOrgStatus.approved.equals(this._organisation.getStatus())) { throw new ExecutionException("Die Institution ist bereits in der Status 'approved'.", null); }/*w w w.ja v a 2s. com*/ Future<Organisation> submitOrgOnWorkDir = null; Future<Organisation> submitOrgOnLicencedDir = null; Future<Organisation> submitOrgParentOnLicencedDir = null; Future<Organisation> submitOrgParentOnWorkDir = null; Organisation vOrgParentOnLicenceDir = null; Organisation vOrgParentOnWorkDir = null; try { // -- set a new status: this._organisation.setStatus(ConstEnumOrgStatus.approved); // -- save status: ThreadOrganisationUpdate threadOrganisationUpdate = new ThreadOrganisationUpdate(_ready, _organisation, false, _performer); threadOrganisationUpdate.setChangeOfStatus(true); submitOrgOnWorkDir = LDAPConnector.getSingletonInstance().getExecutorServiceOne() .submit(threadOrganisationUpdate); // -- Ist diese Organisation unter Licensed schon vorhanden? // -- Read organization on the license directory: ThreadOrganisationRead threadOrgOnLicencedDirRead = new ThreadOrganisationRead( new OIDs(this._organisation.getOIDs().getOrgName(), false), this.getPerformer()); // -- the request goes to the branch with licensed organizations: threadOrgOnLicencedDirRead.setLicensedOrgs(true); submitOrgOnLicencedDir = LDAPConnector.getSingletonInstance().getExecutorServiceOne() .submit(threadOrgOnLicencedDirRead); // -- Operations in the licensed area... Boolean vIsOrgParentLicense = null; if (this._organisation.getOrgParent() != null) { // -- Parent on the license directory: ThreadOrganisationRead threadOrgParentOnLicencedDirRead = new ThreadOrganisationRead( new OIDs(this._organisation.getOrgParent(), false), this.getPerformer()); // -- the request goes to the branch with licensed organizations: threadOrgParentOnLicencedDirRead.setLicensedOrgs(true); submitOrgParentOnLicencedDir = LDAPConnector.getSingletonInstance().getExecutorServiceOne() .submit(threadOrgParentOnLicencedDirRead); // -- Parent on the work directory: ThreadOrganisationRead threadOrgParentOnWorkDirRead = new ThreadOrganisationRead( new OIDs(this._organisation.getOrgParent(), false), this.getPerformer()); // -- the request goes to the branch with licensed organizations: submitOrgParentOnWorkDir = LDAPConnector.getSingletonInstance().getExecutorServiceOne() .submit(threadOrgParentOnWorkDirRead); // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // -- Parent on the license directory: try { //vIsOrgParentLicense = (threadOrgParentOnLicencedDirRead.call() != null); vIsOrgParentLicense = ((vOrgParentOnLicenceDir = submitOrgParentOnLicencedDir.get(3, TimeUnit.SECONDS)) != null); } /* catch (NameNotFoundException ex) { // hier gibt es keinen Grund zur Panik! ;-) vIsOrgParentLicense = Boolean.FALSE; } */ catch (ExecutionException ex) { if ((ex.getCause() != null) && (ex.getCause().getClass().isAssignableFrom(NameNotFoundException.class))) { // hier gibt es keinen Grund zur Panik! ;-) vIsOrgParentLicense = Boolean.FALSE; } else { throw ex; } } catch (InterruptedException ex) { throw new ExecutionException(ex); } catch (TimeoutException ex) { throw new ExecutionException(ex); } } try { // -- Update abwarten this._organisation = submitOrgOnWorkDir.get(3, TimeUnit.SECONDS); // -- die Organisation wenn mglich in der lizenzierte Verzeichnis schreiben: if ((vIsOrgParentLicense == null) || (vIsOrgParentLicense.booleanValue())) { // -- ! This institution is classified to the licensed organizations: Organisation vOrgOnLicensedDir = null; try { vOrgOnLicensedDir = submitOrgOnLicencedDir.get(3, TimeUnit.SECONDS); if (!vOrgOnLicensedDir.getOrgRDN().equalsIgnoreCase(this._organisation.getOrgRDN())) { /* * The shift operation works beautifully but may cause to error, because there are * potential changes from the sub-organizations in the Work Directory will not be included. * ...therefore the Orgnanisation is first deleted and then will be re-copied ThreadOrganisationMove threadOrganisationMove = new ThreadOrganisationMove(vOrgOnLicensedDir.getOIDs().getOrgName(), this._organisation .getOrgParent(), true, _performer); vOrgOnLicensedDir = threadOrganisationMove.call(); */ this.deletingFromLicensedOrgsDir(vOrgOnLicensedDir); // -- !!! very important for further processing: vOrgOnLicensedDir = null; } } /* catch (NameNotFoundException ex) { // es gibt keinen Grund zur Panik! ;-) } */ catch (ExecutionException ex) { if ((ex.getCause() != null) && (ex.getCause().getClass().isAssignableFrom(NameNotFoundException.class))) { // hier gibt es keinen Grund zur Panik... } else { // hier aber schon... throw ex; } } catch (InterruptedException ex) { throw new ExecutionException(ex); } catch (TimeoutException ex) { throw new ExecutionException(ex); } if (vOrgOnLicensedDir != null) { if (!ConstEnumOrgStatus.revised.equals(this._oldStatus)) { // -- This should be never happen: LOG.log(Level.WARNING, "The old status is not ''revised'' but this organization is between the Licensed: this should never be happen! Old status: ''{0}''", this._oldStatus.name()); } // -- !!! The organization could not be moved: if (vOrgOnLicensedDir.getOrgRDN().equals(this._organisation.getOrgRDN())) { // -- Update licensed organization: try { threadOrganisationUpdate = new ThreadOrganisationUpdate(_ready, _organisation, false, _performer); threadOrganisationUpdate.setUpdatingOfLicensedOrgs(true); threadOrganisationUpdate.call(); } catch (NameNotFoundException ex) { throw new ExecutionException(ex); } catch (AttributeModificationException ex) { throw new ExecutionException(ex); } } else { LOG.log(Level.WARNING, "The licensed (RDN='" + vOrgOnLicensedDir.getOrgRDN() + "') organization can not be updated because it has been postponed to new RDN='" + this._organisation.getOrgRDN() + "'"); } } else { // -- Der Knoten sollte kopiert werden aber nur unter einem Bedingung... if (submitOrgParentOnWorkDir != null) { // -- Parent on the work directory: try { vOrgParentOnWorkDir = submitOrgParentOnWorkDir.get(3, TimeUnit.SECONDS); } catch (ExecutionException ex) { if ((ex.getCause() != null) && (ex.getCause().getClass() .isAssignableFrom(NameNotFoundException.class))) { // hier gibt es keinen Grund zur Panik! ;-) } else { throw ex; } } catch (InterruptedException ex) { throw new ExecutionException(ex); } catch (TimeoutException ex) { throw new ExecutionException(ex); } } // ...dass die RDN des Parnts- Knoten stimmt, das heit, dass die nicht verschoben wurde: if (((vOrgParentOnWorkDir != null) && (vOrgParentOnLicenceDir != null) && (vOrgParentOnWorkDir.getOrgRDN().equals(vOrgParentOnLicenceDir.getOrgRDN()))) || ((vOrgParentOnWorkDir == null) && (vOrgParentOnLicenceDir == null))) { this.copyingToLicensedOrgs(_organisation); } } } } catch (InterruptedException ex) { throw new ExecutionException(ex); } catch (TimeoutException ex) { throw new ExecutionException(ex); } } finally { if ((submitOrgOnWorkDir != null) && (!submitOrgOnWorkDir.isDone()) && (!submitOrgOnWorkDir.isCancelled())) { submitOrgOnWorkDir.cancel(true); } if ((submitOrgOnLicencedDir != null) && (!submitOrgOnLicencedDir.isDone()) && (!submitOrgOnLicencedDir.isCancelled())) { submitOrgOnLicencedDir.cancel(true); } if ((submitOrgParentOnWorkDir != null) && (!submitOrgParentOnWorkDir.isDone()) && (!submitOrgParentOnWorkDir.isCancelled())) { submitOrgParentOnWorkDir.cancel(true); } if ((submitOrgParentOnLicencedDir != null) && (!submitOrgParentOnLicencedDir.isDone()) && (!submitOrgParentOnLicencedDir.isCancelled())) { submitOrgParentOnLicencedDir.cancel(true); } } return this._organisation; }
From source file:com.cloudant.sync.replication.BasicPullStrategy.java
/** * Handle exceptions in separate run() method to allow replicate() to * just return when cancel is set to true rather than having to keep * track of whether we terminated via an error in replicate(). *///ww w. j ava 2 s . c o m @Override public void run() { ErrorInfo errorInfo = null; try { replicate(); } catch (ExecutionException ex) { logger.log(Level.SEVERE, String.format("Batch %s ended with error:", this.batchCounter), ex); errorInfo = new ErrorInfo(ex.getCause()); } catch (Throwable e) { logger.log(Level.SEVERE, String.format("Batch %s ended with error:", this.batchCounter), e); errorInfo = new ErrorInfo(e); } finally { this.executor.shutdownNow(); } // Give the in-flight HTTP requests time to complete. It's not vital // for correctness that we do this, but nice to give the remote server // some breathing room. try { this.executor.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException e) { // do nothing } replicationTerminated = true; String msg = "Push replication terminated via "; msg += this.cancel ? "cancel." : "completion."; // notify complete/errored on eventbus logger.info(msg + " Posting on EventBus."); if (errorInfo == null) { // successful replication eventBus.post(new ReplicationStrategyCompleted(this)); } else { eventBus.post(new ReplicationStrategyErrored(this, errorInfo)); } }