Example usage for java.util.concurrent Callable Callable

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

Introduction

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

Prototype

Callable

Source Link

Usage

From source file:com.appleframework.monitor.service.TaskService.java

@SuppressWarnings("rawtypes")
public FutureTask<CommandResult> runScript(final String script, final Project project) {
    FutureTask<CommandResult> _fuFutureTask = new FutureTask<CommandResult>(new Callable() {
        @Override//from  ww w.  j a  va 2 s  . co  m
        public CommandResult call() throws Exception {
            logger.debug("run mongo script = {}", script);
            CommandResult result = project.fetchMongoTemplate().getDb().doEval(script,
                    new BasicDBObject().append("nolock", true));
            logger.debug("mongo task response {}", result);
            return result;
        }
    });
    executor.submit(_fuFutureTask);
    return _fuFutureTask;
}

From source file:net.bhira.sample.api.controller.DepartmentController.java

/**
 * Fetch all the departments for the given company ID. It will return a light weight version of
 * {@link net.bhira.sample.model.Department} model without the address and contactInfo objects.
 * /*  w ww.  jav a  2  s. co  m*/
 * @param companyId
 *            the ID for {@link net.bhira.sample.model.Company}.
 * @param response
 *            the http response to which the results will be written.
 * @return an array of {@link net.bhira.sample.model.Department} instances as JSON.
 */
@RequestMapping(value = "/department/company/{companyId}", method = RequestMethod.GET)
@ResponseBody
public Callable<String> getDepartmentsByCompany(@PathVariable long companyId, HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            String body = "";
            try {
                LOG.debug("servicing GET department/company/{}", companyId);
                List<Department> list = departmentService.loadByCompany(companyId);
                int count = (list == null) ? 0 : list.size();
                LOG.debug("GET department/company/{} count = {}", companyId, count);
                body = JsonUtil.createGson().toJson(list);
            } catch (Exception ex) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                body = ex.getLocalizedMessage();
                LOG.warn("Error loading department/company/{}. {}", companyId, body);
                LOG.debug("Load error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:com.verigreen.common.command.TEQCommandExecuter.java

private <TCommandParameters extends TEQCommandParameters> List<Callable<Void>> createCallables(
        List<CommandPack<TCommandParameters>> commandPacks) {

    List<Callable<Void>> callables = new ArrayList<>();
    for (final CommandPack<TCommandParameters> pack : commandPacks) {
        callables.add(new Callable<Void>() {

            @Override/*from   w  w  w . j a  v a 2 s . c om*/
            public Void call() throws Exception {

                pack.getCommand().execute(pack.getParameters());

                return null;
            }
        });
    }

    return callables;
}

From source file:net.bhira.sample.api.controller.EmployeeController.java

/**
 * Fetch all the employees for the given company ID. It will return a light weight version of
 * {@link net.bhira.sample.model.Employee} model without the address and contactInfo objects.
 * /*  ww w.j a v  a 2s  .co  m*/
 * @param companyId
 *            the ID for {@link net.bhira.sample.model.Company}.
 * @param response
 *            the http response to which the results will be written.
 * @return an array of {@link net.bhira.sample.model.Employee} instances as JSON.
 */
@RequestMapping(value = "/employee/company/{companyId}", method = RequestMethod.GET)
@ResponseBody
public Callable<String> getEmployeesByCompany(@PathVariable long companyId, HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            String body = "";
            try {
                LOG.debug("servicing GET employee/company/{}", companyId);
                List<Employee> list = employeeService.loadByCompany(companyId);
                int count = (list == null) ? 0 : list.size();
                LOG.debug("GET employee/company/{} count = {}", companyId, count);
                body = JsonUtil.createGson().toJson(list);
            } catch (Exception ex) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                body = ex.getLocalizedMessage();
                LOG.warn("Error loading employee/company/{}. {}", companyId, body);
                LOG.debug("Load error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.SessionDaoImplTest.java

@Test
public void testEmptyQueries() throws Exception {
    this.execute(new Callable<Object>() {
        @Override/*w  ww.  j av  a  2s  .  c  o m*/
        public Object call() {
            final Session session = sessionDao.getSession(1);
            assertNull(session);

            return null;
        }
    });

    this.execute(new Callable<Object>() {
        @Override
        public Object call() {
            final Session session = sessionDao.getSessionByBlackboardId(1);
            assertNull(session);

            return null;
        }
    });

    this.execute(new Callable<Object>() {
        @Override
        public Object call() {
            final Session session = sessionDao.getSession(1);
            final Set<ConferenceUser> sessionChairs = sessionDao.getSessionChairs(session);
            assertNull(sessionChairs);

            return null;
        }
    });

    this.execute(new Callable<Object>() {
        @Override
        public Object call() {
            final Session session = sessionDao.getSession(1);
            final Set<ConferenceUser> sessionNonChairs = sessionDao.getSessionNonChairs(session);
            assertNull(sessionNonChairs);

            return null;
        }
    });
}

From source file:io.undertow.server.handlers.RequestLimitingHandlerTestCase.java

@Test
public void testRateLimitingHandler() throws ExecutionException, InterruptedException {
    latch.countDown();//from  w w  w .j ava 2  s.c o  m
    latch = new CountDownLatch(1);
    ExecutorService executor = Executors.newFixedThreadPool(N_THREADS);
    try {
        final List<Future<?>> futures = new ArrayList<>();
        for (int i = 0; i < N_THREADS; ++i) {
            futures.add(executor.submit(new Callable<String>() {
                @Override
                public String call() {
                    TestHttpClient client = new TestHttpClient();
                    try {
                        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
                        HttpResponse result = client.execute(get);
                        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
                        return HttpClientUtils.readResponse(result);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        client.getConnectionManager().shutdown();
                    }
                }
            }));
        }
        Thread.sleep(300);
        latch.countDown();
        for (Future<?> future : futures) {
            String res = (String) future.get();
            Assert.assertTrue(res, res.equals("1") || res.equals("2"));
        }
    } finally {
        executor.shutdown();
    }

}

From source file:gobblin.compliance.validation.ComplianceValidationJob.java

public void run() throws IOException {
    Preconditions.checkNotNull(this.finder, "Dataset finder class is not set");
    List<Dataset> datasets = this.finder.findDatasets();
    this.finishCleanSignal = Optional.of(new CountDownLatch(datasets.size()));
    for (final Dataset dataset : datasets) {
        ListenableFuture<Void> future = this.service.submit(new Callable<Void>() {
            @Override//  w  ww .j a va  2 s .c  o  m
            public Void call() throws Exception {
                if (dataset instanceof ValidatableDataset) {
                    ((ValidatableDataset) dataset).validate();
                } else {
                    log.warn("Not an instance of " + ValidatableDataset.class + " Dataset won't be validated "
                            + dataset.datasetURN());
                }
                return null;
            }
        });
        Futures.addCallback(future, new FutureCallback<Void>() {
            @Override
            public void onSuccess(@Nullable Void result) {
                ComplianceValidationJob.this.finishCleanSignal.get().countDown();
                log.info("Successfully validated: " + dataset.datasetURN());
            }

            @Override
            public void onFailure(Throwable t) {
                ComplianceValidationJob.this.finishCleanSignal.get().countDown();
                log.warn("Exception caught when validating " + dataset.datasetURN() + ".", t);
                ComplianceValidationJob.this.throwables.add(t);
                ComplianceValidationJob.this.eventSubmitter.submit(
                        ComplianceEvents.Validation.FAILED_EVENT_NAME,
                        ImmutableMap.of(ComplianceEvents.FAILURE_CONTEXT_METADATA_KEY,
                                ExceptionUtils.getFullStackTrace(t), ComplianceEvents.DATASET_URN_METADATA_KEY,
                                dataset.datasetURN()));
            }
        });
    }
}

From source file:com.topekalabs.synchronization.LockTest.java

private void testWithContentionHelper(int numThreads, ExecutorService es) {
    final long timeout = 4000;
    final int numIncs = 500;
    final int expectedIncs = numIncs * numThreads;

    final MutableInt a = new MutableInt();
    final MutableInt b = new MutableInt();
    final Lock lock;

    try {//from   w  w w  .  j a v a 2  s  .  c  o  m
        lock = lockClass.newInstance();
    } catch (InstantiationException | IllegalAccessException ex) {
        throw new RuntimeException(ex);
    }

    Callable<Integer> callable = new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            for (int incCount = 0; incCount < numIncs; incCount++) {
                lock.lock();
                int tempB = b.intValue();
                a.increment();
                Thread.sleep(1);
                a.add(b.intValue() - tempB);
                b.increment();
                lock.unlock();
            }

            return 1;
        }
    };

    List<Callable<Integer>> callables = CollectionUtils.fillEmptyCollection(new ArrayList<Callable<Integer>>(),
            callable, numThreads);

    try {
        List<Future<Integer>> futures = es.invokeAll(callables);
        ThreadUtils.done(futures, timeout, TimeUnit.MINUTES);
    } catch (InterruptedException | TimeoutException | ExecutionException ex) {
        ErrorThrower.kill(ex);
    }

    Assert.assertEquals("Incorrect number of increments.", expectedIncs, a.intValue());
    Assert.assertEquals("Incorrect number of increments.", expectedIncs, b.intValue());
}

From source file:com.microsoft.windowsazure.management.servicebus.RelayOperationsImpl.java

/**
* Gets the set of connection strings for a relay.
*
* @param namespaceName Required. The namespace name.
* @param relayName Required. The relay name.
* @return The set of connection details for a service bus entity.
*///  w ww.  j a  v a 2 s . c o m
@Override
public Future<ServiceBusConnectionDetailsResponse> getConnectionDetailsAsync(final String namespaceName,
        final String relayName) {
    return this.getClient().getExecutorService().submit(new Callable<ServiceBusConnectionDetailsResponse>() {
        @Override
        public ServiceBusConnectionDetailsResponse call() throws Exception {
            return getConnectionDetails(namespaceName, relayName);
        }
    });
}