Example usage for org.springframework.web.context.request.async DeferredResult setErrorResult

List of usage examples for org.springframework.web.context.request.async DeferredResult setErrorResult

Introduction

In this page you can find the example usage for org.springframework.web.context.request.async DeferredResult setErrorResult.

Prototype

public boolean setErrorResult(Object result) 

Source Link

Document

Set an error value for the DeferredResult and handle it.

Usage

From source file:co.paralleluniverse.springframework.web.method.support.FiberInvocableHandlerMethod.java

protected Object fiberDispatchInvoke(final Object... args) {
    final Object b = getBean();
    final Method m = getBridgedMethod();
    ReflectionUtils.makeAccessible(m);/*from  w w  w.  java2 s .c o m*/

    // Returning deferred even for normal return values, Spring return handlers will take care dynamically based on the actual returned value
    final DeferredResult ret = new DeferredResult();

    // The actual method execution and deferred completion is dispatched to a new fiber
    new Fiber(new SuspendableRunnable() {
        private Object deAsync(final Object o) throws SuspendExecution, Exception {
            if (o instanceof Callable)
                return deAsync(((Callable) o).call());
            else
                return o;
        }

        @Override
        public void run() throws SuspendExecution, InterruptedException {
            try {
                Object originalRet = m.invoke(b, args);
                ret.setResult(deAsync(originalRet));
            } catch (IllegalArgumentException ex) {
                assertTargetBean(m, b, args);
                ret.setErrorResult(
                        new IllegalStateException(getInvocationErrorMessage(ex.getMessage(), args), ex));
            } catch (InvocationTargetException ex) {
                // Unwrap for HandlerExceptionResolvers ...
                Throwable targetException = ex.getTargetException();
                if (targetException instanceof RuntimeException || targetException instanceof Error
                        || targetException instanceof Exception) {
                    ret.setErrorResult(targetException);
                } else {
                    String msg = getInvocationErrorMessage("Failed to invoke controller method", args);
                    ret.setErrorResult(new IllegalStateException(msg, targetException));
                }
            } catch (Exception ex) {
                ret.setErrorResult(ex);
            }
        }
    }).start();

    return ret;
}

From source file:com.opopov.cloud.image.service.ImageStitchingServiceImpl.java

@Override
public DeferredResult<ResponseEntity<?>> getStitchedImage(@RequestBody ImageStitchingConfiguration config) {

    validator.validateConfig(config);//  w  ww  .j  a  v a2 s  . c o m

    List<ListenableFuture<ResponseEntity<byte[]>>> futures = config.getUrlList().stream()
            .map(url -> remoteResource.getForEntity(url, byte[].class)).collect(Collectors.toList());

    //wrap the listenable futures into the completable futures
    //writing loop in pre-8 style, since it would be more concise compared to stream api in this case
    CompletableFuture[] imageFutures = new CompletableFuture[futures.size()];
    int taskIndex = 0;
    IndexMap indexMap = new IndexMap(config.getRowCount() * config.getColumnCount());
    for (ListenableFuture<ResponseEntity<byte[]>> f : futures) {
        imageFutures[taskIndex] = imageDataFromResponse(taskIndex, indexMap, utils.fromListenableFuture(f));
        taskIndex++;
    }

    CompletableFuture<Void> allDownloadedAndDecompressed = CompletableFuture.allOf(imageFutures);

    //Synchronous part - start - writing decompressed bytes to the large image
    final int DOWNLOAD_AND_DECOMPRESS_TIMEOUT = 30; //30 seconds for each of the individual tasks
    DeferredResult<ResponseEntity<?>> response = new DeferredResult<>();
    boolean allSuccessful = false;
    byte[] imageBytes = null;
    try {
        Void finishResult = allDownloadedAndDecompressed.get(DOWNLOAD_AND_DECOMPRESS_TIMEOUT, TimeUnit.SECONDS);

        imageBytes = combineImagesIntoStitchedImage(config, indexMap);

        HttpHeaders headers = new HttpHeaders();
        headers.setCacheControl(CacheControl.noCache().getHeaderValue());
        headers.setContentType(MediaType.IMAGE_JPEG);
        allSuccessful = true;
    } catch (InterruptedException | ExecutionException e) {
        // basically either download or decompression of the source image failed
        // just skip it then, we have no image to show
        response.setErrorResult(
                new SourceImageLoadException("Unable to load and decode one or more source images", e));
    } catch (TimeoutException e) {
        //send timeout response, via ImageLoadTimeoutException
        response.setErrorResult(new ImageLoadTimeoutException(
                String.format("Some of the images were not loaded and decoded before timeout of %d seconds",
                        DOWNLOAD_AND_DECOMPRESS_TIMEOUT),
                e

        ));
    } catch (IOException e) {
        response.setErrorResult(new ImageWriteException("Error writing image into output buffer", e));
    }

    //Synchronous part - end

    if (!allSuccessful) {
        //shoud not get here, some unknown error
        response.setErrorResult(
                new ImageLoadTimeoutException("Unknown error", new RuntimeException("Something went wrong")

                ));

        return response;
    }

    ResponseEntity<?> successResult = ResponseEntity.ok(imageBytes);
    response.setResult(successResult);

    return response;

}

From source file:com.chessix.vas.web.TransferController.java

@RequestMapping(value = "/{clasId}/{from}/{to}/{amount}", method = RequestMethod.POST)
public DeferredResult<Object> transfer(@PathVariable final String clasId, @PathVariable final String from,
        @PathVariable final String to, @PathVariable final int amount) {
    log.debug("transfer({},{},{},{})", clasId, from, to, amount);
    final ActorRef clas = clasService.getClas(clasId);
    final DeferredResult<Object> deferredResult = new DeferredResult<Object>();
    if (clas != null) {
        final ExecutionContext ec = actorSystem.dispatcher();
        final Future<Object> future = Patterns.ask(clas,
                new Transfer.RequestBuilder(accountService.getAccountId(from), accountService.getAccountId(to),
                        amount).build(),
                timeout);//from www .java 2s  . com
        future.onSuccess(new OnSuccess<Object>() {
            @Override
            public void onSuccess(final Object result) {
                log.info("transfer({},{},{},{}) : result: {}", clasId, from, to, amount, result);
                deferredResult.setResult(result);
            }
        }, ec);
        future.onFailure(new OnFailure() {
            @Override
            public void onFailure(final Throwable arg) throws Throwable {
                log.error("onFailure", arg);
                deferredResult.setErrorResult(arg);
            }
        }, ec);
    } else {
        deferredResult.setErrorResult(new TransferDTO(clasId, from, to, false, "CLAS does not exist"));
    }
    return deferredResult;
}

From source file:be.solidx.hot.data.rest.RestDataStore.java

private DeferredResult<ResponseEntity<byte[]>> blockingCall(final Callable<ResponseEntity<byte[]>> dbCall) {

    final DeferredResult<ResponseEntity<byte[]>> deferredResult = new DeferredResult<>();

    DeferredManager deferredManager = new DefaultDeferredManager(blockingTaskThreadPool);

    deferredManager.when(dbCall).done(new DoneCallback<ResponseEntity<byte[]>>() {
        @Override/*w  w  w . ja  v  a2  s. co  m*/
        public void onDone(ResponseEntity<byte[]> result) {
            deferredResult.setResult(result);
        }
    }).fail(new FailCallback<Throwable>() {
        @Override
        public void onFail(Throwable e) {
            deferredResult.setErrorResult(new ResponseEntity<byte[]>(extractStackTrace(e).getBytes(),
                    HttpStatus.INTERNAL_SERVER_ERROR));

        }
    });
    return deferredResult;
}

From source file:io.ignitr.dispatchr.manager.controller.client.ClientsController.java

/**
 * Finds all clients in the system.//from w  ww  .j a va2s.  c om
 *
 * @param offset starting offset when using pagination
 * @param limit number of records to return when using pagination
 * @param sortDir sort direction of records when using pagination
 * @param httpRequest http request
 * @return an HTTP 200 response containing a list of all clients defined in the system
 */
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public DeferredResult<ResponseEntity<?>> findAll(
        @RequestParam(value = "offset", defaultValue = "0") Long offset,
        @RequestParam(value = "limit", defaultValue = "25") Long limit,
        @RequestParam(value = "sort_dir", defaultValue = "asc") String sortDir,
        @RequestParam(value = "active", defaultValue = "true") Boolean active, HttpServletRequest httpRequest) {
    final DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();

    Observable.fromCallable(() -> SortDirectionValidator.validate(sortDir))
            .lift(new RequestContextStashOperator<>())
            .flatMap(valid -> Observable.create(new Observable.OnSubscribe<List<Client>>() {
                List<Client> clients = new ArrayList<>();

                @Override
                public void call(Subscriber<? super List<Client>> subscriber) {
                    service.findAll(offset, limit, sortDir, active).collect(() -> clients, List::add)
                            .subscribe(clients -> {
                                subscriber.onNext(clients);
                                subscriber.onCompleted();
                            });
                }
            })).map(FindClientsResponse::from).subscribeOn(Schedulers.io()).subscribe(body -> {
                deferredResult.setResult(ResponseEntity.ok(body));
            }, error -> {
                deferredResult.setErrorResult(errorHandler.handleError(httpRequest, error));
            });

    return deferredResult;
}

From source file:com.chessix.vas.web.AccountController.java

@RequestMapping(value = "/{clasId}/{accountId}", method = RequestMethod.POST)
public DeferredResult<Object> createAccount(@PathVariable final String clasId,
        @PathVariable final String accountId) {
    log.info("createAccount({},{})", clasId, accountId);
    final ActorRef clas = clasService.getClas(clasId);
    final DeferredResult<Object> deferredResult = new DeferredResult<Object>();
    if (clas != null) {
        final Future<Object> future = Patterns.ask(clas,
                new CreateAccount.RequestBuilder(clasId).accountId(accountId).build(), timeout);
        future.onSuccess(new OnSuccess<Object>() {
            @Override//ww  w.  ja  v a  2  s. c  om
            public void onSuccess(final Object result) {
                log.info("createAccount({}) : result: {}", clasId, result);
                final CreateAccount.Response response = (CreateAccount.Response) result;
                deferredResult.setResult(
                        new AccountCreated(clasId, response.getAccountId(), true, "Account created"));
            }
        }, system.dispatcher());
        future.onFailure(new OnFailure() {
            @Override
            public void onFailure(final Throwable arg) throws Throwable {
                log.error("onFailure", arg);
                deferredResult
                        .setErrorResult(new AccountCreated(clasId, null, false, arg.getLocalizedMessage()));
            }
        }, system.dispatcher());
    } else {
        deferredResult.setErrorResult(new AccountCreated(clasId, null, false, "CLAS does not exist"));
    }
    return deferredResult;
}

From source file:io.ignitr.dispatchr.manager.controller.topic.TopicsController.java

/**
 * Find all available SNS topics within the AWS account and whether or not they are registered with Dispatchr.
 *
 * @param offset index of item to start returning when using pagination
 * @param limit number of items to return when using pagination
 * @param sortDir sort order in which to return items when using pagination
 * @return an HTTP 200 response if the request was successful
 *//*from  w ww . j ava 2s .co m*/
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public DeferredResult<ResponseEntity<FindTopicsResponse>> findAll(
        @RequestParam(value = "offset", defaultValue = "0") Long offset,
        @RequestParam(value = "limit", defaultValue = "25") Long limit,
        @RequestParam(value = "sort_dir", defaultValue = "asc") String sortDir,
        HttpServletRequest httpRequest) {
    final DeferredResult<ResponseEntity<FindTopicsResponse>> deferredResult = new DeferredResult<>();

    Observable.fromCallable(() -> SortDirectionValidator.validate(sortDir))
            .lift(new RequestContextStashOperator<>())
            .flatMap(valid -> Observable.create(new Observable.OnSubscribe<List<Topic>>() {
                List<Topic> topicMetadatas = new ArrayList<>();

                @Override
                public void call(Subscriber<? super List<Topic>> subscriber) {
                    service.findAll(offset, limit, sortDir).collect(() -> topicMetadatas, List::add)
                            .subscribe(topicMetadatas -> {
                                subscriber.onNext(topicMetadatas);
                                subscriber.onCompleted();
                            });
                }
            })).map(FindTopicsResponse::from).subscribeOn(Schedulers.io()).subscribe(body -> {
                deferredResult.setResult(ResponseEntity.ok(body));
            }, error -> {
                deferredResult.setErrorResult(errorHandler.handleError(httpRequest, error));
            });

    return deferredResult;
}

From source file:io.ignitr.dispatchr.manager.controller.topic.TopicsController.java

/**
 * Find all SNS topics that have been registered with Dispatchr.
 *
 * @param offset index of item to start returning when using pagination
 * @param limit number of items to return when using pagination
 * @param sortDir sort order in which to return items when using pagination
 * @return an HTTP 200 response if the request was successful
 *///from w  w  w.  j  a  va2 s  . c om
@RequestMapping(method = RequestMethod.GET, value = "/registered", produces = MediaType.APPLICATION_JSON_VALUE)
public DeferredResult<ResponseEntity<FindTopicsResponse>> findRegistered(
        @RequestParam(value = "offset", defaultValue = "0") Long offset,
        @RequestParam(value = "limit", defaultValue = "25") Long limit,
        @RequestParam(value = "sort_dir", defaultValue = "asc") String sortDir,
        HttpServletRequest httpRequest) {
    final DeferredResult<ResponseEntity<FindTopicsResponse>> deferredResult = new DeferredResult<>();

    Observable.fromCallable(() -> SortDirectionValidator.validate(sortDir))
            .lift(new RequestContextStashOperator<>())
            .flatMap(valid -> Observable.create(new Observable.OnSubscribe<List<Topic>>() {
                List<Topic> topicMetadatas = new ArrayList<>();

                @Override
                public void call(Subscriber<? super List<Topic>> subscriber) {
                    service.findRegistered(offset, limit, sortDir).collect(() -> topicMetadatas, List::add)
                            .subscribe(topicMetadatas -> {
                                subscriber.onNext(topicMetadatas);
                                subscriber.onCompleted();
                            });
                }
            })).map(FindTopicsResponse::from).subscribeOn(Schedulers.io()).subscribe(body -> {
                deferredResult.setResult(ResponseEntity.ok(body));
            }, error -> {
                deferredResult.setErrorResult(errorHandler.handleError(httpRequest, error));
            });

    return deferredResult;
}

From source file:io.ignitr.dispatchr.manager.controller.topic.TopicsController.java

/**
 * Find all SNS topics that are not registered with Dispatchr.
 *
 * @param offset index of item to start returning when using pagination
 * @param limit number of items to return when using pagination
 * @param sortDir sort order in which to return items when using pagination
 * @return an HTTP 200 response if the request was successful
 *//*from  ww w  . ja v  a2  s.c  om*/
@RequestMapping(method = RequestMethod.GET, value = "/unregistered", produces = MediaType.APPLICATION_JSON_VALUE)
public DeferredResult<ResponseEntity<FindTopicsResponse>> findUnregistered(
        @RequestParam(value = "offset", defaultValue = "0") Long offset,
        @RequestParam(value = "limit", defaultValue = "25") Long limit,
        @RequestParam(value = "sort_dir", defaultValue = "asc") String sortDir,
        HttpServletRequest httpRequest) {
    final DeferredResult<ResponseEntity<FindTopicsResponse>> deferredResult = new DeferredResult<>();

    Observable.fromCallable(() -> SortDirectionValidator.validate(sortDir))
            .lift(new RequestContextStashOperator<>())
            .flatMap(valid -> Observable.create(new Observable.OnSubscribe<List<Topic>>() {
                List<Topic> topicMetadatas = new ArrayList<>();

                @Override
                public void call(Subscriber<? super List<Topic>> subscriber) {
                    service.findUnregistered(offset, limit, sortDir).collect(() -> topicMetadatas, List::add)
                            .subscribe(topicMetadatas -> {
                                subscriber.onNext(topicMetadatas);
                                subscriber.onCompleted();
                            });
                }
            })).map(FindTopicsResponse::from).subscribeOn(Schedulers.io()).subscribe(body -> {
                deferredResult.setResult(ResponseEntity.ok(body));
            }, error -> {
                deferredResult.setErrorResult(errorHandler.handleError(httpRequest, error));
            });

    return deferredResult;
}

From source file:net.tenorite.web.TempoController.java

@RequestMapping("/t/{tempo}/channels")
public DeferredResult<ModelAndView> channels(@PathVariable("tempo") Tempo tempo) {
    DeferredResult<ModelAndView> deferred = new DeferredResult<>();

    channelsRegistry.listChannels(tempo).whenComplete((channels, throwable) -> {
        if (throwable != null) {
            deferred.setErrorResult(throwable);
        } else {//from ww w.j av  a  2 s .c  om
            List<Channel> sorted = channels.stream().sorted(new PropertyComparator<>("name", true, true))
                    .collect(toList());

            ModelAndView mav = new ModelAndView("channels").addObject("tempo", tempo)
                    .addObject("gameModes", gameModes).addObject("channels", sorted);

            deferred.setResult(mav);
        }
    });

    return deferred;
}