Example usage for java.util.concurrent Future isDone

List of usage examples for java.util.concurrent Future isDone

Introduction

In this page you can find the example usage for java.util.concurrent Future isDone.

Prototype

boolean isDone();

Source Link

Document

Returns true if this task completed.

Usage

From source file:eu.europa.ec.fisheries.uvms.plugins.ais.service.AisService.java

@Schedule(minute = "*/1", hour = "*", persistent = false)
public void connectAndRetrive() {
    if (!startUp.isEnabled()) {
        return;//ww w .j a v  a2 s . c o m
    }
    if (connection != null && !connection.isOpen()) {
        String host = startUp.getSetting("HOST");
        int port = Integer.parseInt(startUp.getSetting("PORT"));
        String username = startUp.getSetting("USERNAME");
        String password = startUp.getSetting("PASSWORD");

        connection.open(host, port, username, password);
    }

    if (connection != null && connection.isOpen()) {
        Iterator<Future<Long>> processIterator = processes.iterator();
        while (processIterator.hasNext()) {
            Future<Long> process = processIterator.next();
            if (process.isDone() || process.isCancelled()) {
                processIterator.remove();
            }
        }
        List<String> sentences = connection.getSentences();
        Future<Long> process = processService.processMessages(sentences);
        processes.add(process);
        LOG.info("Got {} sentences from AIS RA. Currently running {} parallel threads", sentences.size(),
                processes.size());
    }
}

From source file:org.openengsb.opencit.core.projectmanager.internal.SchedulingServiceImpl.java

@Override
public boolean isProjectBuilding(String projectId) {
    if (!buildFutures.containsKey(projectId)) {
        return false;
    }//from ww  w .  ja v  a 2 s.  co m
    Future<Boolean> future = buildFutures.get(projectId);
    return !future.isDone();
}

From source file:org.wisdom.test.http.HttpClientHelper.java

/**
 * Emits an asynchronous request.//from  ww w. j  a v  a  2  s.co m
 *
 * @param request       the request
 * @param responseClass the response class
 * @param callback      the completion callback
 * @param <T>           the type of the expected result
 * @return the future to retrieve the result
 */
public static <T> Future<HttpResponse<T>> requestAsync(HttpRequest request, final Class<T> responseClass,
        Callback<T> callback) {
    HttpUriRequest requestObj = prepareRequest(request);

    CloseableHttpAsyncClient asyncHttpClient = ClientFactory.getAsyncHttpClient();
    if (!asyncHttpClient.isRunning()) {
        asyncHttpClient.start();
    }

    final Future<org.apache.http.HttpResponse> future = asyncHttpClient.execute(requestObj,
            prepareCallback(responseClass, callback));

    return new Future<HttpResponse<T>>() {

        /**
         * Cancels the request.
         *
         * @param mayInterruptIfRunning whether or not we need to interrupt the request.
         * @return {@literal true} if the task is successfully canceled.
         */
        public boolean cancel(boolean mayInterruptIfRunning) {
            return future.cancel(mayInterruptIfRunning);
        }

        /**
         * @return whether the future is cancelled.
         */
        public boolean isCancelled() {
            return future.isCancelled();
        }

        /**
         * @return whether the result is available.
         */
        public boolean isDone() {
            return future.isDone();
        }

        /**
         * Gets the result.
         * @return the response.
         * @throws InterruptedException if the request is interrupted.
         * @throws ExecutionException if the request fails.
         */
        public HttpResponse<T> get() throws InterruptedException, ExecutionException {
            org.apache.http.HttpResponse httpResponse = future.get();
            return new HttpResponse<>(httpResponse, responseClass);
        }

        /**
         * Gets the result.
         * @param timeout timeout configuration
         * @param unit unit timeout
         * @return the response.
         * @throws InterruptedException if the request is interrupted.
         * @throws ExecutionException if the request fails.
         * @throws TimeoutException if the set time out is reached before the completion of the request.
         */
        public HttpResponse<T> get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            org.apache.http.HttpResponse httpResponse = future.get(timeout * TimeUtils.TIME_FACTOR, unit);
            return new HttpResponse<>(httpResponse, responseClass);
        }
    };
}

From source file:com.mycompany.crawlertest.GrabManager.java

private boolean checkPageGrabs() throws InterruptedException {
    Thread.sleep(PAUSE_TIME);/*from   www .j  a  v  a2s.co m*/
    Set<GrabPage> pageSet = new HashSet<>();
    Iterator<Future<GrabPage>> iterator = futures.iterator();

    while (iterator.hasNext()) {
        Future<GrabPage> future = iterator.next();
        if (future.isDone()) {
            iterator.remove();
            try {
                pageSet.add(future.get());
            } catch (InterruptedException e) { // skip pages that load too slow
            } catch (ExecutionException e) {
            }
        }
    }
    for (GrabPage grabPage : pageSet) {
        addNewURLs(grabPage);
    }

    return (futures.size() > 0);
}

From source file:com.adaptris.core.services.splitter.MessageSplitterServiceImp.java

protected void waitForCompletion(List<Future> tasks) throws ServiceException {
    do {//from w  ww .ja v a 2  s  . c  o m
        for (Iterator<Future> i = tasks.iterator(); i.hasNext();) {
            Future f = i.next();
            if (f.isDone()) {
                i.remove();
            }
        }
        if (tasks.size() > 0) {
            LifecycleHelper.waitQuietly(100);
        }
    } while (tasks.size() > 0);
}

From source file:com.msopentech.odatajclient.engine.it.AsyncTestITCase.java

@Test
public void updateEntity() throws InterruptedException, ExecutionException {
    final URI uri = client.getURIBuilder(testDefaultServiceRootURL).appendEntityTypeSegment("Product")
            .appendKeySegment(-10).build();

    final ODataRetrieveResponse<ODataEntity> entityRes = client.getRetrieveRequestFactory()
            .getEntityRequest(uri).execute();
    final ODataEntity entity = entityRes.getBody();
    entity.getAssociationLinks().clear();
    entity.getNavigationLinks().clear();
    entity.getEditMediaLinks().clear();//from  ww  w.  ja  v a  2 s  .  co  m
    entity.getProperty("Description")
            .setValue(client.getPrimitiveValueBuilder().setText("AsyncTest#updateEntity").build());

    final ODataEntityUpdateRequest updateReq = client.getCUDRequestFactory().getEntityUpdateRequest(uri,
            UpdateType.MERGE, entity);
    updateReq.setIfMatch(entityRes.getEtag());
    final Future<ODataEntityUpdateResponse> futureRes = updateReq.asyncExecute();

    while (!futureRes.isDone()) {
    }

    final ODataEntityUpdateResponse res = futureRes.get();
    assertNotNull(res);
    assertEquals(204, res.getStatusCode());
}

From source file:org.silverpeas.core.web.index.IndexationProcessExecutor.java

/**
 * Stops a current indexation operation if it exists a running one.<br>
 * Otherwise, nothing is done.//from w w w  .  java2 s .  co  m
 */
@SuppressWarnings({ "unchecked", "WeakerAccess", "unused" })
public void stopCurrentExecutionIfAny() {
    final Cache cache = CacheServiceProvider.getApplicationCacheService().getCache();
    Pair<IndexationProcess, Future<Void>> process = cache.get(INDEXATION_PROCESS_EXECUTOR_KEY, Pair.class);
    final Future<Void> task = (process != null) ? process.getRight() : null;
    if (process != null && !task.isDone()) {
        try {
            task.cancel(true);
        } catch (Exception e) {
            SilverLogger.getLogger(this).error("stopping indexation process failed", e);
        }
    }
}

From source file:com.googlecode.jsfFlex.shared.tasks.TaskRunnerImpl.java

public boolean isTaskDone(String taskName) {
    Future<Void> task = _queuedTasks.get(taskName);
    return (task != null && task.isDone());
}

From source file:com.magnet.plugin.helpers.URLHelper.java

public static InputStream loadUrl(final String url) throws Exception {
    final InputStream[] inputStreams = new InputStream[] { null };
    final Exception[] exception = new Exception[] { null };
    Future<?> downloadThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
        public void run() {
            try {
                HttpURLConnection connection;
                if (ApplicationManager.getApplication() != null) {
                    connection = HttpConfigurable.getInstance().openHttpConnection(url);
                } else {
                    connection = (HttpURLConnection) new URL(url).openConnection();
                    connection.setReadTimeout(Rest2MobileConstants.CONNECTION_TIMEOUT);
                    connection.setConnectTimeout(Rest2MobileConstants.CONNECTION_TIMEOUT);
                }/*from  w  ww.  j a  va 2  s. com*/
                connection.connect();

                inputStreams[0] = connection.getInputStream();
            } catch (IOException e) {
                exception[0] = e;
            }
        }
    });

    try {
        downloadThreadFuture.get(5, TimeUnit.SECONDS);
    } catch (TimeoutException ignored) {
    }

    if (!downloadThreadFuture.isDone()) {
        downloadThreadFuture.cancel(true);
        throw new ConnectionException(IdeBundle.message("updates.timeout.error"));
    }

    if (exception[0] != null)
        throw exception[0];
    return inputStreams[0];
}

From source file:org.apache.olingo.client.core.it.v3.AsyncTestITCase.java

@Test
public void updateEntity() throws InterruptedException, ExecutionException {
    final URI uri = client.getURIBuilder(testStaticServiceRootURL).appendEntitySetSegment("Product")
            .appendKeySegment(-10).build();

    final ODataRetrieveResponse<ODataEntity> entityRes = client.getRetrieveRequestFactory()
            .getEntityRequest(uri).execute();
    final ODataEntity entity = entityRes.getBody();
    entity.getAssociationLinks().clear();
    entity.getNavigationLinks().clear();
    entity.getEditMediaLinks().clear();//from   w w  w .  ja va2  s. c om
    entity.getProperty("Description")
            .setValue(client.getPrimitiveValueBuilder().setText("AsyncTest#updateEntity").build());

    final ODataEntityUpdateRequest updateReq = client.getCUDRequestFactory().getEntityUpdateRequest(uri,
            UpdateType.MERGE, entity);
    updateReq.setIfMatch(entityRes.getEtag());
    final Future<ODataEntityUpdateResponse> futureRes = updateReq.asyncExecute();

    while (!futureRes.isDone()) {
        Thread.sleep(1000L);
    }

    final ODataEntityUpdateResponse res = futureRes.get();
    assertNotNull(res);
    assertEquals(204, res.getStatusCode());
}