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.tangrainc.inappbilling.InAppBillingHelper.java

public ListenableFuture<JSONObject[]> getProducts() {
    return _executor.submit(new Callable<JSONObject[]>() {
        @Override/*from w w w .j  a  va 2  s.  co  m*/
        public JSONObject[] call() throws Exception {
            // Wait for the service to be initialized (if call too soon after constructor)
            int loop = 0;
            while (_service == null || loop < 20) {
                Thread.sleep(500);
                loop++;
            }
            if (_service == null) {
                throw new Exception(
                        "Billing service could not be connected for 10 secs! May be running on an emulator w/o Google Service?");
            }

            Bundle queryProducts = new Bundle();
            queryProducts.putStringArrayList("ITEM_ID_LIST",
                    new ArrayList<>(Arrays.asList(_productIdentifiers)));

            Bundle productDetails = _service.getSkuDetails(3, _context.getPackageName(), "inapp",
                    queryProducts);
            ArrayList<JSONObject> result = new ArrayList<>();

            int response = productDetails.getInt("RESPONSE_CODE");
            if (response == 0) {
                ArrayList<String> responseList = productDetails.getStringArrayList("DETAILS_LIST");

                for (String thisResponse : responseList) {
                    result.add(new JSONObject(thisResponse));
                }

                return result.toArray(new JSONObject[0]);
            } else {
                throw new Exception("Response from service: " + response);
            }
        }
    });
}

From source file:de.unentscheidbar.validation.swing.trigger.FocusLossTriggerTest.java

@Override
protected void doNotProvokeTrigger(Iterable<JComponent> components) {

    for (final JComponent c : components) {
        runInEdt(new Callable<Void>() {

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

                if (c instanceof JTextComponent) {
                    ((JTextComponent) c).setText(RandomStringUtils.randomAlphanumeric(rnd.nextInt(16)));
                } else {
                    c.setToolTipText(RandomStringUtils.randomAlphanumeric(rnd.nextInt(16)));
                }
                return null;
            }
        });
    }
    drainEventQueue();
}

From source file:net.eusashead.hateoas.response.argumentresolver.AsyncEntityController.java

@RequestMapping(method = RequestMethod.POST)
public Callable<ResponseEntity<Void>> post(@RequestBody final Entity entity,
        final PostResponseBuilder builder) {

    return new Callable<ResponseEntity<Void>>() {

        @Override//from w  ww. j a v a 2  s.  co m
        public ResponseEntity<Void> call() throws Exception {
            Entity created = service.save(entity);
            return builder.location("/path/to/{name}", created.getName()).build();
        }
    };
}

From source file:com.amazon.s3.S3ParserTest.java

@Test
void testAmazonParseListAllMyBucketsParallelResponseTime() throws InterruptedException, ExecutionException {
    CompletionService<Boolean> completer = new ExecutorCompletionService<Boolean>(exec);

    for (int i = 0; i < LOOP_COUNT; i++)
        completer.submit(new Callable<Boolean>() {
            public Boolean call() throws IOException {
                runAmazonParseListAllMyBuckets();
                return true;
            }/* w  w w  .  j a  v a  2  s  .  c  om*/
        });
    for (int i = 0; i < LOOP_COUNT; i++)
        assert completer.take().get();
}

From source file:nl.waisda.services.EuropeanaImportServiceTest.java

private void setup() {
    // NOTE: the rollback config is not needed as the service runs in a new transaction and therefor
    // is never rolled back unless an error occurs within the process
    transactionService.runInNewTransaction(new Callable<Void>() {
        @Override// www  .j  a v a2  s. com
        public Void call() throws Exception {
            Query query = entityManager.createQuery("delete from Video");
            query.executeUpdate();

            return null;
        }
    });
}

From source file:com.atomicleopard.thundr.ftp.FtpSession.java

public boolean changeWorkingDirectory(final String directory) {
    return timeLogAndCatch("Change working directory", new Callable<Boolean>() {
        @Override// w w  w .ja va  2 s. c  om
        public Boolean call() throws Exception {
            return preparedClient.changeWorkingDirectory(directory);
        }
    });
}

From source file:com.alibaba.cobar.client.support.execution.DefaultConcurrentRequestProcessor.java

public List<Object> process(List<ConcurrentRequest> requests) {
    List<Object> resultList = new ArrayList<Object>();

    if (CollectionUtils.isEmpty(requests))
        return resultList;

    List<RequestDepository> requestsDepo = fetchConnectionsAndDepositForLaterUse(requests);
    final CountDownLatch latch = new CountDownLatch(requestsDepo.size());
    List<Future<Object>> futures = new ArrayList<Future<Object>>();
    try {/* w w  w . ja va  2s. co  m*/

        for (RequestDepository rdepo : requestsDepo) {
            ConcurrentRequest request = rdepo.getOriginalRequest();
            final SqlMapClientCallback action = request.getAction();
            final Connection connection = rdepo.getConnectionToUse();

            futures.add(request.getExecutor().submit(new Callable<Object>() {
                public Object call() throws Exception {
                    try {
                        return executeWith(connection, action);
                    } finally {
                        latch.countDown();
                    }
                }
            }));
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new ConcurrencyFailureException(
                    "interrupted when processing data access request in concurrency", e);
        }

    } finally {
        for (RequestDepository depo : requestsDepo) {
            Connection springCon = depo.getConnectionToUse();
            DataSource dataSource = depo.getOriginalRequest().getDataSource();
            try {
                if (springCon != null) {
                    if (depo.isTransactionAware()) {
                        springCon.close();
                    } else {
                        DataSourceUtils.doReleaseConnection(springCon, dataSource);
                    }
                }
            } catch (Throwable ex) {
                logger.info("Could not close JDBC Connection", ex);
            }
        }
    }

    fillResultListWithFutureResults(futures, resultList);

    return resultList;
}

From source file:io.neba.core.resourcemodels.caching.RequestScopedResourceModelCacheTest.java

@Test
public void testLookupOfModel() throws Exception {
    request(new Callable<Object>() {
        @Override//from   www.  j a  v  a  2 s .c o  m
        public Object call() throws Exception {
            withResourcePath("/junit/test/1");

            lookupModelFromCache();
            assertModelIsNotInCache();
            putModelInCache();

            lookupModelFromCache();
            assertModelWasFoundInCache();
            return null;
        }
    });
}

From source file:com.facebook.stats.mx.TestStats.java

/**
 * Test the setAttribute(String, Callable <String> ) function
 *///from  ww w.j av a2s  .c om
@Test(groups = "fast")
public void testAttributeCallable() {
    for (final String key : attributeMap.keySet()) {
        stats.setAttribute(key, new Callable<String>() {
            @Override
            public String call() throws Exception {
                return TestStats.this.attributeMap.get(key);
            }
        });
    }

    verifyStatAttributes();
}