List of usage examples for java.lang InterruptedException getCause
public synchronized Throwable getCause()
From source file:de.blizzy.documentr.search.PageFinder.java
public SearchResult findPages(final String searchText, final int page, final Authentication authentication) throws ParseException, IOException, TimeoutException { Assert.hasLength(searchText);//ww w. ja v a 2 s . co m Assert.isTrue(page >= 1); Assert.notNull(authentication); IndexSearcher searcher = null; Future<SearchResult> findFuture = null; try { searcher = searcherManager.acquire(); final IndexSearcher indexSearcher = searcher; Callable<SearchResult> findCallable = new Callable<SearchResult>() { @Override public SearchResult call() throws ParseException, IOException, TimeoutException { return findPages(searchText, page, authentication, indexSearcher); } }; findFuture = taskExecutor.submit(findCallable); SearchTextSuggestion suggestion = getSearchTextSuggestion(searchText, authentication, indexSearcher); SearchResult result = findFuture.get(DocumentrConstants.INTERACTIVE_TIMEOUT, TimeUnit.SECONDS); result.setSuggestion(suggestion); return result; } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof ParseException) { throw (ParseException) cause; } else if (cause instanceof IOException) { throw (IOException) cause; } else if (cause instanceof TimeoutException) { throw (TimeoutException) cause; } else { throw Util.toRuntimeException(cause); } } finally { if (findFuture != null) { findFuture.cancel(false); } if (searcher != null) { searcherManager.release(searcher); } } }
From source file:org.marketcetera.util.except.ExceptUtilsTest.java
@Test public void interruptionNestedThrow() { CloneNotSupportedException nested = new CloneNotSupportedException(); Thread.currentThread().interrupt(); try {//from ww w .j a v a 2 s . c om ExceptUtils.checkInterruption(nested); fail(); } catch (InterruptedException ex) { assertTrue(Thread.interrupted()); assertEquals("Thread execution was interrupted", ex.getMessage()); assertEquals(nested, ex.getCause()); } }
From source file:de.blizzy.documentr.search.PageFinder.java
private SearchResult findPages(String searchText, int page, Authentication authentication, IndexSearcher searcher) throws ParseException, IOException, TimeoutException { Future<Query> queryFuture = taskExecutor.submit(new ParseQueryTask(searchText, analyzer)); ListenableFuture<Bits> visibleDocIdsFuture = taskExecutor.submit( new GetVisibleDocIdsTask(searcher, authentication, userStore, permissionEvaluator, taskExecutor)); Query query;//from w ww .jav a 2s. c o m TopDocs docs; try { query = queryFuture.get(DocumentrConstants.INTERACTIVE_TIMEOUT, TimeUnit.SECONDS); Bits visibleDocIds = visibleDocIdsFuture.get(DocumentrConstants.INTERACTIVE_TIMEOUT, TimeUnit.SECONDS); docs = searcher.search(query, new PagePermissionFilter(visibleDocIds), HITS_PER_PAGE * page); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof ParseException) { throw (ParseException) cause; } else { throw Util.toRuntimeException(cause); } } finally { queryFuture.cancel(false); visibleDocIdsFuture.cancel(false); } int start = HITS_PER_PAGE * (page - 1); int end = Math.min(HITS_PER_PAGE * page, docs.scoreDocs.length); IndexReader reader = searcher.getIndexReader(); List<ListenableFuture<SearchHit>> hitFutures = Lists.newArrayList(); for (int i = start; i < end; i++) { ListenableFuture<SearchHit> hitFuture = taskExecutor .submit(new GetSearchHitTask(query, reader, docs.scoreDocs[i].doc, analyzer)); hitFutures.add(hitFuture); } try { ListenableFuture<List<SearchHit>> allHitsFuture = Futures.allAsList(hitFutures); List<SearchHit> hits = allHitsFuture.get(DocumentrConstants.INTERACTIVE_TIMEOUT, TimeUnit.SECONDS); return new SearchResult(hits, docs.totalHits, HITS_PER_PAGE); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof IOException) { throw (IOException) cause; } else { throw Util.toRuntimeException(cause); } } finally { for (ListenableFuture<SearchHit> hitFuture : hitFutures) { hitFuture.cancel(false); } } }
From source file:org.apache.hadoop.hbase.backup.regionserver.LogRollBackupSubprocedurePool.java
/** * Wait for all of the currently outstanding tasks submitted via {@link #submitTask(Callable)} * @return <tt>true</tt> on success, <tt>false</tt> otherwise * @throws ForeignException exception//from ww w. jav a2s.c o m */ public boolean waitForOutstandingTasks() throws ForeignException { LOG.debug("Waiting for backup procedure to finish."); try { for (Future<Void> f : futures) { f.get(); } return true; } catch (InterruptedException e) { if (aborted) { throw new ForeignException("Interrupted and found to be aborted while waiting for tasks!", e); } Thread.currentThread().interrupt(); } catch (ExecutionException e) { if (e.getCause() instanceof ForeignException) { throw (ForeignException) e.getCause(); } throw new ForeignException(name, e.getCause()); } finally { // close off remaining tasks for (Future<Void> f : futures) { if (!f.isDone()) { f.cancel(true); } } } return false; }
From source file:cn.clxy.upload.UploadFileService.java
private String checkFuture(Future<String> future) { String result = null;/*from ww w . ja v a2 s . co m*/ try { result = future.get(); return result; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return null; } catch (ExecutionException e) { listener.onFail(result); log.error(e.getCause()); throw new RuntimeException(e.getCause()); } }
From source file:ch.cyberduck.core.cryptomator.features.CryptoChecksumCompute.java
protected Checksum compute(final InputStream in, final long offset, final ByteBuffer header, final NonceGenerator nonces) throws ChecksumException { if (log.isDebugEnabled()) { log.debug(String.format("Calculate checksum with header %s", header)); }/*from ww w .ja va2s. co m*/ try { final PipedOutputStream source = new PipedOutputStream(); final CryptoOutputStream<Void> out = new CryptoOutputStream<Void>(new VoidStatusOutputStream(source), cryptomator.getCryptor(), cryptomator.getCryptor().fileHeaderCryptor().decryptHeader(header), nonces, cryptomator.numberOfChunks(offset)); final PipedInputStream sink = new PipedInputStream(source, PreferencesFactory.get().getInteger("connection.chunksize")); final ThreadPool pool = ThreadPoolFactory.get("checksum", 1); try { final Future execute = pool.execute(new Callable<TransferStatus>() { @Override public TransferStatus call() throws Exception { if (offset == 0) { source.write(header.array()); } final TransferStatus status = new TransferStatus(); new StreamCopier(status, status).transfer(in, out); return status; } }); try { return delegate.compute(sink, new TransferStatus()); } finally { try { execute.get(); } catch (InterruptedException e) { throw new ChecksumException(LocaleFactory.localizedString("Checksum failure", "Error"), e.getMessage(), e); } catch (ExecutionException e) { if (e.getCause() instanceof BackgroundException) { throw (BackgroundException) e.getCause(); } throw new DefaultExceptionMappingService().map(e.getCause()); } } } finally { pool.shutdown(true); } } catch (ChecksumException e) { throw e; } catch (IOException | BackgroundException e) { throw new ChecksumException(LocaleFactory.localizedString("Checksum failure", "Error"), e.getMessage(), e); } }
From source file:dk.netarkivet.common.lifecycle.PeriodicTaskExecutor.java
/** * Checks tasks execution. Called by the checker thread. */// w ww. j ava 2 s . c o m private synchronized void checkExecution() { try { for (PeriodicTask t : tasks) { t.future.get(); } } catch (InterruptedException e) { if (log.isTraceEnabled()) { log.trace("checkExecution was interrupted."); } } catch (ExecutionException e) { log.error("Task threw exception: " + e.getCause(), e); } }
From source file:com.treasuredata.jdbc.TDResultSet.java
private ClientAPI.ExtUnpacker fetchRows() throws SQLException { JobSummary jobSummary = null;// ww w .j a v a 2 s. com Callable<JobSummary> callback = new Callable<JobSummary>() { @Override public JobSummary call() throws Exception { JobSummary jobSummary = clientApi.waitJobResult(job); return jobSummary; } }; Future<JobSummary> future = executor.submit(callback); try { if (queryTimeout <= 0) { jobSummary = future.get(); } else { jobSummary = future.get(queryTimeout, TimeUnit.SECONDS); } } catch (InterruptedException e) { // ignore } catch (TimeoutException e) { throw new SQLException(e); } catch (ExecutionException e) { throw new SQLException(e.getCause()); } if (jobSummary == null) { throw new SQLException("job result is null"); } try { initColumnNamesAndTypes(jobSummary.getResultSchema()); return clientApi.getJobResult2(job); } catch (ClientException e) { throw new SQLException(e); } }
From source file:com.echopf.ECHOInstallation.java
/** * Does Get registration id from the GCM server in a background thread. * // w w w. jav a 2 s . c o m * @param sync if set TRUE, then the main (UI) thread is waited for complete the fetching in a background thread. * (a synchronous communication) * @param callback invoked after the getting is completed * @throws ECHOException */ protected void doGetRegistrationId(final boolean sync, final InstallationCallback callback) throws ECHOException { // if(!checkPlayServices(ECHO.context)) return; // Get senderId from AndroidManifest.xml String senderId = null; try { ApplicationInfo appInfo = ECHO.context.getPackageManager() .getApplicationInfo(ECHO.context.getPackageName(), PackageManager.GET_META_DATA); senderId = appInfo.metaData.getString(GCM_SENDER_ID_KEY); senderId = (senderId.startsWith("id:")) ? senderId.substring(3) : null; } catch (NameNotFoundException ignored) { // skip } if (senderId == null) throw new RuntimeException("`" + GCM_SENDER_ID_KEY + "` is not specified in `AndroidManifest.xml`."); // Get ready a background thread final Handler handler = new Handler(); final String fSenderId = senderId; ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<Object> communictor = new Callable<Object>() { @Override public Object call() throws ECHOException { ECHOException exception = null; // InstanceID instanceID = InstanceID.getInstance(ECHO.context); String token = null; // Get updated InstanceID token. token = FirebaseInstanceId.getInstance().getToken(); // Log.d(TAG, "Refreshed token: " + refreshedToken); // TODO: Implement this method to send any registration to your app's servers. // token = instanceID.getToken(fSenderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE); synchronized (lock) { deviceToken = token; } if (sync == false) { // Execute a callback method in the main (UI) thread. final ECHOException fException = exception; final String fToken = token; handler.post(new Runnable() { @Override public void run() { ECHOInstallation.this.deviceToken = fToken; callback.done(fException); } }); } else { if (exception != null) throw exception; } return null; } }; Future<Object> future = executor.submit(communictor); if (sync) { try { future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // ignore/reset } catch (ExecutionException e) { Throwable e2 = e.getCause(); if (e2 instanceof ECHOException) { throw (ECHOException) e2; } throw new RuntimeException(e2); } } }
From source file:org.peercast.pecaport.PecaPortService.java
private void onWANConnection(WanConnection wanConnection) { String serviceId = wanConnection.getService().getServiceId().getId(); if (wanConnection.getExternalIp() == null || wanConnection.getStatus() != Connection.Status.Connected) { logger.finest("Disconnected: " + serviceId); return;/*from ww w .j a va 2s .c o m*/ } PecaPortPreferences pref = PecaPortPreferences.from(this); NetworkIdentity identity = new NetworkIdentity(this, mActiveNicInfo, wanConnection.getService()); if (pref.getAllDisabledNetworks().contains(identity)) { logger.finest(String.format("Denied: serviceId=%s. ", serviceId)); return; } final List<PortMapping> mappings = wanConnection.getMappingEntries(); PortManipulator.OnResultListener listener = new PortManipulator.OnResultListener() { @Override public void onSuccess(Method m, RemoteService service, PortMapping mapping) { //?? if (m == Method.Add) { mappings.add(mapping); } else { for (ListIterator<PortMapping> it = mappings.listIterator(); it.hasNext();) { if (it.next().getExternalPort().equals(mapping.getExternalPort())) { it.remove(); break; } } } String msg = getString(R.string.t_log_success) + String.format("\n%sPortMapping %s", m, mapping); logger.info(msg.replace("\n", "")); showToast(msg); } @Override public void onFailure(Method m, RemoteService service, PortMapping mapping, String errMsg) { String msg = getString(R.string.t_log_failed) + String.format("\n%sPortMapping %s %s", m, mapping, errMsg); logger.severe(msg.replace("\n", "")); showToast(msg); } }; while (!mTasks.isEmpty()) { PecaPortServiceTask task = mTasks.poll(); if (task.needExecute(mappings)) { logger.info(getString(R.string.t_log_fmt_try_mapping, task.method, serviceId, task.port)); Future f = task.execute(wanConnection.getManipulator(), listener); try { f.get(); } catch (InterruptedException e) { Log.w(TAG, "! Interrupted !", e); } catch (ExecutionException e) { throw new RuntimeException(e.getCause()); } } } }