List of usage examples for java.util.concurrent FutureTask FutureTask
public FutureTask(Callable<V> callable)
From source file:com.eclectide.intellij.whatthecommit.WhatTheCommitAction.java
public String loadCommitMessage(final String url) { final FutureTask<String> downloadTask = new FutureTask<String>(new Callable<String>() { public String call() { final HttpClient client = new HttpClient(); final GetMethod getMethod = new GetMethod(url); try { final int statusCode = client.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) throw new RuntimeException("Connection error (HTTP status = " + statusCode + ")"); return getMethod.getResponseBodyAsString(); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); }/*from ww w . j av a 2 s .com*/ } }); ApplicationManager.getApplication().executeOnPooledThread(downloadTask); try { return downloadTask.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); } catch (TimeoutException e) { // ignore } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } if (!downloadTask.isDone()) { downloadTask.cancel(true); throw new RuntimeException("Connection timed out"); } return ""; }
From source file:org.geoserver.wms.animate.FrameCatalogVisitor.java
/** * Adds a new visitor to the runnables list and initializes the animatorExecutor service is not yet initialied. * @param request//from w w w .j ava 2s. c om * @param wms * @param wmsConfiguration * @param aparam * @param avalue */ public void visit(final GetMapRequest request, WebMapService wms, WMS wmsConfiguration, String aparam, String avalue) { if (this.tasks == null) { this.tasks = new LinkedList<Future<RenderedImage>>(); } FrameLoader loader = new FrameLoader(request, wms, wmsConfiguration, aparam, avalue); final FutureTask<RenderedImage> task = new FutureTask<RenderedImage>(loader); this.tasks.add(task); this.framesNumber++; // run the loading in this thread wmsConfiguration.getAnimatorExecutorService().execute(task); }
From source file:FutureTest.java
public Integer call() { count = 0;//from w w w .j a v a2 s. c o m try { File[] files = directory.listFiles(); ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>(); for (File file : files) if (file.isDirectory()) { MatchCounter counter = new MatchCounter(file, keyword); FutureTask<Integer> task = new FutureTask<Integer>(counter); results.add(task); Thread t = new Thread(task); t.start(); } else { if (search(file)) count++; } for (Future<Integer> result : results) try { count += result.get(); } catch (ExecutionException e) { e.printStackTrace(); } } catch (InterruptedException e) { } return count; }
From source file:android.support.test.espresso.base.ThreadPoolExecutorExtractor.java
public Optional<ThreadPoolExecutor> getCompatAsyncTaskThreadPool() { try {/* w ww. ja v a 2s.co m*/ return runOnMainThread(new FutureTask<Optional<ThreadPoolExecutor>>(MODERN_ASYNC_TASK_EXTRACTOR)).get(); } catch (InterruptedException ie) { throw new RuntimeException("Interrupted while trying to get the compat async executor!", ie); } catch (ExecutionException ee) { throw new RuntimeException(ee.getCause()); } }
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.j a va 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:com.saysth.commons.quartz.SimpleThreadPoolTaskExecutor.java
public <T> Future<T> submit(Callable<T> task) { FutureTask<T> future = new FutureTask<T>(task); execute(future);/*w w w . j av a 2s. c o m*/ return future; }
From source file:ubic.gemma.core.loader.util.fetcher.HttpFetcher.java
protected FutureTask<Boolean> defineTask(final String outputFileName, final String seekFile) { return new FutureTask<>(new Callable<Boolean>() { @Override/*w w w .jav a2 s . co m*/ @SuppressWarnings("synthetic-access") public Boolean call() throws IOException { AbstractFetcher.log.info("Fetching " + seekFile); URL urlPattern = new URL(seekFile); InputStream inputStream = new BufferedInputStream(urlPattern.openStream()); try (OutputStream outputStream = new FileOutputStream(new File(outputFileName))) { final byte[] buffer = new byte[65536]; int read; while ((read = inputStream.read(buffer)) > -1) { outputStream.write(buffer, 0, read); } outputStream.close(); return Boolean.TRUE; } } }); }
From source file:com.norman0406.slimgress.API.Interface.Interface.java
public AuthSuccess authenticate(final String token) { FutureTask<AuthSuccess> future = new FutureTask<AuthSuccess>(new Callable<AuthSuccess>() { @Override/*from w ww .j a v a2 s.co m*/ public AuthSuccess call() throws Exception { // see http://blog.notdot.net/2010/05/Authenticating-against-App-Engine-from-an-Android-app // also use ?continue= (?) String login = mApiBaseURL + mApiLogin + token; HttpGet get = new HttpGet(login); try { HttpResponse response = null; synchronized (Interface.this) { mClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); Log.i("Interface", "executing authentication"); response = mClient.execute(get); } assert (response != null); @SuppressWarnings("unused") String content = EntityUtils.toString(response.getEntity()); response.getEntity().consumeContent(); if (response.getStatusLine().getStatusCode() == 401) { // the token has expired Log.i("Interface", "401: authentication token has expired"); return AuthSuccess.TokenExpired; } else if (response.getStatusLine().getStatusCode() != 302) { // Response should be a redirect Log.i("Interface", "unknown error: " + response.getStatusLine().getReasonPhrase()); return AuthSuccess.UnknownError; } else { // get cookie synchronized (Interface.this) { for (Cookie cookie : mClient.getCookieStore().getCookies()) { if (cookie.getName().equals("SACSID")) { // secure cookie! (ACSID is non-secure http cookie) mCookie = cookie.getValue(); } } } if (mCookie == null) { Log.i("Interface", "authentication token has expired"); return AuthSuccess.TokenExpired; } Log.i("Interface", "authentication successful"); return AuthSuccess.Successful; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { synchronized (Interface.this) { mClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); } } return AuthSuccess.Successful; } }); // start thread new Thread(future).start(); // obtain authentication return value AuthSuccess retVal = AuthSuccess.UnknownError; try { retVal = future.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return retVal; }
From source file:com.alibaba.dragoon.common.protocol.transport.socket.SocketConnector.java
public Future<DragoonSession> connect(final SocketAddress address, final MessageHandler messageHandler) { if (address == null) { throw new IllegalArgumentException("address is null"); }/* w ww . j av a2 s . co m*/ if (!(address instanceof InetSocketAddress)) { throw new IllegalArgumentException("address must be VmPipeAddress."); } final InetSocketAddress inetSocketAddress = (InetSocketAddress) address; FutureTask<DragoonSession> task = new FutureTask<DragoonSession>(new Callable<DragoonSession>() { public DragoonSession call() throws Exception { connectCount.incrementAndGet(); if (LOG.isInfoEnabled()) { LOG.info("CONNECT TO " + inetSocketAddress); } remoteAddress = inetSocketAddress.toString(); Socket socket = new Socket(inetSocketAddress.getAddress(), inetSocketAddress.getPort()); connectEstablishedCount.incrementAndGet(); if (LOG.isInfoEnabled()) { LOG.info("CONNECTED TO " + inetSocketAddress); } SocketSessionImpl impl = new SocketSessionImpl(socket, receivedBytes, receivedMessages, sentBytes, sentMessages); final long sessionId = generateSessionId(); DragoonSession session = new DragoonSession(sessionId, new DragoonSessionConfig(messageHandler), impl); impl.init(session); return session; } }); connectorExecutor.submit(task); return task; }
From source file:com.taobao.common.tfs.comm.TfsClientFactory.java
public TfsClient get(Long targetId, final int connectionTimeout, final PacketStreamer pstreamer) throws TfsException { final Long key = targetId; if (clients.containsKey(key)) { try {/* ww w . j ava2s. c o m*/ return clients.get(key).get(); } catch (Exception e) { removeClient(key); throw new TfsException("get tfs connection error,targetAddress is " + targetId, e); } } else { FutureTask<TfsClient> task = new FutureTask<TfsClient>(new Callable<TfsClient>() { public TfsClient call() throws Exception { return createClient(key, connectionTimeout, pstreamer); } }); FutureTask<TfsClient> existTask = clients.putIfAbsent(key, task); if (existTask == null) { existTask = task; task.run(); } try { return existTask.get(); } catch (Exception e) { removeClient(key); throw new TfsException("get tfs connection error,targetAddress is " + targetId, e); } } }