Example usage for java.util.concurrent Future get

List of usage examples for java.util.concurrent Future get

Introduction

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

Prototype

V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;

Source Link

Document

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

Usage

From source file:com.agileEAP.module.cache.memcached.SpyMemcachedClient.java

/**
 * Delete, ??updateTimeout, ?false??.//from w ww.  j  ava 2 s.  c  om
 */
public boolean safeDelete(String key) {
    Future<Boolean> future = memcachedClient.delete(key);
    try {
        return future.get(updateTimeout, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        future.cancel(false);
    }
    return false;
}

From source file:apiserver.services.images.controllers.info.SizeController.java

/**
 * get basic info about image.// ww w .  jav  a 2 s.c o  m
 *
 * @param documentId cache id
 * @return height, width, pixel size, transparency
 * , @RequestPart("meta-data") Object metadata
 * <p/>
 * , @RequestParam MultipartFile file
 */
@ApiOperation(value = "Get the height and width for the image", response = Map.class)
@RequestMapping(value = "/info/{documentId}/size", method = { RequestMethod.GET })
public WebAsyncTask<ResponseEntity<Map>> imageInfoByImageAsync(
        @ApiParam(name = "documentId", required = true, defaultValue = "8D981024-A297-4169-8603-E503CC38EEDA") @PathVariable(value = "documentId") String documentId)
        throws ExecutionException, TimeoutException, InterruptedException {
    final String _documentId = documentId;

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

            Future<Map> imageFuture = gateway.imageSize(args);
            Map payload = imageFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            ResponseEntity<Map> result = new ResponseEntity<Map>(payload, headers, HttpStatus.OK);
            return result;
        }
    };

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

From source file:iddb.runtime.cache.impl.CacheImpl.java

@Override
public Object get(String key) {
    synchronized (key) {
        Object obj = null;/*from  w ww  .j a v  a2s  .c  o  m*/
        Future<Object> asGet = client.asyncGet(getNamespace() + "-" + key);
        try {
            obj = asGet.get(10, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            asGet.cancel(false);
            log.error(e.getMessage());
        } catch (InterruptedException e) {
            log.error(e.getMessage());
        } catch (ExecutionException e) {
            log.error(e.getMessage());
        }
        return obj;
    }
}

From source file:com.yahoo.yqlplus.engine.tools.YQLPlusRun.java

@SuppressWarnings("unchecked")
public int run(CommandLine command) throws Exception {
    String script = null;/*from w  w w  .ja  va2s  .  c o  m*/
    String filename = null;
    if (command.hasOption("command")) {
        script = command.getOptionValue("command");
        filename = "<command line>";
    }
    List<String> scriptAndArgs = (List<String>) command.getArgList();
    if (filename == null && scriptAndArgs.size() < 1) {
        System.err.println("No script specified.");
        return -1;
    } else if (script == null) {
        filename = scriptAndArgs.get(0);
        Path scriptPath = Paths.get(filename);
        if (!Files.isRegularFile(scriptPath)) {
            System.err.println(scriptPath + " is not a file.");
            return -1;
        }
        script = Charsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(scriptPath))).toString();
    }
    List<String> paths = Lists.newArrayList();
    if (command.hasOption("path")) {
        paths.addAll(Arrays.asList(command.getOptionValues("path")));
    }
    // TODO: this isn't going to be very interesting without some sources
    Injector injector = Guice.createInjector(new JavaEngineModule());
    YQLPlusCompiler compiler = injector.getInstance(YQLPlusCompiler.class);
    CompiledProgram program = compiler.compile(script);
    if (command.hasOption("source")) {
        program.dump(System.out);
        return 0;
    }
    // TODO: read command line arguments to pass to program
    ExecutorService outputThreads = Executors.newSingleThreadExecutor();
    ProgramResult result = program.run(Maps.<String, Object>newHashMap(), true);
    for (String name : result.getResultNames()) {
        final ListenableFuture<YQLResultSet> future = result.getResult(name);
        future.addListener(new Runnable() {
            @Override
            public void run() {
                try {
                    YQLResultSet resultSet = future.get();
                    System.out.println(new String((byte[]) resultSet.getResult()));
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }

            }
        }, outputThreads);
    }
    Future<TraceRequest> done = result.getEnd();
    try {
        done.get(10000L, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ExecutionException | TimeoutException e) {
        e.printStackTrace();
    }
    outputThreads.awaitTermination(1L, TimeUnit.SECONDS);
    return 0;
}

From source file:apiserver.services.pdf.service.GetPdfInfoCFService.java

public Object execute(Message<?> message) throws ColdFusionException {
    PdfGetInfoResult props = (PdfGetInfoResult) message.getPayload();

    try {//from  w  w  w . j  av  a  2s  . com
        long startTime = System.nanoTime();
        Grid grid = verifyGridConnection();

        // Get grid-enabled executor service for nodes where attribute 'worker' is defined.
        ExecutorService exec = getColdFusionExecutor();

        Future<MapResult> future = exec
                .submit(new GetInfoCallable(props.getFile().getFileBytes(), props.getOptions()));

        MapResult _result = future.get(defaultTimeout, TimeUnit.SECONDS);
        props.setResult(_result.getData());

        long endTime = System.nanoTime();
        log.debug("execution times: CF=" + _result.getStats().getExecutionTime() + "ms -- total="
                + (endTime - startTime) + "ms");

        return props;
    } catch (Exception ge) {
        throw new RuntimeException(ge);
    }
}

From source file:apiserver.services.pdf.service.SetPdfInfoCFService.java

public Object execute(Message<?> message) throws ColdFusionException {
    PdfSetInfoResult props = (PdfSetInfoResult) message.getPayload();

    try {/*from w w  w  . j  a va 2s.c o m*/
        long startTime = System.nanoTime();
        Grid grid = verifyGridConnection();

        // Get grid-enabled executor service for nodes where attribute 'worker' is defined.
        ExecutorService exec = getColdFusionExecutor();

        Future<MapResult> future = exec
                .submit(new SetInfoCallable(props.getFile().getFileBytes(), props.getOptions()));

        MapResult _result = future.get(defaultTimeout, TimeUnit.SECONDS);
        props.setResult(_result.getData());

        long endTime = System.nanoTime();
        log.debug("execution times: CF=" + _result.getStats().getExecutionTime() + "ms -- total="
                + (endTime - startTime) + "ms");

        return props;
    } catch (Exception ge) {
        throw new RuntimeException(ge);
    }
}

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

/**
 * get embedded metadata//from w  ww  .j  a v  a  2  s  .  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:apiserver.services.images.controllers.MetadataController.java

/**
 * get embedded metadata/*w  w  w . ja v  a  2s . c om*/
 * @param file uploaded image
 * @return   height,width
 */
@ApiOperation(value = "Get the embedded metadata", responseClass = "java.util.Map")
@RequestMapping(value = "/info/metadata", method = { RequestMethod.POST })
public WebAsyncTask<Map> imageMetadataByImage(
        @ApiParam(name = "file", required = true) @RequestParam(value = "file", required = true) MultipartFile file) {
    final MultipartFile _file = file;

    Callable<Map> callable = new Callable<Map>() {
        @Override
        public Map call() throws Exception {
            FileMetadataJob job = new FileMetadataJob();
            job.setDocumentId(null);
            job.setDocument(new Document(_file));
            job.getDocument().setContentType(MimeType.getMimeType(_file.getContentType()));
            job.getDocument().setFileName(_file.getOriginalFilename());

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

            return payload.getMetadata();
        }
    };

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

From source file:com.agileEAP.module.cache.memcached.SpyMemcachedClient.java

/**
 * Set, ??updateTimeout, ?false??.//from w w w. j  av  a 2  s  .c o  m
 */
public boolean safeSet(String key, int expiration, Object value) {
    Future<Boolean> future = memcachedClient.set(key, expiration, value);
    try {
        return future.get(updateTimeout, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        future.cancel(false);
    }
    return false;
}

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

/**
 * get embedded metadata/*from   w w w  . j a va2  s . com*/
 *
 * @param file uploaded image
 * @return height, width
 */
@ApiOperation(value = "Get the embedded metadata", response = Map.class)
@RequestMapping(value = "/info/metadata", method = { RequestMethod.POST })
public ResponseEntity<Map> imageMetadataByImage(HttpServletRequest request, HttpServletResponse response,
        @ApiParam(name = "file", required = true) @RequestParam(value = "file", required = true) MultipartFile file)
        throws ExecutionException, InterruptedException, TimeoutException, IOException {
    Document _file = null;

    MultipartFile _mFile = fileUploadHelper.getFileFromRequest(file, request);
    _file = new Document(_mFile);
    if (!_file.getContentType().isSupportedImage()) {
        return new ResponseEntity<>(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
    }

    FileMetadataJob job = new FileMetadataJob();
    job.setDocumentId(null);
    job.setDocument(_file);

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

    return new ResponseEntity<>(payload.getMetadata(), HttpStatus.OK);

}