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:de.cuseb.bilderbuch.images.ImageSearchService.java

public ImageResponse searchImages(final String query) {

    final ImageResponse response = new ImageResponse();
    final ListeningExecutorService executor = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(searches.size()));

    for (final ImageSearch search : searches.values()) {

        if (!search.isEnabled()) {
            continue;
        }//from w w w .j a v  a 2  s . c  o m

        ListenableFuture<List<Image>> searchResult = executor.submit(new Callable<List<Image>>() {
            @Override
            public List<Image> call() throws Exception {
                log.debug("starting enabled search " + search.getClass().getSimpleName());
                return search.searchImages(query);
            }
        });

        Futures.addCallback(searchResult, new FutureCallback<List<Image>>() {
            @Override
            public void onSuccess(List<Image> result) {
                log.debug(search.getClass().getSimpleName() + " result size: " + result.size());
                response.addImages(result);
            }

            @Override
            public void onFailure(Throwable t) {
                log.error(search.getClass().getSimpleName(), t);
            }
        });
    }

    try {
        executor.shutdown();
        executor.awaitTermination(timeout, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        log.error("awaitTermination interrupted", e);
    }

    if (shuffle) {
        log.debug("shuffling result");
        response.shuffle();
    }

    return response;
}

From source file:at.beris.virtualfile.client.ftp.FtpClient.java

@Override
public void deleteFile(final String path) throws IOException {
    LOGGER.debug("deleteFile (path : {})", path);
    executionHandler(new Callable<Void>() {
        @Override/*  w  w  w . j  a  v  a  2 s  .  c  o  m*/
        public Void call() throws Exception {
            int replyCode = ftpClient.dele(path);
            String replyText = ftpClient.getReplyString();
            if (!FTPReply.isPositiveCompletion(replyCode))
                LOGGER.warn("Unexpected Reply (Code: {}, Text: '{}'", replyCode, replyText);
            return null;
        }
    });
}

From source file:com.glaf.core.cache.CacheFactory.java

public static String getString(final String key) {
    boolean waitFor = true;
    Callable<String> task = new Callable<String>() {
        @Override//from   w  w  w .  jav  a  2 s.  c  om
        public String call() throws Exception {
            try {
                Cache cache = getCache();
                if (cache != null) {
                    String cacheKey = Environment.getCurrentSystemName() + "_" + CACHE_PREFIX + key;
                    if (SystemProperties.getDeploymentSystemName() != null) {
                        cacheKey = SystemProperties.getDeploymentSystemName() + "_"
                                + Environment.getCurrentSystemName() + "_" + CACHE_PREFIX + key;
                    }
                    cacheKey = DigestUtils.md5Hex(cacheKey.getBytes());
                    Object value = cache.get(cacheKey);
                    if (value != null) {
                        logger.debug("get object'" + key + "' from cache.");
                        return value.toString();
                    }
                }
            } catch (Exception ex) {
                if (logger.isDebugEnabled()) {
                    ex.printStackTrace();
                    logger.debug(ex);
                }
            }
            return null;
        }
    };

    try {
        Future<String> result = pool.submit(task);
        long start = System.currentTimeMillis();
        // ?
        if (waitFor) {
            while (true) {
                if (System.currentTimeMillis() - start > 2000) {
                    break;
                }
                if (result.isDone()) {
                    return result.get();
                }
            }
        }
    } catch (Exception e) {
        logger.error(e);
    }

    return null;
}

From source file:net.eusashead.hateoas.conditional.interceptor.AsyncTestController.java

@RequestMapping(method = RequestMethod.POST)
public Callable<ResponseEntity<Void>> post() {
    return new Callable<ResponseEntity<Void>>() {

        @Override/*from  w  w  w .  j  a va  2s .c  o  m*/
        public ResponseEntity<Void> call() throws Exception {
            return new ResponseEntity<Void>(HttpStatus.CREATED);
        }
    };
}

From source file:com.parse.CacheQueryController.java

/**
 * Retrieves the results of the last time {@link ParseQuery#find()} was called on a query
 * identical to this one./*from ww w  . j ava2 s  .co m*/
 *
 * @param sessionToken The user requesting access.
 * @return A list of {@link ParseObject}s corresponding to this query. Returns null if there is no
 *          cache for this query.
 */
private <T extends ParseObject> Task<List<T>> findFromCacheAsync(final ParseQuery.State<T> state,
        String sessionToken) {
    final String cacheKey = ParseRESTQueryCommand.findCommand(state, sessionToken).getCacheKey();
    return Task.call(new Callable<List<T>>() {
        @Override
        public List<T> call() throws Exception {
            JSONObject cached = ParseKeyValueCache.jsonFromKeyValueCache(cacheKey, state.maxCacheAge());
            if (cached == null) {
                throw new ParseException(ParseException.CACHE_MISS, "results not cached");
            }
            try {
                return networkController.convertFindResponse(state, cached);
            } catch (JSONException e) {
                throw new ParseException(ParseException.CACHE_MISS, "the cache contains corrupted json");
            }
        }
    }, Task.BACKGROUND_EXECUTOR);
}

From source file:SingleThreadRequestExecutor.java

@Override
public <T> Future<T> submit(final Callable<T> task) {
    return executor.submit(new Callable<T>() {
        @Override//from   ww w . ja va2 s  .c o m
        public T call() throws Exception {
            try {
                return task.call();
            } catch (Throwable e) {
                // This normally bad code of catch on Exception is here for a *reason*.
                // Future *eats* all exceptions *silently*. This clause at least allows
                // the exception to emit noise for debugging. This is particularly pernicious
                // if you have something like a NullPointerException

                e.printStackTrace();
                throw new RuntimeException(e);
            }

        }
    });
}

From source file:com.mrfeinberg.translation.AbstractTranslationService.java

public Runnable translate(final String phrase, final LanguagePair lp, final TranslationListener listener) {
    final Language b = lp.b();

    final HttpClient httpClient = new HttpClient();
    if (proxyPrefs.getUseProxy()) {
        httpClient.getHostConfiguration().setProxy(proxyPrefs.getProxyHost(), proxyPrefs.getProxyPort());
    }/*from  ww w  .  j av a  2  s . c o m*/

    final HttpMethod httpMethod = getHttpMethod(phrase, lp);
    final Callable<String> callable = new Callable<String>() {
        public String call() throws Exception {
            int result = httpClient.executeMethod(httpMethod);
            if (result != 200) {
                throw new Exception("Got " + result + " status for " + httpMethod.getURI());
            }
            final BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpMethod.getResponseBodyAsStream(), "utf8"));
            try {
                final StringBuilder sb = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null)
                    sb.append(line);
                return sb.toString();
            } finally {
                in.close();
                httpMethod.releaseConnection();
            }
        }
    };
    final FutureTask<String> tc = new FutureTask<String>(callable);
    return new Runnable() {
        public void run() {
            try {
                executor.execute(tc);
                final String result = tc.get(timeout, TimeUnit.MILLISECONDS);
                String found = findTranslatedText(result);
                if (found == null) {
                    listener.error("Cannot find translated text in result.");
                } else {
                    found = found.replaceAll("\\s+", " ");
                    listener.result(found, b);
                }
            } catch (final TimeoutException e) {
                listener.timedOut();
            } catch (final InterruptedException e) {
                listener.cancelled();
            } catch (final Exception e) {
                e.printStackTrace();
                listener.error(e.toString());
            }
        }
    };
}

From source file:com.microsoft.windowsazure.management.RoleSizeOperationsImpl.java

/**
* The List Role Sizes operation lists all of the role sizes that are valid
* for your subscription./*from   www.  j  av  a 2  s  .  c  o  m*/
*
* @return The List Role Sizes operation response.
*/
@Override
public Future<RoleSizeListResponse> listAsync() {
    return this.getClient().getExecutorService().submit(new Callable<RoleSizeListResponse>() {
        @Override
        public RoleSizeListResponse call() throws Exception {
            return list();
        }
    });
}

From source file:apiserver.services.images.controllers.MetadataController.java

/**
 * get embedded metadata/*ww w .j  ava 2s. c o m*/
 * @param documentId
 * @return   height,width
 */
@ApiOperation(value = "Get the embedded metadata", responseClass = "java.util.Map")
@RequestMapping(value = "/info/{documentId}/metadata", method = { RequestMethod.GET })
public WebAsyncTask<Map> imageMetadataByImage(
        @ApiParam(name = "documentId", required = true, defaultValue = "8D981024-A297-4169-8603-E503CC38EEDA") @PathVariable(value = "documentId") String documentId) {
    final String _documentId = documentId;

    Callable<Map> callable = new Callable<Map>() {
        @Override
        public Map call() throws Exception {
            FileMetadataJob args = new FileMetadataJob();
            args.setDocumentId(_documentId);

            Future<Map> imageFuture = imageMetadataGateway.getMetadata(args);
            FileMetadataJob payload = (FileMetadataJob) imageFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

            return payload.getMetadata();
        }
    };

    return new WebAsyncTask<Map>(defaultTimeout, callable);
}

From source file:org.apache.camel.component.http4.HttpConcurrentTest.java

private void doSendMessages(int files, int poolSize) throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    // we access the responses Map below only inside the main thread,
    // so no need for a thread-safe Map implementation
    Map<Integer, Future<String>> responses = new HashMap<Integer, Future<String>>();
    for (int i = 0; i < files; i++) {
        final int index = i;
        Future<String> out = executor.submit(new Callable<String>() {
            public String call() throws Exception {
                return template.requestBody("http4://" + getHostName() + ":" + getPort(), null, String.class);
            }//from  w  ww.ja v  a  2s.  c o m
        });
        responses.put(index, out);
    }

    assertEquals(files, responses.size());

    // get all responses
    Set<String> unique = new HashSet<String>();
    for (Future<String> future : responses.values()) {
        unique.add(future.get());
    }

    // should be 'files' unique responses
    assertEquals("Should be " + files + " unique responses", files, unique.size());
    executor.shutdownNow();
}