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.rhq.enterprise.server.configuration.LiveConfigurationLoader.java
/** * * @param resources// w w w . j a va2s .c o m * @param timeout the number of seconds before this call should timeout and * @return * @throws Exception */ public Map<Integer, Configuration> loadLiveResourceConfigurations(final Set<Resource> resources, long timeout) { try { FutureTask<Map<Integer, Configuration>> task = new FutureTask<Map<Integer, Configuration>>( new Callable<Map<Integer, Configuration>>() { public Map<Integer, Configuration> call() throws Exception { return loadLiveResourceConfigurations(resources); } }); new Thread(task).start(); return task.get(timeout, TimeUnit.SECONDS); } catch (TimeoutException e) { throw new RuntimeException( "Timed out after " + timeout + " seconds while retrieving live Resource configurations."); } catch (Exception e) { throw new RuntimeException("Failed to retrieve live Resource configurations.", e); } }
From source file:org.apache.kylin.storage.hbase.util.StorageCleanupJob.java
private void cleanUnusedHBaseTables(Configuration conf) throws IOException { CubeManager cubeMgr = CubeManager.getInstance(KylinConfig.getInstanceFromEnv()); // get all kylin hbase tables Connection conn = HBaseConnection.get(KylinConfig.getInstanceFromEnv().getStorageUrl()); Admin hbaseAdmin = conn.getAdmin();//from w w w. ja v a 2 s . c o m String tableNamePrefix = IRealizationConstants.SharedHbaseStorageLocationPrefix; HTableDescriptor[] tableDescriptors = hbaseAdmin.listTables(tableNamePrefix + ".*"); List<String> allTablesNeedToBeDropped = new ArrayList<String>(); for (HTableDescriptor desc : tableDescriptors) { String host = desc.getValue(IRealizationConstants.HTableTag); if (KylinConfig.getInstanceFromEnv().getMetadataUrlPrefix().equalsIgnoreCase(host)) { //only take care htables that belongs to self, and created more than 2 days allTablesNeedToBeDropped.add(desc.getTableName().getNameAsString()); } } // remove every segment htable from drop list for (CubeInstance cube : cubeMgr.listAllCubes()) { for (CubeSegment seg : cube.getSegments()) { String tablename = seg.getStorageLocationIdentifier(); if (allTablesNeedToBeDropped.contains(tablename)) { allTablesNeedToBeDropped.remove(tablename); logger.info("Exclude table " + tablename + " from drop list, as the table belongs to cube " + cube.getName() + " with status " + cube.getStatus()); } } } if (delete == true) { // drop tables ExecutorService executorService = Executors.newSingleThreadExecutor(); for (String htableName : allTablesNeedToBeDropped) { FutureTask futureTask = new FutureTask(new DeleteHTableRunnable(hbaseAdmin, htableName)); executorService.execute(futureTask); try { futureTask.get(deleteTimeout, TimeUnit.MINUTES); } catch (TimeoutException e) { logger.warn("It fails to delete htable " + htableName + ", for it cost more than " + deleteTimeout + " minutes!"); futureTask.cancel(true); } catch (Exception e) { e.printStackTrace(); futureTask.cancel(true); } } executorService.shutdown(); } else { System.out.println("--------------- Tables To Be Dropped ---------------"); for (String htableName : allTablesNeedToBeDropped) { System.out.println(htableName); } System.out.println("----------------------------------------------------"); } hbaseAdmin.close(); }
From source file:uk.ac.kcl.tika.parsers.PDFPreprocessorParser.java
private File makeTiffFromPDF(File input, File output, ImageMagickConfig config) throws IOException, TikaException { String[] cmd = { config.getImageMagickPath() + getImageMagickProg(), "-density", config.getDensity(), input.getPath(), "-depth", config.getDepth(), "-quality", config.getQuality(), output.getPath() }; ProcessBuilder pb = new ProcessBuilder(cmd); //setEnv(config, pb); final Process process = pb.start(); process.getOutputStream().close();/*from w ww. j a v a 2s .c om*/ InputStream out = process.getInputStream(); InputStream err = process.getErrorStream(); logStream("IMAGEMAGICK MSG", out, input); logStream("IMAGEMAGICK ERROR", err, input); FutureTask<Integer> waitTask = new FutureTask<Integer>(new Callable<Integer>() { public Integer call() throws Exception { return process.waitFor(); } }); Thread waitThread = new Thread(waitTask); waitThread.start(); try { waitTask.get(config.getTimeout(), TimeUnit.SECONDS); return output; } catch (InterruptedException e) { waitThread.interrupt(); process.destroy(); Thread.currentThread().interrupt(); throw new TikaException("ImageMagickOCRPDFParser interrupted", e); } catch (ExecutionException e) { // should not be thrown } catch (TimeoutException e) { waitThread.interrupt(); process.destroy(); throw new TikaException("ImageMagickOCRPDFParser timeout", e); } return null; }
From source file:com.loopj.android.http.sample.AsyncBackgroundThreadSample.java
@Override public RequestHandle executeSample(final AsyncHttpClient client, final String URL, final Header[] headers, HttpEntity entity, final ResponseHandlerInterface responseHandler) { final Activity ctx = this; FutureTask<RequestHandle> future = new FutureTask<>(new Callable<RequestHandle>() { public RequestHandle call() { Log.d(LOG_TAG, "Executing GET request on background thread"); return client.get(ctx, URL, headers, null, responseHandler); }/*from w ww . j a v a2s. c o m*/ }); executor.execute(future); RequestHandle handle = null; try { handle = future.get(5, TimeUnit.SECONDS); Log.d(LOG_TAG, "Background thread for GET request has finished"); } catch (Exception e) { Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG).show(); e.printStackTrace(); } return handle; }
From source file:org.apache.kylin.tool.StorageCleanupJob.java
private void cleanUnusedHBaseTables(Configuration conf) throws IOException { CubeManager cubeMgr = CubeManager.getInstance(KylinConfig.getInstanceFromEnv()); // get all kylin hbase tables try (HBaseAdmin hbaseAdmin = new HBaseAdmin(conf)) { String tableNamePrefix = IRealizationConstants.SharedHbaseStorageLocationPrefix; HTableDescriptor[] tableDescriptors = hbaseAdmin.listTables(tableNamePrefix + ".*"); List<String> allTablesNeedToBeDropped = new ArrayList<String>(); for (HTableDescriptor desc : tableDescriptors) { String host = desc.getValue(IRealizationConstants.HTableTag); if (KylinConfig.getInstanceFromEnv().getMetadataUrlPrefix().equalsIgnoreCase(host)) { //only take care htables that belongs to self, and created more than 2 days allTablesNeedToBeDropped.add(desc.getTableName().getNameAsString()); }//from w w w .j a v a 2 s.co m } // remove every segment htable from drop list for (CubeInstance cube : cubeMgr.listAllCubes()) { for (CubeSegment seg : cube.getSegments()) { String tablename = seg.getStorageLocationIdentifier(); if (allTablesNeedToBeDropped.contains(tablename)) { allTablesNeedToBeDropped.remove(tablename); logger.info("Exclude table " + tablename + " from drop list, as the table belongs to cube " + cube.getName() + " with status " + cube.getStatus()); } } } if (delete == true) { // drop tables ExecutorService executorService = Executors.newSingleThreadExecutor(); for (String htableName : allTablesNeedToBeDropped) { FutureTask futureTask = new FutureTask(new DeleteHTableRunnable(hbaseAdmin, htableName)); executorService.execute(futureTask); try { futureTask.get(deleteTimeout, TimeUnit.MINUTES); } catch (TimeoutException e) { logger.warn("It fails to delete htable " + htableName + ", for it cost more than " + deleteTimeout + " minutes!"); futureTask.cancel(true); } catch (Exception e) { e.printStackTrace(); futureTask.cancel(true); } } executorService.shutdown(); } else { System.out.println("--------------- Tables To Be Dropped ---------------"); for (String htableName : allTablesNeedToBeDropped) { System.out.println(htableName); } System.out.println("----------------------------------------------------"); } } }
From source file:uk.ac.kcl.tika.parsers.TesseractOCRParser.java
/** * Run external tesseract-ocr process./* ww w .j ava 2 s . c o m*/ * * @param input * File to be ocred * @param output * File to collect ocr result * @param config * Configuration of tesseract-ocr engine * @throws TikaException * if the extraction timed out * @throws IOException * if an input error occurred */ private void doOCR(File input, File output, TesseractOCRConfig config) throws IOException, TikaException { String[] cmd = { config.getTesseractPath() + getTesseractProg(), input.getPath(), output.getPath(), "-l", config.getLanguage(), "-psm", config.getPageSegMode() }; ProcessBuilder pb = new ProcessBuilder(cmd); setEnv(config, pb); final Process process = pb.start(); process.getOutputStream().close(); InputStream out = process.getInputStream(); InputStream err = process.getErrorStream(); logStream("OCR MSG", out, input); logStream("OCR ERROR", err, input); FutureTask<Integer> waitTask = new FutureTask<Integer>(new Callable<Integer>() { public Integer call() throws Exception { return process.waitFor(); } }); Thread waitThread = new Thread(waitTask); waitThread.start(); try { waitTask.get(config.getTimeout(), TimeUnit.SECONDS); } catch (InterruptedException e) { waitThread.interrupt(); process.destroy(); Thread.currentThread().interrupt(); throw new TikaException("TesseractOCRParser interrupted", e); } catch (ExecutionException e) { // should not be thrown } catch (TimeoutException e) { waitThread.interrupt(); process.destroy(); throw new TikaException("TesseractOCRParser timeout", e); } }
From source file:org.springframework.ide.eclipse.beans.core.internal.model.BeansJavaConfig.java
@Override protected void readConfig() { if (!isModelPopulated) { w.lock();// w w w . ja va 2 s.c om if (this.isModelPopulated) { w.unlock(); return; } try { if (this.configClass == null) { return; } IBeansProject beansProject = BeansModelUtils.getParentOfClass(this, IBeansProject.class); if (beansProject == null) { return; } final ClassLoader cl = JdtUtils.getClassLoader(beansProject.getProject(), ApplicationContext.class.getClassLoader()); if (cl.getResource(this.configClass.getFullyQualifiedName().replace('.', '/') + ".class") == null) { return; } Callable<Integer> loadBeanDefinitionOperation = new Callable<Integer>() { public Integer call() throws Exception { // Obtain thread context classloader and override with the project classloader ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(cl); // Create special ReaderEventListener that essentially just passes through component definitions ReaderEventListener eventListener = new BeansConfigPostProcessorReaderEventListener(); problemReporter = new BeansConfigProblemReporter(); beanNameGenerator = new UniqueBeanNameGenerator(BeansJavaConfig.this); registry = new ScannedGenericBeanDefinitionSuppressingBeanDefinitionRegistry(); try { registerAnnotationProcessors(eventListener); registerBean(eventListener, cl); IBeansConfigPostProcessor[] postProcessors = BeansConfigPostProcessorFactory .createPostProcessor(ConfigurationClassPostProcessor.class.getName()); for (IBeansConfigPostProcessor postProcessor : postProcessors) { executePostProcessor(postProcessor, eventListener); } } finally { // Reset the context classloader Thread.currentThread().setContextClassLoader(threadClassLoader); LogFactory.release(cl); //Otherwise permgen leak? } return 0; } }; FutureTask<Integer> task = new FutureTask<Integer>(loadBeanDefinitionOperation); BeansCorePlugin.getExecutorService().submit(task); task.get(BeansCorePlugin.getDefault().getPreferenceStore() .getInt(BeansCorePlugin.TIMEOUT_CONFIG_LOADING_PREFERENCE_ID), TimeUnit.SECONDS); } catch (TimeoutException e) { problems.add(new ValidationProblem(IMarker.SEVERITY_ERROR, "Loading of configuration '" + this.configClass.getFullyQualifiedName() + "' took more than " + BeansCorePlugin.getDefault().getPreferenceStore() .getInt(BeansCorePlugin.TIMEOUT_CONFIG_LOADING_PREFERENCE_ID) + "sec", file, 1)); } catch (Exception e) { problems.add(new ValidationProblem(IMarker.SEVERITY_ERROR, String.format("Error occured processing Java config '%s'. See Error Log for more details", e.getCause().getMessage()), getElementResource())); BeansCorePlugin.log(new Status(IStatus.INFO, BeansCorePlugin.PLUGIN_ID, String.format("Error occured processing '%s'", this.configClass.getFullyQualifiedName()), e.getCause())); } finally { // Prepare the internal cache of all children for faster access List<ISourceModelElement> allChildren = new ArrayList<ISourceModelElement>(imports); allChildren.addAll(aliases.values()); allChildren.addAll(components); allChildren.addAll(beans.values()); Collections.sort(allChildren, new Comparator<ISourceModelElement>() { public int compare(ISourceModelElement element1, ISourceModelElement element2) { return element1.getElementStartLine() - element2.getElementStartLine(); } }); this.children = allChildren.toArray(new IModelElement[allChildren.size()]); this.isModelPopulated = true; w.unlock(); } } }
From source file:org.nuxeo.ecm.core.event.impl.PostCommitEventExecutor.java
public void run(List<EventListenerDescriptor> listeners, EventBundle bundle, long timeoutMillis, boolean bulk) { // check that there's at list one listener interested boolean some = false; for (EventListenerDescriptor listener : listeners) { if (listener.acceptBundle(bundle)) { some = true;/* w ww .j a v a 2 s . c o m*/ break; } } if (!some) { if (log.isDebugEnabled()) { log.debug("Events postcommit execution has nothing to do"); } return; } if (log.isDebugEnabled()) { log.debug(String.format("Events postcommit execution starting with timeout %sms%s", Long.valueOf(timeoutMillis), bulk ? " in bulk mode" : "")); } Callable<Boolean> callable = !bulk ? new EventBundleRunner(listeners, bundle) : new EventBundleBulkRunner(listeners, bundle); FutureTask<Boolean> futureTask = new FutureTask<Boolean>(callable); try { executor.execute(futureTask); } catch (RejectedExecutionException e) { log.error("Events postcommit execution rejected", e); return; } try { // wait for runner to be finished, with timeout Boolean ok = futureTask.get(timeoutMillis, TimeUnit.MILLISECONDS); if (Boolean.FALSE.equals(ok)) { log.error("Events postcommit bulk execution aborted due to previous error"); } } catch (InterruptedException e) { // restore interrupted status Thread.currentThread().interrupt(); // interrupt thread futureTask.cancel(true); // mayInterruptIfRunning=true } catch (TimeoutException e) { if (!bulk) { log.warn(String.format( "Events postcommit execution exceeded timeout of %sms, leaving thread running", Long.valueOf(timeoutMillis))); // don't cancel task, let it run } else { log.error(String.format( "Events postcommit bulk execution exceeded timeout of %sms, interrupting thread", Long.valueOf(timeoutMillis))); futureTask.cancel(true); // mayInterruptIfRunning=true } } catch (ExecutionException e) { log.error("Events postcommit execution encountered unexpected exception", e.getCause()); } if (log.isDebugEnabled()) { log.debug("Events postcommit execution finished"); } }
From source file:org.apache.tika.parser.ocr.TesseractOCRParser.java
/** * Run external tesseract-ocr process./*from w w w. j av a 2 s. co m*/ * * @param input * File to be ocred * @param output * File to collect ocr result * @param config * Configuration of tesseract-ocr engine * @throws TikaException * if the extraction timed out * @throws IOException * if an input error occurred */ private void doOCR(File input, File output, TesseractOCRConfig config) throws IOException, TikaException { String[] cmd = { config.getTesseractPath() + getTesseractProg(), input.getPath(), output.getPath(), "-l", config.getLanguage(), "-psm", config.getPageSegMode() }; ProcessBuilder pb = new ProcessBuilder(cmd); setEnv(config, pb); final Process process = pb.start(); process.getOutputStream().close(); InputStream out = process.getInputStream(); InputStream err = process.getErrorStream(); logStream("OCR MSG", out, input); logStream("OCR ERROR", err, input); FutureTask<Integer> waitTask = new FutureTask<Integer>(new Callable<Integer>() { public Integer call() throws Exception { return process.waitFor(); } }); Thread waitThread = new Thread(waitTask); waitThread.start(); try { waitTask.get(config.getTimeout(), TimeUnit.SECONDS); } catch (InterruptedException e) { waitThread.interrupt(); process.destroy(); Thread.currentThread().interrupt(); throw new TikaException("TesseractOCRParser interrupted", e); } catch (ExecutionException e) { // should not be thrown } catch (TimeoutException e) { waitThread.interrupt(); process.destroy(); throw new TikaException("TesseractOCRParser timeout", e); } }
From source file:org.apache.tika.parser.ocr.TesseractOCRParser.java
/** * Run external tesseract-ocr process./*www .ja v a 2 s . c o m*/ * * @param input * File to be ocred * @param output * File to collect ocr result * @param config * Configuration of tesseract-ocr engine * @throws TikaException * if the extraction timed out * @throws IOException * if an input error occurred */ private void doOCR(File input, File output, TesseractOCRConfig config) throws IOException, TikaException { String[] cmd = { config.getTesseractPath() + getTesseractProg(), input.getPath(), output.getPath(), "-l", config.getLanguage(), "-psm", config.getPageSegMode(), config.getOutputType().name().toLowerCase(Locale.US), "-c", (config.getPreserveInterwordSpacing()) ? "preserve_interword_spaces=1" : "preserve_interword_spaces=0" }; ProcessBuilder pb = new ProcessBuilder(cmd); setEnv(config, pb); final Process process = pb.start(); process.getOutputStream().close(); InputStream out = process.getInputStream(); InputStream err = process.getErrorStream(); logStream("OCR MSG", out, input); logStream("OCR ERROR", err, input); FutureTask<Integer> waitTask = new FutureTask<>(new Callable<Integer>() { public Integer call() throws Exception { return process.waitFor(); } }); Thread waitThread = new Thread(waitTask); waitThread.start(); try { waitTask.get(config.getTimeout(), TimeUnit.SECONDS); } catch (InterruptedException e) { waitThread.interrupt(); process.destroy(); Thread.currentThread().interrupt(); throw new TikaException("TesseractOCRParser interrupted", e); } catch (ExecutionException e) { // should not be thrown } catch (TimeoutException e) { waitThread.interrupt(); process.destroy(); throw new TikaException("TesseractOCRParser timeout", e); } }