Example usage for org.springframework.validation BindException getBindingResult

List of usage examples for org.springframework.validation BindException getBindingResult

Introduction

In this page you can find the example usage for org.springframework.validation BindException getBindingResult.

Prototype

public final BindingResult getBindingResult() 

Source Link

Document

Return the BindingResult that this BindException wraps.

Usage

From source file:com.github.iexel.fontus.web.rest.GlobalControllerAdviceRest.java

@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)/*from www. j  a v  a2  s.c o m*/
@ExceptionHandler(BindException.class)
public AjaxError handle(BindException ex, Locale locale) {

    BindingResult bindingResult = ex.getBindingResult();
    AjaxError ajaxError = new AjaxError();
    ajaxError.setValidationErrors(fetchValidationErrorsAsStringArray(bindingResult, locale));
    ajaxError.setLocalErrorMessage(fetchErrorMessage("jggrid_validation_error_message", locale));
    return ajaxError;
}

From source file:org.wallride.web.controller.guest.comment.CommentRestController.java

@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)/*  w w  w  . ja  v  a  2 s .  co m*/
public RestValidationErrorModel bindException(BindException e) {
    logger.debug("BindException", e);
    return RestValidationErrorModel.fromBindingResult(e.getBindingResult(), messageSourceAccessor);
}

From source file:org.ng200.openolympus.controller.errors.BindingErrorController.java

@ResponseStatus(value = HttpStatus.OK)
@ExceptionHandler({ BindException.class })
@ResponseBody/*from   w  w w .  j  a v a 2s  .c  om*/
public BindingResponse handleBindException(BindException exception) {
    BindingErrorController.logger.info("Handling binding exception");
    return new BindingResponse(Status.BINDING_ERROR, exception.getBindingResult().getFieldErrors());
}

From source file:org.ng200.openolympus.controller.user.RegistrationRestController.java

@ResponseStatus(value = HttpStatus.OK)
@ExceptionHandler({ BindException.class })
public RegistrationResponse handleBindException(BindException exception) {
    return new RegistrationResponse(Status.BINDING_ERROR, null, exception.getBindingResult().getFieldErrors(),
            exception.getBindingResult().getGlobalErrors());
}

From source file:com.tkmtwo.exhandler.handlers.BindExceptionHandler.java

@Override
public ValidationErrorMessage createBody(BindException ex, HttpServletRequest req) {

    ErrorMessage tmpl = super.createBody(ex, req);
    ValidationErrorMessage msg = new ValidationErrorMessage(tmpl);

    BindingResult result = ex.getBindingResult();

    for (ObjectError err : result.getGlobalErrors()) {
        msg.addError(err.getDefaultMessage());
    }// w  ww . ja  va2  s  .  co  m
    for (FieldError err : result.getFieldErrors()) {
        msg.addError(err.getField(), err.getRejectedValue(), err.getDefaultMessage());
    }
    return msg;
}

From source file:org.wallride.web.controller.admin.article.ArticleCreateController.java

@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)//w  w w  .  ja  va 2s. co m
public @ResponseBody RestValidationErrorModel bindException(BindException e) {
    logger.debug("BindException", e);
    return RestValidationErrorModel.fromBindingResult(e.getBindingResult(), messageSourceAccessor);
}

From source file:com.iflytek.edu.cloud.frame.spring.DefaultHandlerExceptionResolver.java

protected MainError handleBindException(BindException ex, HttpServletRequest request,
        HttpServletResponse response, Object handler) throws IOException {
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

    List<ObjectError> errorList = ex.getBindingResult().getAllErrors();

    //Bean??Rop/*from   w w  w .jav  a 2  s .c o m*/
    MainError mainError = null;
    if (errorList != null && errorList.size() > 0) {
        mainError = toMainErrorOfSpringValidateErrors(errorList,
                (Locale) request.getAttribute(Constants.SYS_PARAM_KEY_LOCALE));
    }

    return mainError;
}

From source file:org.opentides.web.controller.BaseCrudController.java

/**
 * Handles all binding errors and return as json object for display to the
 * user.//ww w.  j a v a2  s  . co m
 * 
 * @param e
 * @param request
 * @return
 */
@ExceptionHandler(Exception.class)
public @ResponseBody Map<String, Object> handleBindException(Exception ex, HttpServletRequest request)
        throws Exception {
    Map<String, Object> response = new HashMap<String, Object>();
    List<MessageResponse> messages = new ArrayList<MessageResponse>();
    if (ex instanceof BindException) {
        BindException e = (BindException) ex;
        messages.addAll(CrudUtil.convertErrorMessage(e.getBindingResult(), request.getLocale(), messageSource));
        if (_log.isDebugEnabled())
            _log.debug("Bind error encountered.", e);
    } else {
        if (!request.getHeader("Accept").contains("application/json")) {
            throw ex;
        }
        MessageResponse message = new MessageResponse(Type.error, new String[] { "error.uncaught-exception" },
                new Object[] { ex.getMessage() });
        message.setMessage(messageSource.getMessage(message, request.getLocale()));
        messages.add(message);
        _log.error(ex, ex);
    }
    response.put("messages", messages);
    return response;
}

From source file:org.springframework.web.method.annotation.ModelAttributeMethodProcessor.java

/**
 * Resolve the argument from the model or if not found instantiate it with
 * its default if it is available. The model attribute is then populated
 * with request values via data binding and optionally validated
 * if {@code @java.validation.Valid} is present on the argument.
 * @throws BindException if data binding and validation result in an error
 * and the next method parameter is not of type {@link Errors}
 * @throws Exception if WebDataBinder initialization fails
 *//*w ww.ja va 2s .co m*/
@Override
@Nullable
public final Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

    Assert.state(mavContainer != null, "ModelAttributeMethodProcessor requires ModelAndViewContainer");
    Assert.state(binderFactory != null, "ModelAttributeMethodProcessor requires WebDataBinderFactory");

    String name = ModelFactory.getNameForParameter(parameter);
    ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
    if (ann != null) {
        mavContainer.setBinding(name, ann.binding());
    }

    Object attribute = null;
    BindingResult bindingResult = null;

    if (mavContainer.containsAttribute(name)) {
        attribute = mavContainer.getModel().get(name);
    } else {
        // Create attribute instance
        try {
            attribute = createAttribute(name, parameter, binderFactory, webRequest);
        } catch (BindException ex) {
            if (isBindExceptionRequired(parameter)) {
                // No BindingResult parameter -> fail with BindException
                throw ex;
            }
            // Otherwise, expose null/empty value and associated BindingResult
            if (parameter.getParameterType() == Optional.class) {
                attribute = Optional.empty();
            }
            bindingResult = ex.getBindingResult();
        }
    }

    if (bindingResult == null) {
        // Bean property binding and validation;
        // skipped in case of binding failure on construction.
        WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name);
        if (binder.getTarget() != null) {
            if (!mavContainer.isBindingDisabled(name)) {
                bindRequestParameters(binder, webRequest);
            }
            validateIfApplicable(binder, parameter);
            if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
                throw new BindException(binder.getBindingResult());
            }
        }
        // Value type adaptation, also covering java.util.Optional
        if (!parameter.getParameterType().isInstance(attribute)) {
            attribute = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType(), parameter);
        }
        bindingResult = binder.getBindingResult();
    }

    // Add resolved attribute and BindingResult at the end of the model
    Map<String, Object> bindingResultModel = bindingResult.getModel();
    mavContainer.removeAttributes(bindingResultModel);
    mavContainer.addAllAttributes(bindingResultModel);

    return attribute;
}

From source file:org.uhp.portlets.news.web.ItemAddController.java

@Override
protected void processCancel(ActionRequest request, ActionResponse response, Object command,
        BindException errors) throws Exception {
    final int currentPage = getCurrentPage(request);
    if (currentPage == 1 || currentPage == 2 || currentPage == 3) {
        final BindingResult bindingResult = errors.getBindingResult();
        errors = new BindException(bindingResult);

        ItemForm itemForm = (ItemForm) command;
        itemForm.setCategoryId((long) -1);
        itemForm.setTopicId((long) -1);
        itemForm.setItemId((long) -1);

        this.setPageRenderParameter(response, 0);
        request.getPortletSession().setAttribute("_globalCancel", false);

        response.setRenderParameter(Constants.ATT_CAT_ID, request.getParameter(Constants.ATT_CAT_ID));

    } else {/*  w  ww. j ava2 s  .  com*/
        ItemForm itemForm = (ItemForm) command;
        final Long tId = ctxTopicId;
        if (tId != null) {
            response.setRenderParameter(Constants.ATT_TOPIC_ID, String.valueOf(tId));
            ctxTopicId = null;
            String status = itemForm.getItem().getStatus();
            if (status == null) {
                response.setRenderParameter(Constants.ATT_STATUS, "1");
            } else {
                response.setRenderParameter(Constants.ATT_STATUS, status);
            }
            response.setRenderParameter(Constants.ACT, Constants.ACT_VIEW_TOPIC);
        } else {
            Long cId = itemForm.getItem().getCategoryId();
            response.setRenderParameter(Constants.ATT_CAT_ID, String.valueOf(cId));
            response.setRenderParameter(Constants.ACT, Constants.ACT_VIEW_CAT);
        }
        request.getPortletSession().setAttribute("_globalCancel", true);

        // clean temporary directory
        String prefix = "user_" + request.getRemoteUser() + "_";
        this.am.cleanTempStorageDirectory(this.getPortletContext().getRealPath(temporaryStoragePath), prefix);
    }
}