List of usage examples for java.util.concurrent FutureTask FutureTask
public FutureTask(Callable<V> callable)
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./* www. java2s . c om*/ * * 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.nuxeo.ecm.core.management.jtajca.CanMonitorTransactionsTest.java
@Test public void isActiveStatisticsCollected() throws InterruptedException, ExecutionException { FutureTask<Boolean> task = new FutureTask<Boolean>(new TestCollectStatistics()); executor.execute(task);/* ww w.ja va 2 s .com*/ assertThat(task.get(), is(true)); }
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.jav a2 s .co 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:cc.gospy.core.util.StringHelper.java
public static String getMyExternalIp() { if (myExternalIp == null) { try {// w ww. ja v a2 s. c o m logger.info("Querying external ip..."); FutureTask futureTask = new FutureTask<>(() -> { URL ipEcho = new URL("http://ipecho.net/plain"); BufferedReader in = new BufferedReader(new InputStreamReader(ipEcho.openStream())); String resultIp = in.readLine(); in.close(); return resultIp; }); futureTask.run(); myExternalIp = (String) futureTask.get(3, TimeUnit.SECONDS); logger.info("My external ip: {}", myExternalIp); } catch (TimeoutException e) { myExternalIp = "unknown ip"; logger.error("Get external ip failure, cause: Timeout (3 seconds)"); } catch (Exception e) { myExternalIp = "unknown ip"; logger.error("Get external ip failure, cause: {}", e.getMessage()); } } return myExternalIp; }
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 ww .ja v a2 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:org.apache.jackrabbit.oak.jcr.CompatibilityIssuesTest.java
private static void run(Callable<Void> callable) throws InterruptedException, ExecutionException { FutureTask<Void> task = new FutureTask<Void>(callable); new Thread(task).start(); task.get();//from w w w . j a v a 2 s. co m }
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() };// w w w . jav a 2 s. com 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:org.apache.axis2.jaxws.client.async.CallbackFuture.java
@SuppressWarnings("unchecked") public CallbackFuture(InvocationContext ic, AsyncHandler handler) { // We need to save off the classloader associated with the AsyncHandler instance // since we'll need to set this same classloader on the thread where // handleResponse() is invoked. // This is required so that we don't encounter ClassCastExceptions. final Object handlerObj = handler; final ClassLoader handlerCL = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return handlerObj.getClass().getClassLoader(); }//from w ww. j a v a 2 s . co m }); // Allow the AsyncHandlerProxyFactory to create the proxy for the AsyncHandler // passed in (which was provided by the client on the async invocation). // This allows any server-specific work to be done, such as thread context management, etc. AsyncHandler originalHandler = handler; try { if (debug) { log.debug("Calling factory to create proxy for AsyncHandler instance: " + displayHandle(handler)); } AsyncHandlerProxyFactory proxyFactory = (AsyncHandlerProxyFactory) FactoryRegistry .getFactory(AsyncHandlerProxyFactory.class); handler = proxyFactory.createAsyncHandlerProxy(handler); if (debug) { log.debug("Factory returned AsyncHandler proxy instance: " + displayHandle(handler)); } } catch (Exception e) { if (debug) { log.debug("AsyncHandlerProxyFactory threw an exception: " + e.toString()); e.printStackTrace(); } // Just use the original handler provided by the client if we // failed to create a proxy for it. handler = originalHandler; } cft = new CallbackFutureTask(ic.getAsyncResponseListener(), handler, handlerCL); task = new FutureTask(cft); executor = ic.getExecutor(); /* * TODO review. We need to save the invocation context so we can set it on the * response (or fault) context so the FutureCallback has access to the handler list. */ invocationCtx = ic; }
From source file:org.apache.ambari.server.KdcServerConnectionVerification.java
/** * Attempt to communicate with KDC server over UDP. * @param server KDC hostname or IP address * @param port KDC server port//from w w w. j a v a 2 s . c o m * @return true if communication is successful; false otherwise */ public boolean isKdcReachableViaUDP(final String server, final int port) { int timeoutMillis = udpTimeout * 1000; final KdcConfig config = KdcConfig.getDefaultConfig(); config.setHostName(server); config.setKdcPort(port); config.setUseUdp(true); config.setTimeout(timeoutMillis); final KdcConnection connection = getKdcUdpConnection(config); FutureTask<Boolean> future = new FutureTask<Boolean>(new Callable<Boolean>() { @Override public Boolean call() { try { // we are only testing whether we can communicate with server and not // validating credentials connection.getTgt("noUser@noRealm", "noPassword"); } catch (KerberosException e) { // unfortunately, need to look at msg as error 60 is a generic error code return !(e.getErrorCode() == ErrorType.KRB_ERR_GENERIC.getValue() && e.getMessage().contains("TimeOut")); //todo: evaluate other error codes to provide better information //todo: as there may be other error codes where we should return false } catch (Exception e) { // some bad unexpected thing occurred throw new RuntimeException(e); } return true; } }); new Thread(future, "ambari-kdc-verify").start(); Boolean result; try { // timeout after specified timeout result = future.get(timeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { LOG.error("Interrupted while trying to communicate with KDC server over UDP"); result = false; future.cancel(true); } catch (ExecutionException e) { LOG.error( "An unexpected exception occurred while attempting to communicate with the KDC server over UDP", e); result = false; } catch (TimeoutException e) { LOG.error("Timeout occurred while attempting to to communicate with KDC server over UDP"); result = false; future.cancel(true); } return result; }