List of usage examples for java.util.concurrent FutureTask get
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
From source file:org.sipfoundry.sipxconfig.xmlrpc.XmlRpcClientInterceptor.java
/** * Temporary workaround for the problem with timeout (or lack thereof) in the XML/RPC library * transport.//from ww w. j a va 2 s. com * * We call the XML/RPC in the background thread and interrupt it if it takes too long. We * attempt to handle exceptions related to the threading issues (And timeout) only. Everything * else is handled by the invoke method. * * @param request XML/RPC request * @return result of XML/RPC call */ private Object executeWithTimeout(final XmlRpcClientRequest request) throws Throwable { Callable execute = new Callable() { public Object call() throws IOException { try { Object result = m_xmlRpcClient.execute(request); // strangely execute returns exceptions, instead of throwing them if (result instanceof XmlRpcException) { // let catch block translate it throw (XmlRpcException) result; } return result; } catch (XmlRpcException e) { LOG.error("XML/RPC error: ", e); // in cases execute throws exception - we still need to translate throw new XmlRpcRemoteException(e); } } }; FutureTask task = new FutureTask(execute); m_service.execute(task); try { return task.get(m_timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new XmlRpcRemoteException(e); } catch (TimeoutException e) { LOG.error("Timeout in XML/RPC call"); throw new XmlRpcRemoteException(e); } catch (ExecutionException e) { // rethrow cause and let us to repackage it below throw e.getCause(); } }
From source file:org.apache.nutch.parse.ParseUtil.java
private ParseResult runParser(Parser p, Content content) { ParseCallable pc = new ParseCallable(p, content); FutureTask<ParseResult> task = new FutureTask<ParseResult>(pc); ParseResult res = null;//from ww w .j a v a 2s . c o m Thread t = new Thread(task); t.start(); try { res = task.get(MAX_PARSE_TIME, TimeUnit.SECONDS); } catch (TimeoutException e) { LOG.warn("TIMEOUT parsing " + content.getUrl() + " with " + p); } catch (Exception e) { task.cancel(true); res = null; t.interrupt(); } finally { t = null; pc = null; } return res; }
From source file:cognition.common.service.DocumentConversionService.java
private File makeTiffFromPDF(DNCWorkCoordinate coordinate, File input) throws IOException, TikaException { File output = File.createTempFile(coordinate.getFileName(), ".tiff"); String[] cmd = { getImageMagickProg(), "-density", "300", input.getPath(), "-depth", "8", "-quality", "1", output.getPath() };/*from ww w. j a va2 s . c o m*/ Process process = new ProcessBuilder(cmd).start(); IOUtils.closeQuietly(process.getOutputStream()); InputStream processInputStream = process.getInputStream(); logStream(processInputStream); FutureTask<Integer> waitTask = new FutureTask<>(process::waitFor); Thread waitThread = new Thread(waitTask); waitThread.start(); try { waitTask.get(240, TimeUnit.SECONDS); return output; } catch (Exception e) { logger.error(e.getMessage()); waitThread.interrupt(); process.destroy(); waitTask.cancel(true); } finally { IOUtils.closeQuietly(processInputStream); process.destroy(); waitThread.interrupt(); waitTask.cancel(true); } return null; }
From source file:uk.ac.kcl.iop.brc.core.pipeline.common.service.DocumentConversionService.java
private File makeTiffFromPDF(DNCWorkCoordinate coordinate, File input) throws IOException, TikaException { File output = File.createTempFile(coordinate.getFileName(), ".tiff"); String[] cmd = { getImageMagickProg(), "-density", "300", input.getPath(), "-depth", "8", "-quality", "1", output.getPath() };//from w w w . j a v a2 s .c o m Process process = new ProcessBuilder(cmd).start(); IOUtils.closeQuietly(process.getOutputStream()); InputStream processInputStream = process.getInputStream(); logStream(processInputStream); FutureTask<Integer> waitTask = new FutureTask<>(process::waitFor); Thread waitThread = new Thread(waitTask); waitThread.start(); try { waitTask.get(240, TimeUnit.SECONDS); return output; } catch (Exception e) { logger.error(e.getMessage()); waitThread.interrupt(); process.destroy(); Thread.currentThread().interrupt(); waitTask.cancel(true); } finally { IOUtils.closeQuietly(processInputStream); process.destroy(); waitThread.interrupt(); waitTask.cancel(true); } return null; }
From source file:org.apache.qpid.server.security.access.firewall.HostnameFirewallRule.java
/** * @param remote//from w ww . j av a 2s.c o m * the InetAddress to look up * @return the hostname, null if not found, takes longer than * {@value #DNS_LOOKUP} to find or otherwise fails */ private String getHostname(final InetAddress remote) throws AccessControlFirewallException { FutureTask<String> lookup = new FutureTask<String>(new Callable<String>() { public String call() { return remote.getCanonicalHostName(); } }); DNS_LOOKUP.execute(lookup); try { return lookup.get(DNS_TIMEOUT, TimeUnit.MILLISECONDS); } catch (Exception e) { _logger.warn("Unable to look up hostname from address " + remote, e); return null; } finally { lookup.cancel(true); } }
From source file:io.kahu.hawaii.util.call.dispatch.RequestDispatcher.java
/** * Blocking (synchronous) execute of the request. * * @param request//w w w .j av a 2 s. co m * @param <T> * @return * @throws ServerException */ public <T> Response<T> execute(AbortableRequest<T> request) throws ServerException { Response<T> response = request.getResponse(); try { HawaiiExecutor executor = executorServiceRepository.getExecutor(request); notifyListeners(request, executor); FutureTask<T> task = executor.execute(request, response); /* * Block until data is retrieved, but with a time out. */ TimeOut timeOut = request.getTimeOut(); task.get(timeOut.getDuration(), timeOut.getUnit()); } catch (RejectedExecutionException e) { // Executor is too busy (no threads available nor is there a place in the queue). request.reject(); } catch (TimeoutException e) { // The task.get( ... ) is timed out. The execution takes too long. request.abort(); } catch (InterruptedException e) { // .. response.setStatus(ResponseStatus.INTERNAL_FAILURE, "Interrupted", e); } catch (ExecutionException e) { // Catches all exceptions from within the executor response.setStatus(ResponseStatus.INTERNAL_FAILURE, "Execution exception", e.getCause()); } catch (Throwable t) { // Catches all exceptions outside the executor response.setStatus(ResponseStatus.INTERNAL_FAILURE, "Unexpected exception", t); } finally { request.finish(); } return response; }
From source file:com.mrfeinberg.translation.AbstractTranslationService.java
public Runnable translate(final String phrase, final LanguagePair lp, final TranslationListener listener) { final Language b = lp.b(); final HttpClient httpClient = new HttpClient(); if (proxyPrefs.getUseProxy()) { httpClient.getHostConfiguration().setProxy(proxyPrefs.getProxyHost(), proxyPrefs.getProxyPort()); }/*from www. j av a 2 s .co m*/ final HttpMethod httpMethod = getHttpMethod(phrase, lp); final Callable<String> callable = new Callable<String>() { public String call() throws Exception { int result = httpClient.executeMethod(httpMethod); if (result != 200) { throw new Exception("Got " + result + " status for " + httpMethod.getURI()); } final BufferedReader in = new BufferedReader( new InputStreamReader(httpMethod.getResponseBodyAsStream(), "utf8")); try { final StringBuilder sb = new StringBuilder(); String line; while ((line = in.readLine()) != null) sb.append(line); return sb.toString(); } finally { in.close(); httpMethod.releaseConnection(); } } }; final FutureTask<String> tc = new FutureTask<String>(callable); return new Runnable() { public void run() { try { executor.execute(tc); final String result = tc.get(timeout, TimeUnit.MILLISECONDS); String found = findTranslatedText(result); if (found == null) { listener.error("Cannot find translated text in result."); } else { found = found.replaceAll("\\s+", " "); listener.result(found, b); } } catch (final TimeoutException e) { listener.timedOut(); } catch (final InterruptedException e) { listener.cancelled(); } catch (final Exception e) { e.printStackTrace(); listener.error(e.toString()); } } }; }
From source file:org.ow2.petals.launcher.tasks.InstallFromRepositoryTask.java
@Override protected int doProcess(List<String> args) { // for now just do it by copying things in the install path... need to // use the PEtALS API... String componentToInstall = args.get(0); File[] files = this.repository.listFiles(new ComponentNamesFilter()); if (files == null) { System.out.println("No file in repository"); return ERROR_CODE; }/*from w w w. ja v a 2 s.c o m*/ for (File file : files) { String name = this.getComponentName(file); if (name.equals(componentToInstall)) { System.out.println("Installing component " + componentToInstall + "..."); // do it in a separate thread FutureTask<String> task = new FutureTask<String>(new FutureInstaller(file, this.installPath)); Thread t = new Thread(task); t.setDaemon(true); t.start(); try { System.out.println(task.get(20, TimeUnit.SECONDS)); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TimeoutException e) { System.out.println("Timeout while installing component"); } break; } } return OK_CODE; }
From source file:org.gytheio.health.CompositeComponentUnavailableAction.java
protected void execute(final ComponentUnavailableAction action, final Throwable e) throws Throwable { FutureTask<Void> task = null; try {//from w ww.j a va2s .c o m task = new FutureTask<Void>(new Runnable() { @Override public void run() { action.execute(e); } }, null); getExecutorService().execute(task); task.get(actionTimeoutMs, TimeUnit.MILLISECONDS); } catch (TimeoutException e1) { task.cancel(true); throw e; } catch (InterruptedException e1) { // We were asked to stop task.cancel(true); } catch (ExecutionException e1) { // Unwrap our cause and throw that Throwable cause = e.getCause(); throw cause; } }
From source file:org.atomserver.ThrottledAtomServer.java
/** * Execute the CallableTask on a ThreadPoolTaskExecutor. <br/> * NOTE: the standard Exception handling of AtomServer still happens in the AtomServer class. * Any Exception handling done here is for Exceptions that actually are thrown this far up * the food chain -- Exceptions that pertain directly to the TaskExecutor -- * for example, TimeoutException or ExecutionException. * * @param request The Abdera RequestContext * @param callableTask The CallableTask, which shoudl just be a wrapped call to * the corresponding super task. * @return The Abdera ResponseContext/*from w w w . j av a 2 s . c o m*/ */ private ResponseContext executePooledTask(final RequestContext request, final Callable<ResponseContext> callableTask) { ResponseContext response = null; Abdera abdera = request.getServiceContext().getAbdera(); try { FutureTask<ResponseContext> futureTask = new FutureTask(callableTask); threadPool.execute(futureTask); try { logger.debug("starting to wait for the task to complete"); response = futureTask.get(taskTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // InterruptedException - if the current thread was interrupted while waiting // Re-assert the thread's interrupted status Thread.currentThread().interrupt(); logger.error("InterruptedException in executePooledTask: Cause= " + e.getCause() + " Message= " + e.getMessage(), e); return getAtomServer().servererror(abdera, request, "InterruptedException occurred:: " + e.getCause(), e); } catch (ExecutionException e) { // ExecutionException - if the computation threw an exception // Because all Exception handling is done in the super class; AtomServer, we should never get this logger.error("ExecutionException in executePooledTask: Cause= " + e.getCause() + " Message= " + e.getMessage(), e); return getAtomServer().servererror(abdera, request, "ExecutionException occurred:: " + e.getCause(), e); } catch (TimeoutException e) { // TimeoutException - if the wait timed out logger.error("TimeoutException in executePooledTask: Cause= " + e.getCause() + " Message= " + e.getMessage(), e); return getAtomServer().servererror(abdera, request, "TimeoutException occurred:: " + e.getCause(), e); } catch (Exception e) { logger.error("Unknown Exception in executePooledTask: Cause= " + e.getCause() + " Message= " + e.getMessage(), e); return getAtomServer().servererror(abdera, request, "Unknown Exception occurred:: " + e.getCause(), e); } finally { // Best practice is to cancel tasks whose result is no longer needed // NOTE; task.cancel() is harmless if the task has already completed // Interrupt if running... futureTask.cancel(true); // Help out the garbage collector futureTask = null; } } finally { // Log all thread pool statistics at INFO level. // This information is very critical in understanding the effectiveness of the pool logThreadPoolStats(); } return response; }