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:apiserver.services.cache.controllers.CacheDocumentController.java

/**
 *  delete an document from cache//  w  w  w.ja  v  a2s .  com
 *
 * @param documentId id of document in the persistence/cache layer
 * @return TRUE if the item was deleted successfully
 */
@ApiOperation(value = "delete an document from cache")
@RequestMapping(value = "/{documentId}", method = { RequestMethod.DELETE })
public WebAsyncTask<Boolean> deleteDocument(
        @ApiParam(name = "documentId", required = true) @PathVariable(value = "documentId") String documentId) {
    final String _documentId = documentId;

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

            try {
                Future<DocumentJob> imageFuture = documentDeleteGateway.deleteDocument(args);
                DocumentJob payload = imageFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

                return (payload != null);
            } catch (Exception ex) {
                return Boolean.FALSE;
            }
        }
    };

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

From source file:apiserver.services.images.controllers.filters.OilController.java

/**
 * This filter replaces each pixel by the median of the input pixel and its eight neighbours. Each of the RGB channels is considered separately.
 *
 * @param file/*from   www  .  j ava  2  s  .  c  o m*/
 * @param level
 * @param range
 * @param format
 * @return
 * @throws java.util.concurrent.TimeoutException
 * @throws java.util.concurrent.ExecutionException
 * @throws InterruptedException
 * @throws java.io.IOException
 */
@ApiOperation(value = "This filter produces an oil painting effect as described in the book \"Beyond Photography - The Digital Darkroom\". You can specify the smearing radius. It's quite a slow filter especially with a large radius.")
@RequestMapping(value = "/filter/oil", method = { RequestMethod.POST })
@ResponseBody
public ResponseEntity<byte[]> imageOilBlurByFile(HttpServletRequest request, HttpServletResponse response,
        @ApiParam(name = "file", required = false) @RequestParam(value = "file", required = false) MultipartFile file,
        @ApiParam(name = "level", required = true, defaultValue = "3") @RequestParam(value = "angle", required = false, defaultValue = "3") int level,
        @ApiParam(name = "range", required = true, defaultValue = "256") @RequestParam(value = "range", required = false, defaultValue = "256") int range,
        @ApiParam(name = "format", required = false) @RequestParam(value = "format", required = false) String format

) throws TimeoutException, ExecutionException, InterruptedException, IOException {
    Document _file = null;
    MimeType _outputMimeType = null;
    String _outputContentType = null;

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

    OilJob job = new OilJob();
    job.setDocumentId(null);
    job.setDocument(new Document(file));
    job.setLevels(level);
    job.setRange(range);

    Future<Map> imageFuture = imageFilterOilGateway.imageOilFilter(job);
    ImageDocumentJob payload = (ImageDocumentJob) imageFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

    ResponseEntity<byte[]> result = ResponseEntityHelper.processImage(payload.getBufferedImage(),
            _outputContentType, false);
    return result;
}

From source file:com.naver.template.social.TwitterBO.java

public List<TwitterProfile> getFriendListParallel(String userId) {
    // get chunked id list
    CursoredList<Long> friendIdList = getFriendIdList(userId);
    List<List<Long>> chunkedList = ChunkUtils.chunk(friendIdList, 100);

    Twitter twitter = getTwitterConnection(userId);

    List<Future<List<TwitterProfile>>> futureList = new ArrayList<Future<List<TwitterProfile>>>();

    // call parallel
    for (List<Long> eachList : chunkedList) {
        Long[] array = eachList.toArray(new Long[0]);
        long[] ids = ArrayUtils.toPrimitive(array);
        futureList.add(pool.submit(new TwitterFriendsCallable(twitter, ids)));
    }/*from w w  w.j  a  va 2s  .c o  m*/

    // async get result and merge
    List<TwitterProfile> twitterFriends = new ArrayList<TwitterProfile>();
    for (Future<List<TwitterProfile>> future : futureList) {
        List<TwitterProfile> resultList = null;
        try {
            resultList = future.get(3000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            //
        } catch (ExecutionException e) {
            //
        } catch (TimeoutException e) {
            //
        }

        if (CollectionUtils.isNotEmpty(resultList)) {
            twitterFriends.addAll(resultList);
        }
    }

    return twitterFriends;
}

From source file:apiserver.services.images.controllers.filters.LensBlurController.java

/**
 * This filter simulates the blurring caused by a camera lens. You can change the aperture size and shape and also specify blooming of the uploaded image. This filter is very slow.
 *
 * @param documentId/*from  w w  w .  ja  va 2s.  com*/
 * @param radius
 * @param sides
 * @param bloom
 * @return
 * @throws java.util.concurrent.TimeoutException
 * @throws java.util.concurrent.ExecutionException
 * @throws InterruptedException
 * @throws java.io.IOException
 */
@ApiOperation(value = "This filter simulates the blurring caused by a camera lens. You can change the aperture size and shape and also specify blooming of the image. This filter is very slow.")
@RequestMapping(value = "/filter/{documentId}/lensblur.{format}", method = { RequestMethod.GET })
public ResponseEntity<byte[]> imageLensBlurByFile(
        @ApiParam(name = "documentId", required = true, defaultValue = "8D981024-A297-4169-8603-E503CC38EEDA") @PathVariable(value = "documentId") String documentId,
        @ApiParam(name = "radius", required = false, defaultValue = "10") @RequestParam(value = "radius", required = false, defaultValue = "10") float radius,
        @ApiParam(name = "sides", required = false, defaultValue = "5") @RequestParam(value = "sides", required = false, defaultValue = "5") int sides,
        @ApiParam(name = "bloom", required = false, defaultValue = "2") @RequestParam(value = "bloom", required = false, defaultValue = "2") float bloom,
        @ApiParam(name = "format", required = true, defaultValue = "jpg") @PathVariable(value = "format") String format

) throws TimeoutException, ExecutionException, InterruptedException, IOException {
    String _contentType = MimeType.getMimeType(format).contentType;
    if (!MimeType.getMimeType(format).isSupportedImage()) {
        return new ResponseEntity<byte[]>(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
    }

    LensBlurJob args = new LensBlurJob();
    args.setDocumentId(documentId);
    args.setRadius(radius);
    args.setSides(sides);
    args.setBloom(bloom);

    Future<Map> imageFuture = imageFilterLensBlurGateway.imageLensBlurFilter(args);
    ImageDocumentJob payload = (ImageDocumentJob) imageFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

    ResponseEntity<byte[]> result = ResponseEntityHelper.processImage(payload.getBufferedImage(), _contentType,
            false);
    return result;
}

From source file:de.adorsys.jmspojo.JMSJavaFutureAdapterTest.java

@Test
public void testSendAndWaitForReplyWithTimeout()
        throws InterruptedException, ExecutionException, TimeoutException {
    JMSJavaFutureAdapter<PingMessage> jmsServiceMethodInvoker = new JMSJavaFutureAdapter<PingMessage>(
            objectMapper, cf, PingMessage.class, 5000);

    PingMessage data = new PingMessage();
    data.setPing("sampletext");

    Future<PingMessage> future = jmsServiceMethodInvoker.send(testQueue, new HashMap<String, Object>(), data);
    PingMessage message = future.get(1000, TimeUnit.MILLISECONDS);
    Assert.assertNotNull(message);/*from  w  w  w  .  j a v a 2 s  . c  om*/
    Assert.assertEquals(data, message);
}

From source file:apiserver.services.images.controllers.filters.BoxBlurController.java

/**
 * A filter which performs a box blur on an uploaded image. The horizontal and vertical blurs can be specified separately and a number of iterations can be given which allows an approximation to Gaussian blur.
 *
 * @param documentId/*  w w  w .  j ava 2  s  . co  m*/
 * @param hRadius
 * @param vRadius
 * @param iterations
 * @param preMultiplyAlpha
 * @param format
 * @return
 * @throws java.util.concurrent.TimeoutException
 * @throws java.util.concurrent.ExecutionException
 * @throws InterruptedException
 * @throws java.io.IOException
 */
@ApiOperation(value = "A filter which performs a box blur on an image. The horizontal and vertical blurs can be specified separately and a number of iterations can be given which allows an approximation to Gaussian blur.")
@RequestMapping(value = "/filter/{documentId}/boxblur.{format}", method = { RequestMethod.GET })
@ResponseBody
public ResponseEntity<byte[]> imageBoxBlurByFile(
        @ApiParam(name = "documentId", required = true, defaultValue = "8D981024-A297-4169-8603-E503CC38EEDA") @PathVariable(value = "documentId") String documentId,
        @ApiParam(name = "format", required = true, defaultValue = "jpg") @PathVariable(value = "format") String format,
        @ApiParam(name = "hRadius", required = false, defaultValue = "2", value = "the horizontal radius of blur") @RequestParam(value = "hRadius", defaultValue = "2") int hRadius,
        @ApiParam(name = "vRadius", required = false, defaultValue = "2", value = "the vertical radius of blur") @RequestParam(value = "vRadius", defaultValue = "2") int vRadius,
        @ApiParam(name = "iterations", required = false, defaultValue = "1", value = "the number of time to iterate the blur") @RequestParam(value = "iterations", defaultValue = "1") int iterations,
        @ApiParam(name = "preMultiplyAlpha", required = false, defaultValue = "true", allowableValues = "true,false", value = "pre multiply the alpha channel") @RequestParam(value = "preMultiplyAlpha", defaultValue = "true") boolean preMultiplyAlpha

) throws TimeoutException, ExecutionException, InterruptedException, IOException {
    String _contentType = MimeType.getMimeType(format).contentType;
    if (!MimeType.getMimeType(format).isSupportedImage()) {
        return new ResponseEntity<byte[]>(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
    }

    BoxBlurJob args = new BoxBlurJob();
    args.setDocumentId(documentId);
    args.setHRadius(hRadius);
    args.setVRadius(vRadius);
    args.setIterations(iterations);
    args.setPreMultiplyAlpha(preMultiplyAlpha);

    Future<Map> imageFuture = imageFilterBoxBlurGateway.imageBoxBlurFilter(args);
    ImageDocumentJob payload = (ImageDocumentJob) imageFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

    ResponseEntity<byte[]> result = ResponseEntityHelper.processImage(payload.getBufferedImage(), _contentType,
            false);
    return result;
}

From source file:com.digitalpebble.storm.crawler.librato.metrics.LibratoMetricsConsumer.java

private void postPortion(Map<String, Object> chunk) {
    try {/*w  ww.j  a v a  2 s. co m*/
        final String payload = OBJECT_MAPPER.writeValueAsString(chunk);
        final Future<Response> future = httpPoster.post(userAgent, payload);
        final Response response = future.get(timeout, timeoutUnit);
        final int statusCode = response.getStatusCode();
        if (statusCode < 200 || statusCode >= 300) {
            LOG.error("Received an error from Librato API. Code : {}, Message: {}", statusCode,
                    response.getBody());
        }
    } catch (Exception e) {
        LOG.error("Unable to post to Librato API", e);
    }
}

From source file:com.flipkart.poseidon.serviceclients.FutureTaskResultToDomainObjectPromiseWrapper.java

@Override
public DomainObject get(long timeout, TimeUnit timeUnit)
        throws PromiseBrokenException, TimeoutException, InterruptedException {
    try {//from   w  w  w. jav  a 2  s .  c  o  m
        ServiceResponse<DomainObject> serviceResponse = new ServiceResponse<>();
        for (Future<TaskResult> futureResult : futureList) {
            TaskResult result = futureResult.get(timeout, timeUnit);
            if (result == null) {
                throw new PromiseBrokenException("Task result is null");
            }
            ServiceResponse<DomainObject> response = (ServiceResponse<DomainObject>) result.getData();
            if (!response.getIsSuccess())
                throw response.getException();
            serviceResponse.addData(response.getDataList());
        }
        if (responseMerger != null) {
            return responseMerger.mergeResponse(serviceResponse.getDataList());
        } else {
            return serviceResponse.getDataList().get(0);
        }
    } catch (ExecutionException exception) {
        checkAndThrowServiceClientException(exception);
        promiseBrokenException = new PromiseBrokenException(exception);
        throw new InterruptedException(exception.getMessage());
    } catch (CancellationException exception) {
        promiseBrokenException = new PromiseBrokenException(exception);
        throw new PromiseBrokenException(promiseBrokenException);
    }
}

From source file:apiserver.services.images.controllers.filters.LensBlurController.java

/**
 * This filter simulates the blurring caused by a camera lens. You can change the aperture size and shape and also specify blooming of the uploaded image. This filter is very slow.
 *
 * @param file//from  w  ww.  j a  va2s.  c  om
 * @param radius
 * @param sides
 * @param bloom
 * @return
 * @throws java.util.concurrent.TimeoutException
 * @throws java.util.concurrent.ExecutionException
 * @throws InterruptedException
 * @throws java.io.IOException
 */
@ApiOperation(value = "This filter simulates the blurring caused by a camera lens. You can change the aperture size and shape and also specify blooming of the image. This filter is very slow.")
@RequestMapping(value = "/filter/lensblur", method = { RequestMethod.POST })
public ResponseEntity<byte[]> imageLensBlurByFile(HttpServletRequest request, HttpServletResponse response,
        @ApiParam(name = "file", required = false) @RequestParam(value = "file", required = false) MultipartFile file,
        @ApiParam(name = "radius", required = false, defaultValue = "10") @RequestParam(value = "radius", required = false, defaultValue = "10") float radius,
        @ApiParam(name = "sides", required = false, defaultValue = "5") @RequestParam(value = "sides", required = false, defaultValue = "5") int sides,
        @ApiParam(name = "bloom", required = false, defaultValue = "2") @RequestParam(value = "bloom", required = false, defaultValue = "2") float bloom,
        @ApiParam(name = "format", required = false) @RequestParam(value = "format", required = false) String format

) throws TimeoutException, ExecutionException, InterruptedException, IOException {
    Document _file = null;
    MimeType _outputMimeType = null;
    String _outputContentType = null;

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

    LensBlurJob job = new LensBlurJob();
    job.setDocumentId(null);
    job.setDocument(new Document(file));
    job.setRadius(radius);
    job.setSides(sides);
    job.setBloom(bloom);

    Future<Map> imageFuture = imageFilterLensBlurGateway.imageLensBlurFilter(job);
    ImageDocumentJob payload = (ImageDocumentJob) imageFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

    ResponseEntity<byte[]> result = ResponseEntityHelper.processImage(payload.getBufferedImage(),
            _outputContentType, false);
    return result;
}

From source file:apiserver.services.images.controllers.manipulations.TextController.java

/**
 * Overlay text onto an image/* w w  w. jav a 2 s.  com*/
 *
 * @param documentId
 * @param text
 * @param color
 * @param fontSize
 * @param fontStyle
 * @param angle
 * @param x
 * @param y
 * @return
 * @throws InterruptedException
 * @throws java.util.concurrent.ExecutionException
 * @throws java.util.concurrent.TimeoutException
 * @throws java.io.IOException
 */
@RequestMapping(value = "/modify/{documentId}/text.{format}", method = { RequestMethod.GET })
public ResponseEntity<byte[]> drawTextByImage(
        @ApiParam(name = "documentId", required = true) @PathVariable(value = "documentId") String documentId,
        @ApiParam(name = "text", required = true) @RequestParam(required = true) String text,
        @ApiParam(name = "color", required = true) @RequestParam(required = true) String color,
        @ApiParam(name = "fontSize", required = true) @RequestParam(required = true) String fontSize,
        @ApiParam(name = "fontStyle", required = true) @RequestParam(required = true) String fontStyle,
        @ApiParam(name = "angle", required = true) @RequestParam(required = true) Integer angle,
        @ApiParam(name = "x", required = true) @RequestParam(required = true) Integer x,
        @ApiParam(name = "y", required = true) @RequestParam(required = true) Integer y,
        @ApiParam(name = "format", required = true, defaultValue = "jpg") @PathVariable(value = "format") String format

) throws InterruptedException, ExecutionException, TimeoutException, IOException {
    String _contentType = MimeType.getMimeType(format).contentType;
    if (!MimeType.getMimeType(format).isSupportedImage()) {
        return new ResponseEntity<byte[]>(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
    }

    FileTextJob args = new FileTextJob();
    args.setDocumentId(documentId);
    args.setFormat(format);
    args.setText(text);
    args.setColor(color);
    args.setFontSize(fontSize);
    args.setFontStyle(fontStyle);
    args.setAngle(angle);
    args.setX(x);
    args.setY(y);

    Future<Map> imageFuture = imageDrawTextGateway.imageDrawTextFilter(args);
    FileTextJob payload = (FileTextJob) imageFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

    //pass CF Response back to the client
    return payload.getHttpResponse();

}