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:org.thingsboard.rule.engine.action.TbAlarmNodeTest.java

@Before
public void before() {
    dbExecutor = new ListeningExecutor() {
        @Override//from w w w .  ja v a 2 s .  c  o  m
        public <T> ListenableFuture<T> executeAsync(Callable<T> task) {
            try {
                return Futures.immediateFuture(task.call());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void execute(Runnable command) {
            command.run();
        }
    };
}

From source file:org.cloudfoundry.android.cfdroid.CloudFoundry.java

/**
 * Ensures that a proper {@link CloudFoundryClient} exists and handles
 * connection errors.// w  ww . j a  v  a  2s  .co  m
 */

private <R> R doWithClient(Callable<R> work) {
    ensureClient();
    try {
        return work.call();
    } catch (CloudFoundryException e) {
        // Landing here surely means that
        // our client object holds a stale token.
        // Throw it away and retry.
        if (attempt == 0 && e.getStatusCode() == HttpStatus.FORBIDDEN) {
            Ln.w(e, "Caught exception for the first time. Assuming stale token, will retry.");
            attempt++;
            cache.client = null;
            accountManager.invalidateAuthToken(Accounts.ACCOUNT_TYPE, cache.token);
            cache.token = null;
            R result = doWithClient(work);
            attempt--;
            return result;
        } else {
            Ln.w(e, "Caught exception for the second time. Rethrowing");
            throw e;
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.artifactory.storage.db.DbServiceImpl.java

@Override
public <T> T invokeInTransaction(String transactionName, Callable<T> execute) {
    if (StringUtils.isNotBlank(transactionName)) {
        TransactionSynchronizationManager.setCurrentTransactionName(transactionName);
    }// w w w .  j  a  v  a2 s.c o  m
    try {
        return execute.call();
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RuntimeException(e);
    }
}

From source file:net.orfjackal.retrolambda.test.LambdaTest.java

@Test
public void lambdas_with_marker_interfaces_due_to_intersection_types() throws Exception {
    // We must use something other than java.io.Serializable as the marker interface,
    // because serializable lambdas are signified by a flag to LambdaMetafactory.altMetafactory
    Callable<String> lambda = (Callable<String> & Cloneable) () -> "foo";

    assertThat(lambda, is(instanceOf(Cloneable.class)));
    assertThat(lambda.call(), is("foo"));
}

From source file:org.thingsboard.rule.engine.action.TbAlarmNodeTest.java

private void mockJsExecutor() {
    when(ctx.getJsExecutor()).thenReturn(executor);
    doAnswer((Answer<ListenableFuture<Boolean>>) invocationOnMock -> {
        try {//from  ww w  .j  a  v  a2  s.  c o  m
            Callable task = (Callable) (invocationOnMock.getArguments())[0];
            return Futures.immediateFuture((Boolean) task.call());
        } catch (Throwable th) {
            return Futures.immediateFailedFuture(th);
        }
    }).when(executor).executeAsync(any(Callable.class));
}

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

public ConfigurableApplicationContext createApplicationContext(
        @SuperCall Callable<ConfigurableApplicationContext> zuper, @This Object object) throws Exception {
    SpringApplication app = (SpringApplication) object;

    AnnotationConfigEmbeddedWebApplicationContext context = (AnnotationConfigEmbeddedWebApplicationContext) zuper
            .call();//  ww w . ja  v  a 2s  . c  o m

    context.setAllowBeanDefinitionOverriding(true);
    context.setAllowCircularReferences(false);

    SpringBootDescriptor descriptor = descriptors.computeIfAbsent(context, SpringBootDescriptor::new);
    apps.putIfAbsent(app, descriptor);

    ServiceAnnotations serviceAnnotations = new ServiceAnnotations();
    serviceAnnotations.addInjectors(Inject.class, Autowired.class, Real.class);
    serviceAnnotations.addNamedQualifier(Named.class, Qualifier.class);
    serviceAnnotations.addCustomQualfier(javax.inject.Qualifier.class, Qualifier.class);
    descriptor.setServiceAnnotations(serviceAnnotations);

    TestContext testContext = testContexts.get(app);
    descriptor.setTestContext(testContext);

    SpringServiceLocator serviceLocator = new SpringServiceLocator(context, serviceAnnotations);
    descriptor.setServiceLocator(serviceLocator);

    TestNeeds testNeeds = new TestNeeds(testContext, testContext.getName(), NeedScope.METHOD);
    testNeeds.init();

    descriptor.setTestNeeds(testNeeds);

    TestNeedContainers testContainerNeeds = new TestNeedContainers(testContext, testContext.getName(),
            NeedScope.METHOD);
    testContainerNeeds.init();
    descriptor.setTestContainerNeeds(testContainerNeeds);

    SpringServicePostProcessor postProcessor = new SpringServicePostProcessor(serviceLocator, testNeeds,
            testContainerNeeds, null, null);

    context.addBeanFactoryPostProcessor(postProcessor);

    return context;
}

From source file:com.ebay.cloud.cms.service.resources.impl.QueryResource.java

private <T> T execute(String reponame, String query, Callable<T> call) {
    try {/*ww w  . j a v  a  2s. c  o m*/
        return call.call();
    } catch (CannotServeException e) {
        logger.error("Error when exectue query {}", e, query);
        throw new ServiceUnavailableException(e.getMessage());
    } catch (RepositoryNotExistsException e) {
        logger.error("Error when exectue query {}", e, query);
        throw new NotFoundException("repository not found: " + reponame);
    } catch (QueryException e) {
        logger.error("Error when exectue query {}", e, query);
        throw new CMSServerException(e.getErrorCode(), e.getMessage(), e);
    } catch (CmsDalException e) {
        logger.error("Error when exectue query {}", e, query);
        throw ExceptionMapper.convert(e);
    } catch (CmsEntMgrException e) {
        logger.error("Error when exectue query {}", e, query);
        throw ExceptionMapper.convert(e);
    } catch (WebApplicationException e) {
        logger.error("Error when exectue query {}", e, query);
        throw e;
    } catch (Throwable t) {
        logger.error("Error when exectue query {}", t, query);
        throw new CMSServerException(t);
    }
}

From source file:org.force66.circuit.Circuit.java

public T invoke(Callable<T> operation) {
    Validate.notNull(operation, "Null operation not allowed.");
    if (!circuitBreakerAlgorithm.isExecutionAllowed()) {
        throw new CircuitException("Operation not available.")
                .addContextValue("callable class", operation.getClass().getName())
                .addContextValue("callable", operation.toString());
    }/*from w w  w .  jav a  2 s .c  o m*/

    try {
        T output = operation.call();
        circuitBreakerAlgorithm.reportExecutionSuccess();
        return output;
    } catch (Exception e) {
        circuitBreakerAlgorithm.reportExecutionFailure(e);
        throw new CircuitException(e).addContextValue("callable class", operation.getClass().getName())
                .addContextValue("callable", operation.toString());
    }

}

From source file:org.apache.ode.bpel.engine.Contexts.java

public <T> T execTransaction(Callable<T> transaction) throws Exception {
    try {//from w ww. j a  va  2  s  .  com
        txManager.begin();
    } catch (Exception ex) {
        String errmsg = "Internal Error, could not begin transaction.";
        throw new BpelEngineException(errmsg, ex);
    }
    boolean success = false;
    try {
        T retval = transaction.call();
        success = (txManager.getStatus() != Status.STATUS_MARKED_ROLLBACK);
        return retval;
    } catch (Exception ex) {
        throw ex;
    } finally {
        if (success)
            try {
                txManager.commit();
            } catch (Exception ex) {
                __log.error("Commit failed.", ex);
                throw new BpelEngineException("Commit failed.", ex);
            }
        else
            try {
                txManager.rollback();
            } catch (Exception ex) {
                __log.error("Transaction rollback failed.", ex);
            }
    }
}

From source file:com.linkedin.helix.TestHelper.java

public static <T> Map<String, T> startThreadsConcurrently(final List<Callable<T>> methods, final long timeout) {
    final int nrThreads = methods.size();
    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch finishCounter = new CountDownLatch(nrThreads);
    final Map<String, T> resultsMap = new ConcurrentHashMap<String, T>();
    final List<Thread> threadList = new ArrayList<Thread>();

    for (int i = 0; i < nrThreads; i++) {
        final Callable<T> method = methods.get(i);

        Thread thread = new Thread() {
            @Override/* w ww.j  a v  a2  s .  c om*/
            public void run() {
                try {
                    boolean isTimeout = !startLatch.await(timeout, TimeUnit.SECONDS);
                    if (isTimeout) {
                        LOG.error("Timeout while waiting for start latch");
                    }
                } catch (InterruptedException ex) {
                    LOG.error("Interrupted while waiting for start latch");
                }

                try {
                    T result = method.call();
                    if (result != null) {
                        resultsMap.put("thread_" + this.getId(), result);
                    }
                    LOG.debug("result=" + result);
                } catch (Exception e) {
                    LOG.error("Exeption in executing " + method.getClass().getName(), e);
                }

                finishCounter.countDown();
            }
        };
        threadList.add(thread);
        thread.start();
    }
    startLatch.countDown();

    // wait for all thread to complete
    try {
        boolean isTimeout = !finishCounter.await(timeout, TimeUnit.SECONDS);
        if (isTimeout) {
            LOG.error("Timeout while waiting for finish latch. Interrupt all threads");
            for (Thread thread : threadList) {
                thread.interrupt();
            }
        }
    } catch (InterruptedException e) {
        LOG.error("Interrupted while waiting for finish latch", e);
    }

    return resultsMap;
}