Example usage for java.util.concurrent Callable call

List of usage examples for java.util.concurrent Callable call

Introduction

In this page you can find the example usage for java.util.concurrent Callable call.

Prototype

V call() throws Exception;

Source Link

Document

Computes a result, or throws an exception if unable to do so.

Usage

From source file:Main.java

public TimedFutureTask(final Callable<Object> callable, final int timeoutMS) {
    timedCallable = (new Callable<Object>() {
        @Override//ww w.  j  a  v  a 2 s.  co m
        public Object call() throws Exception {
            cancelTimer = new Timer();
            cancelTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    f.cancel(true);
                }
            }, timeoutMS);
            final Object res = callable.call();
            cancelTimer.cancel();
            return res;
        }
    });
}

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

public static String check(final Future future, final long delayTime, final Callable<String> suffixCallable) {
    try {/*from  w w  w .  j a  v  a  2s  .c om*/
        try {
            future.get(delayTime, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            future.get(REQUEST_TIMEOUT, TimeUnit.MILLISECONDS);
            return AnsiColor.colorize(StringProcessor.fillWithSpaces("DELAYED", STATE_RANGE, Alignment.LEFT),
                    AnsiColor.ANSI_GREEN);
        }
    } catch (InterruptedException ex) {
        countError();
        return AnsiColor.colorize(StringProcessor.fillWithSpaces("INTERRUPTED", STATE_RANGE, Alignment.LEFT),
                AnsiColor.ANSI_YELLOW);
    } catch (ExecutionException ex) {
        countError();
        return AnsiColor.colorize(StringProcessor.fillWithSpaces("FAILED", STATE_RANGE, Alignment.LEFT),
                AnsiColor.ANSI_RED);
    } catch (TimeoutException ex) {
        countError();
        return AnsiColor.colorize(StringProcessor.fillWithSpaces("TIMEOUT", STATE_RANGE, Alignment.LEFT),
                AnsiColor.ANSI_CYAN);
    }

    String suffix;
    try {
        suffix = (suffixCallable != null ? suffixCallable.call() : "");
    } catch (Exception e) {
        suffix = "?";
    }

    return AnsiColor.colorize(StringProcessor.fillWithSpaces("OK" + suffix, STATE_RANGE, Alignment.LEFT),
            AnsiColor.ANSI_GREEN);
}

From source file:com.grepcurl.random.ObjectGenerator.java

@SuppressWarnings("RedundantCast")
protected <T> boolean _processCustom(SetterOverrides setterOverrides, Class<?> classUsedForOverrides,
        Method method, T t) throws Exception {
    if (setterOverrides != null) {
        Callable c = setterOverrides.get(classUsedForOverrides, method.getName());
        if (c != null) {
            Object params = c.call();
            method.invoke(t, params == null ? (Object) null : params);
            return true;
        }//from   w ww  . j av  a  2 s  . com
    }

    if (defaultSetterOverrides != null) {
        Callable c = defaultSetterOverrides.get(classUsedForOverrides, method.getName());
        if (c != null) {
            Object params = c.call();
            method.invoke(t, params == null ? (Object) null : params);
            return true;
        }
    }
    if (classUsedForOverrides.getSuperclass() != null) {
        return _processCustom(setterOverrides, classUsedForOverrides.getSuperclass(), method, t);
    }
    return false;
}

From source file:com.zero_x_baadf00d.play.module.redis.RedisModuleImpl.java

@Override
public <T> T getOrElse(final String key, final TypeReference<T> typeReference, final Callable<T> block,
        final int expiration) {
    T data = this.get(key, typeReference);
    if (data == null) {
        try {//from  w  ww. ja  v  a 2 s.  com
            data = block.call();
            this.set(key, typeReference, data, expiration);
        } catch (Exception ex) {
            RedisModuleImpl.LOG.error("Something goes wrong during the Callable execution", ex);
        }
    }
    return data;
}

From source file:org.apache.storm.sql.compiler.backends.trident.TestPlanCompiler.java

private void waitForCompletion(long timeout, Callable<Boolean> cond) throws Exception {
    long start = TestUtils.monotonicNow();
    while (TestUtils.monotonicNow() - start < timeout && cond.call()) {
        Thread.sleep(100);//from www .  j  av  a  2  s. c  om
    }
}

From source file:org.ros.time.RemoteUptimeClock.java

/**
 * Creates a new {@link UptimeCalculationResult} where the local uptime has
 * been adjusted to compensate for latency while retrieving the remote uptime.
 *
 * @param callable/*from w w  w .  jav a 2 s. co  m*/
 *          returns the remote uptime as quickly as possible
 * @return a new {@link UptimeCalculationResult}
 */
private UptimeCalculationResult calculateNewUptime(Callable<Double> callable) {
    double newLocalUptime = localUptimeProvider.getSeconds();
    double newRemoteUptime;
    try {
        newRemoteUptime = callable.call();
    } catch (Exception e) {
        log.error(e);
        throw new RosRuntimeException(e);
    }
    double latency = localUptimeProvider.getSeconds() - newLocalUptime;
    double latencyOffset = latency / 2;
    newLocalUptime += latencyOffset;
    return new UptimeCalculationResult(newLocalUptime, newRemoteUptime, latency);
}

From source file:org.ros.internal.node.client.Registrar.java

private <T> boolean callMaster(Callable<Response<T>> callable) {
    Preconditions.checkNotNull(nodeIdentifier, "Registrar not started.");
    boolean success;
    try {//from   w ww . ja v  a2 s.  c  o m
        Response<T> response = callable.call();
        if (log.isDebugEnabled()) {
            log.debug(response);
        }
        success = response.isSuccess();
    } catch (Exception e) {
        log.error("Exception caught while communicating with master.", e);

        success = false;
    }
    return success;
}

From source file:eu.esdihumboldt.hale.doc.util.content.AbstractVelocityContent.java

/**
 * Generate content from the template and the given context factory. If
 * called more than once with the same id, the previously generated content
 * for that id is returned./*from  w w  w . ja  v  a2 s  .  co m*/
 * 
 * @param contentId the content id
 * @param templateId the template id (there may be multiple templates)
 * @param contextFactory the context factory, is called once or not at all
 * @return the content input stream to return in
 *         {@link #getInputStream(String, String, Locale)}
 * @throws Exception if an error occurs creating the content
 */
protected InputStream getContentFromTemplate(String contentId, String templateId,
        Callable<VelocityContext> contextFactory) throws Exception {
    init(templateId);

    // creates the template file into the temporary directory
    // if it doesn't already exist
    File contentFile = new File(tempDir, templateId + "_" + contentId + ".html");
    if (!contentFile.exists()) {
        // get the template context
        VelocityContext context = contextFactory.call();

        // get the template
        Template template = ve.getTemplate(templateId + ".vm", "UTF-8");

        // write to the file
        FileWriter fw = new FileWriter(contentFile);
        template.merge(context, fw);

        fw.close();

        contentFile.deleteOnExit();
    }

    return new FileInputStream(contentFile);
}

From source file:org.orbeon.oxf.xforms.submission.XFormsModelSubmission.java

/**
 * Run the given submission callable. This must be a callable for a replace="all" submission.
 *
 * @param callable          callable run
 * @param response          response to write to if needed
 *///www  .j  a  v  a  2 s  . c o  m
public static void runDeferredSubmission(Callable<SubmissionResult> callable,
        ExternalContext.Response response) {
    // Run submission
    try {
        final SubmissionResult result = callable.call();
        if (result != null) {
            // Callable did not do all the work, completed it here
            try {
                if (result.getReplacer() != null) {
                    // Replacer provided, perform replacement
                    if (result.getReplacer() instanceof AllReplacer)
                        AllReplacer.forwardResultToResponse(result.getConnectionResult(), response);
                    else if (result.getReplacer() instanceof RedirectReplacer)
                        RedirectReplacer.replace(result.getConnectionResult(), response);
                    else
                        assert result.getReplacer() instanceof NoneReplacer;
                } else if (result.getThrowable() != null) {
                    // Propagate throwable, which might have come from a separate thread
                    throw new OXFException(result.getThrowable());
                } else {
                    // Should not happen
                }
            } finally {
                result.close();
            }
        }
    } catch (Exception e) {
        // Something bad happened
        throw new OXFException(e);
    }
}

From source file:org.springframework.aop.interceptor.AsyncExecutionAspectSupport.java

/**
 * Delegate for actually executing the given task with the chosen executor.
 * @param task the task to execute/*from   w  w w. java  2s  .  c  o m*/
 * @param executor the chosen executor
 * @param returnType the declared return type (potentially a {@link Future} variant)
 * @return the execution result (potentially a corresponding {@link Future} handle)
 */
@Nullable
protected Object doSubmit(Callable<Object> task, AsyncTaskExecutor executor, Class<?> returnType) {
    if (CompletableFuture.class.isAssignableFrom(returnType)) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                return task.call();
            } catch (Throwable ex) {
                throw new CompletionException(ex);
            }
        }, executor);
    } else if (ListenableFuture.class.isAssignableFrom(returnType)) {
        return ((AsyncListenableTaskExecutor) executor).submitListenable(task);
    } else if (Future.class.isAssignableFrom(returnType)) {
        return executor.submit(task);
    } else {
        executor.submit(task);
        return null;
    }
}