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:com.teradata.benchto.driver.execution.ExecutionSynchronizer.java

/**
 * Executes {@code callable} when time comes. The {@code callable} gets executed immediately, without
 * offloading to a backghround thread, if execution time requested has already passed.
 *///from www . j a  v  a 2s .c om
public <T> CompletableFuture<T> execute(Instant when, Callable<T> callable) {
    if (!Instant.now().isBefore(when)) {
        // Run immediately.
        try {
            return completedFuture(callable.call());
        } catch (Exception e) {
            CompletableFuture<T> future = new CompletableFuture<>();
            future.completeExceptionally(e);
            return future;
        }
    }

    long delay = Instant.now().until(when, ChronoUnit.MILLIS);
    CompletableFuture<T> future = new CompletableFuture<>();
    executorService.schedule(() -> {
        try {
            future.complete(callable.call());
        } catch (Throwable e) {
            future.completeExceptionally(e);
            throw e;
        }
        return null;
    }, delay, MILLISECONDS);

    return future;
}

From source file:org.eclipse.smarthome.transform.map.internal.MapTransformationServiceTest.java

protected void waitForAssert(Callable<Void> assertion, int timeout, int sleepTime) throws Exception {
    int waitingTime = 0;
    while (waitingTime < timeout) {
        try {// ww  w.  j  av  a  2 s  .c om
            assertion.call();
            return;
        } catch (AssertionError error) {
            waitingTime += sleepTime;
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    assertion.call();
}

From source file:com.fitbur.testify.junit.system.internal.SpringBootInterceptor.java

public EmbeddedServletContainer startEmbeddedServletContainer(
        @SuperCall Callable<EmbeddedServletContainer> zuper, @This Object object) throws Exception {
    EmbeddedServletContainer container = zuper.call();
    SpringBootDescriptor descriptor = getDescriptor(object);
    descriptor.setServletContainer(container);

    return container;
}

From source file:com.fitbur.testify.junit.system.internal.SpringBootInterceptor.java

@RuntimeType
@BindingPriority(Integer.MAX_VALUE)
public Object anyMethod(@SuperCall Callable<?> zuper, @This(optional = true) Object object,
        @AllArguments Object[] args) throws Exception {
    return zuper.call();
}

From source file:org.obiba.mica.search.csvexport.SpecificStudyReportGenerator.java

private String localizedField(Callable<LocalizedString> field) {
    return field(() -> field.call().get(this.locale));
}

From source file:org.obiba.mica.search.csvexport.SpecificStudyReportGenerator.java

private String field(Callable<String> field) {
    try {//from   w  ww.  j a  v a  2 s.c o m
        return field.call();
    } catch (Exception e) {
        logger.debug("Error while generating csv custom report", e);
        return "";
    }
}

From source file:com.example.SampleAppIntegrationTest.java

@Test
public void testSample() throws Exception {
    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    String message = "test message " + UUID.randomUUID();

    map.add("messageBody", message);
    map.add("username", "testUserName");

    this.restTemplate.postForObject("/newMessage", map, String.class);

    Callable<Boolean> logCheck = () -> baos.toString()
            .contains("New message received from testUserName via polling: " + message);
    Awaitility.await().atMost(10, TimeUnit.SECONDS).until(logCheck);

    assertThat(logCheck.call()).isTrue();
}

From source file:org.polymap.core.runtime.PolymapJobExecutor.java

@Override
public <T> Future<T> submit(final Callable<T> task) {
    Job job = new Job("ExecutorJob") {
        protected IStatus run(IProgressMonitor monitor) {
            try {
                T resultValue = task.call();
                setProperty(FutureJobAdapter.RESULT_VALUE_NAME, resultValue);
                return Status.OK_STATUS;
            } catch (Throwable e) {
                return new Status(IStatus.ERROR, CorePlugin.ID, e.getLocalizedMessage(), e);
            }// w w w . j a v  a  2s  .c  o m
        }
    };
    job.setSystem(true);
    job.setPriority(UIJob.DEFAULT_PRIORITY);
    job.schedule();
    return new FutureJobAdapter(job);
}

From source file:org.codehaus.mojo.unix.maven.sysvpkg.PkgUnixPackage.java

public void packageToFile(File packageFile, ScriptUtil.Strategy strategy) throws Exception {
    // -----------------------------------------------------------------------
    // Validate that the prototype looks sane
    // -----------------------------------------------------------------------

    // TODO: This should be more configurable
    RelativePath[] specialPaths = new RelativePath[] { BASE, relativePath("/etc"), relativePath("/etc/opt"),
            relativePath("/opt"), relativePath("/usr"), relativePath("/var"), relativePath("/var/opt"), };

    // TODO: This should use setDirectoryAttributes
    for (RelativePath specialPath : specialPaths) {
        if (prototypeFile.hasPath(specialPath)) {
            // TODO: this should come from a common time object so that all "now" timestamps are the same
            prototypeFile.addDirectory(directory(specialPath, new LocalDateTime(), EMPTY));
        }// w w w  .  ja v  a  2  s  .c  o m
    }

    // -----------------------------------------------------------------------
    // The shit
    // -----------------------------------------------------------------------

    File workingDirectoryF = asFile(workingDirectory);
    File pkginfoF = asFile(pkginfo);
    File prototypeF = asFile(prototype);

    ScriptUtil.Result result = scriptUtil
            .createExecution(classifier.orSome("default"), "pkg", getScripts(), workingDirectoryF, strategy)
            .execute();

    LineStreamUtil.toFile(pkginfoFile.toList(), pkginfoF);

    String pkg = pkginfoFile.getPkgName(pkginfoF);

    prototypeFile.addIFileIf(pkginfoF, "pkginfo");
    prototypeFile.addIFileIf(result.preInstall, "preinstall");
    prototypeFile.addIFileIf(result.postInstall, "postinstall");
    prototypeFile.addIFileIf(result.preRemove, "preremove");
    prototypeFile.addIFileIf(result.postRemove, "postremove");
    for (File file : result.customScripts) {
        prototypeFile.addIFileIf(file);
    }

    workingDirectory.resolveFile("assembly");

    // TODO: Replace this with an Actor-based execution
    for (Callable operation : operations) {
        operation.call();
    }

    LineStreamUtil.toFile(prototypeFile, prototypeF);

    new PkgmkCommand().setDebug(debug).setOverwrite(true).setDevice(workingDirectoryF).setPrototype(prototypeF)
            .execute();

    new PkgtransCommand().setDebug(debug).setAsDatastream(true).setOverwrite(true).execute(workingDirectoryF,
            packageFile, pkg);
}

From source file:org.fishwife.jrugged.spring.retry.ExtendedRetryTemplate.java

/***
 * Execute a given {@link Callable} with retry logic.
 *
 * @param callable The callable to execute
 * @param <T> The return type of the callable
 * @return The result of the callable//from  ww  w .  j a v a2s .  c om
 * @throws Exception
 * @throws ExhaustedRetryException If all retry attempts have been exhausted
 */
public <T> T execute(final Callable<T> callable) throws Exception, ExhaustedRetryException {
    return execute(new RetryCallback<T>() {
        public T doWithRetry(RetryContext retryContext) throws Exception {
            return callable.call();
        }
    });
}