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.msopentech.odatajclient.engine.communication.request.streamed.ODataStreamedRequestImpl.java

/**
 * {@inheritDoc }// w w  w. j a  v  a  2 s. c o  m
 */
@Override
@SuppressWarnings("unchecked")
public T execute() {
    streamManager = getStreamManager();

    ((HttpEntityEnclosingRequestBase) request)
            .setEntity(new InputStreamEntity(streamManager.getBody(), -65000));

    futureWrapper.setWrapped(Configuration.getExecutor().submit(new Callable<HttpResponse>() {

        @Override
        public HttpResponse call() throws Exception {
            return doExecute();
        }
    }));

    // returns the stream manager object
    return (T) streamManager;
}

From source file:it.anyplace.sync.discovery.utils.AddressRanker.java

private void testAndRankAndWait() throws InterruptedException {
    logger.trace("testing and ranking peer addresses");
    List<Future<DeviceAddress>> futures = Lists.newArrayList();
    for (final DeviceAddress deviceAddress : preprocessDeviceAddresses(sourceAddresses)) {
        futures.add(executorService.submit(new Callable<DeviceAddress>() {

            @Override//from   ww w  .ja va  2  s . c o m
            public DeviceAddress call() {
                return testAndRank(deviceAddress);
            }
        }));
    }
    for (Future<DeviceAddress> future : futures) {
        try {
            DeviceAddress deviceAddress = future.get(TCP_CONNECTION_TIMEOUT * 2, TimeUnit.MILLISECONDS);
            if (deviceAddress != null) {
                targetAddresses.add(deviceAddress);
            }
        } catch (ExecutionException ex) {
            throw new RuntimeException(ex);
        } catch (TimeoutException ex) {
            logger.warn("test address timeout : {}", ex.toString());
        }
    }
    Collections.sort(targetAddresses, Ordering.natural().onResultOf(new Function<DeviceAddress, Comparable>() {
        @Override
        public Comparable apply(DeviceAddress a) {
            return a.getScore();
        }
    }));
}

From source file:io.fabric8.forge.camel.commands.project.helper.CamelCommandsHelper.java

public static Callable<Iterable<ComponentDto>> createComponentDtoValues(final Project project,
        final CamelCatalog camelCatalog, final UISelectOne<String> componentCategoryFilter,
        final boolean excludeComponentsOnClasspath) {
    // use callable so we can live update the filter
    return new Callable<Iterable<ComponentDto>>() {
        @Override//from   ww w  .ja v  a2  s. c o m
        public Iterable<ComponentDto> call() throws Exception {
            String label = componentCategoryFilter != null ? componentCategoryFilter.getValue() : null;
            return new CamelComponentsCompleter(project, camelCatalog, null, excludeComponentsOnClasspath,
                    false, false, false).getValueChoices(label);
        }
    };
}

From source file:com.eucalyptus.util.metrics.ThruputMetrics.java

/**
 * Adds end time for monitored action that was started before and adds its execution
 * time as a new data point.//from   ww  w.  j a va  2 s.c  o  m
 */
public static void endOperation(final MonitoredAction action, final String id, final long endTime) {
    Threads.enqueue(Eucalyptus.class, ThruputMetrics.class, new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            String startKey = operationKey(action, id, true);
            String endKey = operationKey(action, id, false);
            Long startTime = (Long) paritalOperations.get(startKey);
            if (startTime != null) {
                paritalOperations.remove(startKey);
                if (endTime - startTime > 0)
                    addDataPointNoThread(action, endTime - startTime);
            } else {
                paritalOperations.put(endKey, endTime);
            }
            return true;
        }
    });
}

From source file:com.palantir.paxos.PaxosConsensusFastTest.java

@Test
public void loseQuorumDiffToken() throws InterruptedException {
    for (int i = QUORUM_SIZE; i < NUM_POTENTIAL_LEADERS; i++) {
        state.goDown(i);//from ww w.  j  a  v  a  2 s.  c o m
    }
    LeadershipToken t = state.gainLeadership(0);
    state.goDown(QUORUM_SIZE - 1);
    ExecutorService exec = PTExecutors.newSingleThreadExecutor();
    Future<Void> f = exec.submit(new Callable<Void>() {
        @Override
        public Void call() {
            int i = QUORUM_SIZE - 1;
            while (!Thread.currentThread().isInterrupted()) {
                int next = i + 1;
                if (next == NUM_POTENTIAL_LEADERS) {
                    next = QUORUM_SIZE - 1;
                }
                state.goDown(next);
                state.comeUp(i);
                i = next;
            }
            return null;
        }
    });
    // Don't check leadership immediately after gaining it, since quorum might get lost.
    LeadershipToken token2 = state.gainLeadershipWithoutCheckingAfter(0);
    assertTrue("leader can confirm leadership with quorum", t.sameAs(token2));
    f.cancel(true);
    exec.shutdown();
    exec.awaitTermination(10, TimeUnit.SECONDS);
    for (int i = 0; i < NUM_POTENTIAL_LEADERS; i++) {
        state.comeUp(i);
    }
}

From source file:com.microsoft.windowsazure.management.mediaservices.MediaServiceManagementIntegrationTestBase.java

protected static void createManagementClient() throws Exception {
    Configuration config = createConfiguration();
    config.setProperty(ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER,
            new DefaultHttpRequestRetryHandler());
    managementClient = ManagementService.create(config);
    addClient((ServiceClient<?>) managementClient, new Callable<Void>() {
        @Override/*w ww . j  ava2  s  .c  o m*/
        public Void call() throws Exception {
            createManagementClient();
            return null;
        }
    });
}

From source file:com.microsoft.windowsazure.management.sql.RecoverableDatabaseOperationsImpl.java

/**
* Returns information about a recoverable Azure SQL Database.
*
* @param serverName Required. The name of the Azure SQL Database Server on
* which the database was hosted./*from   www . j av  a 2s. c  o m*/
* @param databaseName Required. The name of the recoverable Azure SQL
* Database to be obtained.
* @return Contains the response to the Get Recoverable Database request.
*/
@Override
public Future<RecoverableDatabaseGetResponse> getAsync(final String serverName, final String databaseName) {
    return this.getClient().getExecutorService().submit(new Callable<RecoverableDatabaseGetResponse>() {
        @Override
        public RecoverableDatabaseGetResponse call() throws Exception {
            return get(serverName, databaseName);
        }
    });
}

From source file:com.liferay.portal.search.internal.SearchEngineInitializer.java

protected void doReIndex(int delay) {
    if (IndexWriterHelperUtil.isIndexReadOnly()) {
        return;/*from  w  w w  . j  a v a2 s  . c o  m*/
    }

    if (_log.isInfoEnabled()) {
        _log.info("Reindexing Lucene started");
    }

    if (delay < 0) {
        delay = 0;
    }

    try {
        if (delay > 0) {
            Thread.sleep(Time.SECOND * delay);
        }
    } catch (InterruptedException ie) {
    }

    ExecutorService executorService = _portalExecutorManager
            .getPortalExecutor(SearchEngineInitializer.class.getName());

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    try {
        SearchEngineHelperUtil.removeCompany(_companyId);

        SearchEngineHelperUtil.initialize(_companyId);

        long backgroundTaskId = BackgroundTaskThreadLocal.getBackgroundTaskId();
        List<FutureTask<Void>> futureTasks = new ArrayList<>();
        Set<String> searchEngineIds = new HashSet<>();

        for (Indexer<?> indexer : IndexerRegistryUtil.getIndexers()) {
            String searchEngineId = indexer.getSearchEngineId();

            if (searchEngineIds.add(searchEngineId)) {
                IndexWriterHelperUtil.deleteEntityDocuments(searchEngineId, _companyId, indexer.getClassName(),
                        true);
            }

            FutureTask<Void> futureTask = new FutureTask<>(new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    BackgroundTaskThreadLocal.setBackgroundTaskId(backgroundTaskId);

                    reindex(indexer);

                    return null;
                }

            });

            executorService.submit(futureTask);

            futureTasks.add(futureTask);
        }

        for (FutureTask<Void> futureTask : futureTasks) {
            futureTask.get();
        }

        if (_log.isInfoEnabled()) {
            _log.info("Reindexing Lucene completed in " + (stopWatch.getTime() / Time.SECOND) + " seconds");
        }
    } catch (Exception e) {
        _log.error("Error encountered while reindexing", e);

        if (_log.isInfoEnabled()) {
            _log.info("Reindexing Lucene failed");
        }
    }

    _finished = true;
}

From source file:com.github.tomakehurst.wiremock.ResponseDelayAsynchronousAcceptanceTest.java

private List<Callable<TimedHttpResponse>> getHttpRequestCallables(int requestCount) throws IOException {
    List<Callable<TimedHttpResponse>> requests = new ArrayList<>();
    for (int i = 0; i < requestCount; i++) {
        final Stopwatch stopwatch = Stopwatch.createStarted();
        requests.add(new Callable<TimedHttpResponse>() {
            @Override/*w ww . j  a  v  a  2s. c  o  m*/
            public TimedHttpResponse call() throws Exception {
                CloseableHttpResponse response = HttpClientFactory.createClient(SOCKET_TIMEOUT_MILLISECONDS)
                        .execute(
                                new HttpGet(String.format("http://localhost:%d/delayed", wireMockRule.port())));

                return new TimedHttpResponse(response, stopwatch.stop().elapsed(MILLISECONDS));
            }
        });
    }
    return requests;
}

From source file:net.commerce.zocalo.freechart.ChartGenerator.java

static public File writeMultiStepChartFile(String webDirName, String chartDirName, final int chartSize,
        Date lastTrade, final Claim claim) throws IOException {
    String chartStyle = "p";
    final String market = claim.getName();
    final File existingPngFile = pngFile(webDirName, chartDirName, market, chartStyle);
    if (isFileMoreRecent(lastTrade, existingPngFile)) {
        return existingPngFile;
    }//from  w  ww.j  ava2  s  .  c  o  m

    Callable<Boolean> worker = new Callable<Boolean>() {
        public Boolean call() throws Exception {
            List trades = HibernateUtil.tradeListForJsp(market);
            TimePeriodValuesCollection prices = ChartGenerator.getOpenCloseValues(trades, claim);
            JFreeChart chart = EMPTY_CHART;
            if (prices.getItemCount(0) != 0) {
                chart = multiStepChart(prices);
            }
            try {
                writeChartAsPNG(chartSize, chart, existingPngFile);
                new NewChart(market);
                return true;
            } catch (IOException e) {
                Logger log = Logger.getLogger("trace");
                log.error("Couldn't save updated chart for '" + market + "'.", e);
                return false;
            }
        }
    };
    ChartScheduler sched = ChartScheduler.create(market, worker);
    sched.generateNewChart();
    return existingPngFile;
}