Example usage for java.util.concurrent Future isCancelled

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

Introduction

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

Prototype

boolean isCancelled();

Source Link

Document

Returns true if this task was cancelled before it completed normally.

Usage

From source file:org.openbase.bco.manager.util.launch.BCOSystemValidator.java

public static void main(String[] args) {
    BCO.printLogo();//from   w w w  .ja v a2  s .  c om
    JPService.setApplicationName("bco-validate");
    JPService.registerProperty(JPDebugMode.class);
    JPService.registerProperty(JPVerbose.class);
    JPService.parseAndExitOnError(args);

    try {
        System.out.println("==================================================");
        System.out.println("BaseCubeOne - System Validator");
        System.out.println("==================================================");
        System.out.println();

        System.out.println("=== " + AnsiColor.colorize("Check Registries", AnsiColor.ANSI_BLUE) + " ===\n");

        final BooleanComparator trueFirstBooleanComparator = new BooleanComparator(true);
        final BooleanComparator falseFirstBooleanComparator = new BooleanComparator(false);
        // check
        List<RegistryRemote> registries = Registries.getRegistries(false);
        registries.sort((registryRemote, t1) -> falseFirstBooleanComparator.compare(
                registryRemote instanceof AbstractVirtualRegistryRemote,
                t1 instanceof AbstractVirtualRegistryRemote));
        for (final RegistryRemote registry : registries) {
            if (!check(registry, TimeUnit.SECONDS.toMillis(2))) {
                if (registry.isConsistent()) {
                    System.out.println(
                            StringProcessor.fillWithSpaces(registry.getName(), LABEL_RANGE, Alignment.RIGHT)
                                    + "  " + AnsiColor.colorize(OK, AnsiColor.ANSI_GREEN));
                } else {
                    System.out.println(
                            StringProcessor.fillWithSpaces(registry.getName(), LABEL_RANGE, Alignment.RIGHT)
                                    + "  " + AnsiColor.colorize("INCONSISTENT", AnsiColor.ANSI_RED));
                }
            }
        }
        System.out.println();

        System.out.println("=== " + AnsiColor.colorize("Check Units", AnsiColor.ANSI_BLUE) + " ===\n");
        Future<List<UnitRemote<?>>> futureUnits = Units.getFutureUnits(false);

        System.out.println(StringProcessor.fillWithSpaces("Unit Pool", LABEL_RANGE, Alignment.RIGHT) + "  "
                + check(futureUnits, DEFAULT_UNIT_POOL_DELAY_TIME));
        System.out.println();

        if (futureUnits.isCancelled()) {
            System.out.println(AnsiColor.colorize(
                    "Connection could not be established, please make sure BaseCubeOne is up and running!\n",
                    AnsiColor.ANSI_YELLOW));
            try {
                futureUnits.get();
            } catch (ExecutionException | CancellationException ex) {
                ExceptionPrinter.printHistory("Error Details", ex, System.err);
            }
        } else {
            boolean printed = false;
            final List<UnitRemote<?>> unitList = new ArrayList<>(futureUnits.get());
            unitList.sort((unitRemote, t1) -> {
                try {
                    return trueFirstBooleanComparator.compare(unitRemote.isDalUnit(), t1.isDalUnit());
                } catch (CouldNotPerformException ex) {
                    LOGGER.warn("Could not compare unit[" + unitRemote + "] and unit[" + t1 + "]", ex);
                    return 0;
                }
            });
            for (final UnitRemote<?> unit : unitList) {
                printed = check(unit) || printed;
            }
            if (!printed) {
                System.out.println(
                        StringProcessor.fillWithSpaces("Unit Connections", LABEL_RANGE, Alignment.RIGHT) + "  "
                                + AnsiColor.colorize(OK, AnsiColor.ANSI_GREEN));
            }
        }
    } catch (InterruptedException ex) {
        System.out.println("killed");
        System.exit(253);
        return;
    } catch (Exception ex) {
        ExceptionPrinter.printHistory(new CouldNotPerformException("Could not validate system!", ex),
                System.err);
        System.exit(254);
    }

    System.out.println();
    System.out.println("==============================================================");
    System.out.print("===  ");
    switch (errorCounter) {
    case 0:
        System.out.print(AnsiColor.colorize("VALIDATION SUCCESSFUL", AnsiColor.ANSI_GREEN));
        break;
    default:
        System.out.print(errorCounter + " " + AnsiColor
                .colorize("ERROR" + (errorCounter > 1 ? "S" : "") + " DETECTED", AnsiColor.ANSI_RED));
        break;
    }
    System.out.println(" average ping is "
            + AnsiColor.colorize(pingFormat.format(getGlobalPing()), AnsiColor.ANSI_CYAN) + " milli");
    System.out.println("==============================================================");
    System.out.println();
    System.exit(Math.min(errorCounter, 200));
}

From source file:Main.java

private static boolean cancel(final Future<?> future) {
    return future.isDone() || future.isCancelled() || future.cancel(true);
}

From source file:Main.java

public static boolean isCancelled(final Future<?> future) {
    return (future != null) && future.isCancelled();
}

From source file:controllers.GWT2Controller.java

private static Object chainDo(GWT2ChainRuntime chain) {
    Future<?> f = chain.getFuture();
    while (f.isDone() || f.isCancelled()) {
        await(100);//from www . j  a  va2 s  .  co  m
    }
    try {
        return f.get();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.openbase.bco.manager.util.launch.BCOSystemValidator.java

public static boolean check(final Remote<?> remote, final long delayTime) {

    boolean printed = false;

    Future<Long> futurePing = remote.ping();

    try {/*  w ww . j  av  a  2  s  .  c o  m*/
        printed |= print(remote, StringProcessor.fillWithSpaces("Ping", LABEL_RANGE, Alignment.RIGHT) + "  "
                + check(futurePing, delayTime, () -> {
                    if (futurePing.isDone() && !futurePing.isCancelled()) {
                        BCOSystemValidator.computeGlobalPing(futurePing.get());
                        return " (" + futurePing.get() + ")";
                    } else {
                        return "";
                    }
                }));
    } catch (CancellationException ex) {
        throw ex;
    } catch (Exception ex) {
        ExceptionPrinter.printHistory(new FatalImplementationErrorException(BCOSystemValidator.class, ex),
                LOGGER);
    }

    boolean online = futurePing.isDone() && !futurePing.isCancelled();

    if (online) {
        // ping does not cause the connection state to be connected, this is done by a data update, therefore wait a bit for the connection state
        try {
            remote.waitForConnectionState(ConnectionState.CONNECTED, delayTime);
        } catch (org.openbase.jul.exception.TimeoutException ex) {
            // just continue and print error for next step
        } catch (CouldNotPerformException ex) {
            ExceptionPrinter.printHistory(ex, LOGGER);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        final ConnectionState connectionState = remote.getConnectionState();
        String connectionDescription = StringProcessor.fillWithSpaces("Connection", LABEL_RANGE,
                Alignment.RIGHT) + "  ";
        switch (connectionState) {
        case CONNECTED:
            connectionDescription += AnsiColor.colorize(
                    StringProcessor.fillWithSpaces(OK, STATE_RANGE, Alignment.LEFT), AnsiColor.ANSI_GREEN);
            break;
        case DISCONNECTED:
        case CONNECTING:
            countError();
            connectionDescription += AnsiColor.colorize(
                    StringProcessor.fillWithSpaces(connectionState.name(), STATE_RANGE, Alignment.LEFT),
                    AnsiColor.ANSI_RED);
            break;
        case RECONNECTING:
            connectionDescription += AnsiColor.colorize(
                    StringProcessor.fillWithSpaces(connectionState.name(), STATE_RANGE, Alignment.LEFT),
                    AnsiColor.ANSI_YELLOW);
            break;
        default:
            connectionDescription += AnsiColor.colorize(
                    StringProcessor.fillWithSpaces("UNKNOWN", STATE_RANGE, Alignment.LEFT), AnsiColor.ANSI_RED);
            countError();
            break;
        }
        printed |= print(remote, connectionDescription);
    }

    if (online) {
        printed |= print(remote, StringProcessor.fillWithSpaces("Data Cache", LABEL_RANGE, Alignment.RIGHT)
                + "  " + check(remote.getDataFuture(), delayTime));
    } else {
        printed |= print(remote,
                StringProcessor.fillWithSpaces("Data Cache", LABEL_RANGE, Alignment.RIGHT) + "  "
                        + (remote.isDataAvailable()
                                ? AnsiColor.colorize(
                                        StringProcessor.fillWithSpaces("OFFLINE", STATE_RANGE, Alignment.LEFT),
                                        AnsiColor.ANSI_YELLOW)
                                : AnsiColor.colorize(
                                        StringProcessor.fillWithSpaces("EMPTY", STATE_RANGE, Alignment.LEFT),
                                        AnsiColor.ANSI_RED)));
    }

    if (online) {
        try {
            printed |= print(remote,
                    StringProcessor.fillWithSpaces("Synchronization", LABEL_RANGE, Alignment.RIGHT) + "  "
                            + check(remote.requestData(), delayTime));
        } catch (CouldNotPerformException e) {
            countError();
            printed |= print(remote,
                    StringProcessor.fillWithSpaces("Synchronization", LABEL_RANGE, Alignment.RIGHT) + "  "
                            + AnsiColor.colorize(
                                    StringProcessor.fillWithSpaces("CANCELED", STATE_RANGE, Alignment.LEFT),
                                    AnsiColor.ANSI_RED));
        }
    }

    // add new line separator for better overview
    if (printed) {
        System.out.println();
    }

    return printed;
}

From source file:com.concursive.connect.web.portal.PortletManager.java

private static boolean renderPortlet(ActionContext context, PortletContainer container,
        DashboardPortlet thisPortlet, PortletWindowImpl portletWindow, PortalServletRequest portalRequest,
        PortalServletResponse portalResponse) {
    ExecutorService executor = null;
    List<Future<PortletWindowImpl>> futures = null;
    try {/* w w  w.j  a va2 s.  c o  m*/
        long doRenderStartTime = System.currentTimeMillis();
        // NOTE: The infrastructure is here to run in threads, but more work needs to be done
        // for this to be reliable.  So the timeout feature of Executor cannot be used yet
        //      if (thisPortlet.getTimeout() <= 0) {
        if (true) {
            // Remove the project since it might get set by another project
            if (LOG.isDebugEnabled()) {
                LOG.debug("before container.doRender");
                if (portalRequest.getAttribute("project") != null) {
                    LOG.debug("  The project for rendering: "
                            + ((Project) portalRequest.getAttribute("project")).getUniqueId());
                }
            }
            portalRequest.removeAttribute("project");
            // Render the portlet immediately
            container.doRender(portletWindow, portalRequest, portalResponse);
        } else {
            // Render the portlet using an executor; this will allow for cancelling timed-out portlets
            LOG.debug("Using executor...");
            List<PortletRenderTask> renderTasks = new ArrayList<PortletRenderTask>();
            renderTasks.add(new PortletRenderTask(container, portletWindow, portalRequest, portalResponse));
            executor = Executors.newFixedThreadPool(1);
            // NOTE: this wrapper fix is for Java 1.5
            final Collection<Callable<PortletWindowImpl>> wrapper = Collections
                    .<Callable<PortletWindowImpl>>unmodifiableCollection(renderTasks);
            if (thisPortlet.getTimeout() <= 0) {
                futures = executor.invokeAll(wrapper);
            } else {
                futures = executor.invokeAll(wrapper, thisPortlet.getTimeout(), TimeUnit.SECONDS);
            }
            for (Future<PortletWindowImpl> f : futures) {
                if (f.isCancelled()) {
                    LOG.debug("Portlet was cancelled due to timeout");
                    return false;
                }
            }
        }
        long doRenderEndTime = System.currentTimeMillis();
        LOG.debug("Portlet (" + thisPortlet.getName() + ") took: " + (doRenderEndTime - doRenderStartTime)
                + " ms");
        // When the portlet is rendered, place the response in the request for displaying later
        context.getRequest().setAttribute("portal_response_" + thisPortlet.getId(),
                portalResponse.getInternalBuffer().toString());
        LOG.trace("Render response: " + portalResponse.getInternalBuffer().toString());
    } catch (Exception re) {
        // The portlet could not be rendered so skip it
        LOG.error("Render exception", re);
        return false;
    } finally {
        if (executor != null) {
            executor.shutdown();
        }
    }
    return true;
}

From source file:org.eclipse.mylyn.commons.http.HttpUtil.java

/**
 * @since 3.6/*  ww w .  ja  v  a 2 s  .  c  om*/
 */
public static <T> T execute(IProgressMonitor monitor, WebRequest<T> request) throws Throwable {
    // check for legacy reasons
    SubMonitor subMonitor = (monitor instanceof SubMonitor) ? (SubMonitor) monitor : SubMonitor.convert(null);

    Future<T> future = CommonsHttpPlugin.getExecutorService().submit(request);
    while (true) {
        if (monitor.isCanceled()) {
            request.abort();

            // wait for executor to finish
            future.cancel(false);
            try {
                if (!future.isCancelled()) {
                    future.get();
                }
            } catch (CancellationException e) {
                // ignore
            } catch (InterruptedException e) {
                // ignore
            } catch (ExecutionException e) {
                // ignore
            }
            throw new OperationCanceledException();
        }

        try {
            return future.get(POLL_INTERVAL, TimeUnit.MILLISECONDS);
        } catch (ExecutionException e) {
            throw e.getCause();
        } catch (TimeoutException ignored) {
        }

        subMonitor.setWorkRemaining(20);
        subMonitor.worked(1);
    }
}

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

/**
 * Emits an asynchronous request.//www .  j a  va  2  s. c  o  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:org.eclipse.mylyn.commons.net.WebUtil.java

/**
 * @since 3.0//from ww w  .  ja v  a 2s  .  c o  m
 */
public static <T> T execute(IProgressMonitor monitor, WebRequest<T> request) throws Throwable {
    // check for legacy reasons
    SubMonitor subMonitor = (monitor instanceof SubMonitor) ? (SubMonitor) monitor : SubMonitor.convert(null);

    Future<T> future = CommonsNetPlugin.getExecutorService().submit(request);
    while (true) {
        if (monitor.isCanceled()) {
            request.abort();

            // wait for executor to finish
            future.cancel(false);
            try {
                if (!future.isCancelled()) {
                    future.get();
                }
            } catch (CancellationException e) {
                // ignore
            } catch (InterruptedException e) {
                // ignore
            } catch (ExecutionException e) {
                // ignore
            }
            throw new OperationCanceledException();
        }

        try {
            return future.get(POLL_INTERVAL, TimeUnit.MILLISECONDS);
        } catch (ExecutionException e) {
            throw e.getCause();
        } catch (TimeoutException ignored) {
        }

        subMonitor.setWorkRemaining(20);
        subMonitor.worked(1);
    }
}

From source file:org.apache.camel.impl.converter.FutureTypeConverter.java

@SuppressWarnings("unchecked")
private <T> T doConvertTo(Class<T> type, Exchange exchange, Object value) throws Exception {
    // do not convert to stream cache
    if (StreamCache.class.isAssignableFrom(value.getClass())) {
        return null;
    }//from   w  w w. ja  v  a  2 s .  co m

    if (Future.class.isAssignableFrom(value.getClass())) {

        Future future = (Future) value;

        if (future.isCancelled()) {
            // return void to indicate its not possible to convert at this time
            return (T) Void.TYPE;
        }

        // do some trace logging as the get is blocking until the response is ready
        if (LOG.isTraceEnabled()) {
            LOG.trace("Getting future response");
        }

        Object body = future.get();
        if (LOG.isTraceEnabled()) {
            LOG.trace("Got future response");
        }

        if (body == null) {
            // return void to indicate its not possible to convert at this time
            return (T) Void.TYPE;
        }

        // maybe from is already the type we want
        if (type.isAssignableFrom(body.getClass())) {
            return type.cast(body);
        } else if (body instanceof Exchange) {
            Exchange result = (Exchange) body;
            body = ExchangeHelper.extractResultBody(result, result.getPattern());
        }

        // no then try to lookup a type converter
        return converter.convertTo(type, exchange, body);
    }

    return null;
}