Example usage for org.springframework.validation BindingResult getAllErrors

List of usage examples for org.springframework.validation BindingResult getAllErrors

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult getAllErrors.

Prototype

List<ObjectError> getAllErrors();

Source Link

Document

Get all errors, both global and field ones.

Usage

From source file:cec.easyshop.storefront.controllers.pages.CartPageController.java

@SuppressWarnings("boxing")
@ResponseBody//from   w ww  . j  ava  2  s  .c  om
@RequestMapping(value = "/updateMultiD", method = RequestMethod.POST)
public CartData updateCartQuantitiesMultiD(@RequestParam("entryNumber") final Integer entryNumber,
        @RequestParam("productCode") final String productCode, final Model model,
        @Valid final UpdateQuantityForm form, final BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        for (final ObjectError error : bindingResult.getAllErrors()) {
            if (error.getCode().equals("typeMismatch")) {
                GlobalMessages.addErrorMessage(model, "basket.error.quantity.invalid");
            } else {
                GlobalMessages.addErrorMessage(model, error.getDefaultMessage());
            }
        }
    } else {
        try {
            final CartModificationData cartModification = getCartFacade()
                    .updateCartEntry(getOrderEntryData(form.getQuantity(), productCode, entryNumber));
            if (cartModification.getStatusCode().equals(SUCCESSFUL_MODIFICATION_CODE)) {
                GlobalMessages.addMessage(model, GlobalMessages.CONF_MESSAGES_HOLDER,
                        cartModification.getStatusMessage(), null);
            } else if (!model.containsAttribute(ERROR_MSG_TYPE)) {
                GlobalMessages.addMessage(model, GlobalMessages.ERROR_MESSAGES_HOLDER,
                        cartModification.getStatusMessage(), null);
            }
        } catch (final CommerceCartModificationException ex) {
            LOG.warn("Couldn't update product with the entry number: " + entryNumber + ".", ex);
        }

    }
    return getCartFacade().getSessionCart();
}

From source file:org.smigo.user.UserController.java

@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/rest/user", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody/*  ww  w.  j  av  a2  s . c om*/
public List<ObjectError> updateUser(@RequestBody @Valid User userBean, BindingResult result,
        @AuthenticationPrincipal AuthenticatedUser user, HttpServletResponse response) {
    if (result.hasErrors()) {
        log.warn("Update user failed. Username:" + user.getUsername() + " Errors:"
                + StringUtils.arrayToDelimitedString(result.getAllErrors().toArray(), ", "));
        response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
        return result.getAllErrors();
    }
    log.info("Updating user: " + userBean.toString());
    userHandler.updateUser(user.getId(), userBean);
    return Collections.emptyList();
}

From source file:mx.gob.cfe.documentos.web.FeligresController.java

@Transactional
@RequestMapping(value = "/actualiza", method = RequestMethod.POST)
public String actualiza(HttpServletRequest request, @Valid Feligres feligres, BindingResult bindingResult,
        Errors errors, Model modelo, RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        log.debug("eeror");
        log.error("Hubo algun error en la forma, regresando");
        for (ObjectError error : bindingResult.getAllErrors()) {
            log.debug("Error: {}", error);
        }/*  w ww.ja  v  a  2  s .  co  m*/
        modelo.addAttribute("feligres", feligres);
        return "feligres/edita";
    }
    try {

        log.debug("feligres{}", feligres.toString());

        feligres = instance.actualiza(feligres);
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear la Asociacion", e);
        log.debug("exception");
        modelo.addAttribute("feligres", feligres);
        return "feligres/edita";
    }
    redirectAttributes.addFlashAttribute("message", "asociacion.actualizada.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { feligres.getNombre() });

    return "redirect:/feligres/ver/" + feligres.getId();
}

From source file:org.davidmendoza.esu.web.admin.UsuarioController.java

@RequestMapping(value = "/nuevo", method = RequestMethod.POST)
public String nuevo(@ModelAttribute("usuario") Usuario usuario, BindingResult bindingResult,
        RedirectAttributes redirectAttributes, Model model) {
    usuarioValidator.validate(usuario, bindingResult);
    if (bindingResult.hasErrors()) {
        log.warn("No se pudo crear usuario. {}", bindingResult.getAllErrors());
        return "admin/usuario/nuevo";
    }/*  w  w w . j  av  a  2  s.c o  m*/

    try {
        usuarioService.crea(usuario);
    } catch (Exception e) {
        log.error("No se pudo crear usuario", e);
        bindingResult.reject("No se pudo crear usuario. {}", e.getMessage());
        return "admin/usuario/nuevo";
    }
    return "redirect:/admin/usuario/ver/" + usuario.getId();
}

From source file:org.smigo.user.UserController.java

@RequestMapping(value = "/rest/user", method = RequestMethod.POST)
@ResponseBody//from   ww  w  .j av  a  2  s .c  om
public List<ObjectError> addUser(@RequestBody @Valid UserAdd user, BindingResult result,
        HttpServletResponse response, Locale locale) {
    log.info("Create user: " + user);
    if (result.hasErrors()) {
        log.warn("Create user failed. Username:" + user.getUsername() + " Errors:"
                + StringUtils.arrayToDelimitedString(result.getAllErrors().toArray(), ", "));
        response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
        return result.getAllErrors();
    }
    userHandler.createUser(user, locale);
    return Collections.emptyList();
}

From source file:org.davidmendoza.esu.web.admin.UsuarioController.java

@RequestMapping(value = "/editar", method = RequestMethod.POST)
public String editar(@ModelAttribute("perfil") Perfil perfil, BindingResult bindingResult,
        RedirectAttributes redirectAttributes, Model model) {
    perfilValidator.validate(perfil, bindingResult);
    if (bindingResult.hasErrors()) {
        log.warn("No se pudo actualizar usuario. {}", bindingResult.getAllErrors());
        return "admin/usuario/editar";
    }//ww w .  j  a va2  s  .c  o m
    Usuario usuario = perfil.getUsuario();

    try {
        perfilService.actualiza(perfil);
    } catch (Exception e) {
        log.error("No se pudo actualizar usuario", e);
        bindingResult.reject("No se pudo actualizar usuario. {}", e.getMessage());
        return "admin/usuario/editar";
    }
    return "redirect:/admin/usuario/ver/" + usuario.getId();
}

From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.CartPageController.java

@RequestMapping(value = "/update", method = RequestMethod.POST)
@RequireHardLogIn//from   w  w w.  ja v a  2 s .  c  o m
public String updateCartQuantities(@RequestParam("entryNumber") final long entryNumber, final Model model,
        @Valid final UpdateQuantityForm form, final BindingResult bindingResult,
        final RedirectAttributes redirectModel) throws CMSItemNotFoundException {
    if (bindingResult.hasErrors()) {
        for (final ObjectError error : bindingResult.getAllErrors()) {
            if (error.getCode().equals("typeMismatch")) {
                GlobalMessages.addErrorMessage(model, "basket.error.quantity.invalid");
            } else {
                GlobalMessages.addErrorMessage(model, error.getDefaultMessage());
            }
        }
    } else if (cartFacade.getSessionCart().getEntries() != null) {
        try {
            final CartModificationData cartModification = cartFacade.updateCartEntry(entryNumber,
                    form.getQuantity().longValue());
            if (cartModification.getQuantity() == form.getQuantity().longValue()) {
                // Success

                if (cartModification.getQuantity() == 0) {
                    // Success in removing entry
                    GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
                            "basket.page.message.remove");
                } else {
                    // Success in update quantity
                    GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
                            "basket.page.message.update");
                }
            } else {
                // Less than successful
                GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.ERROR_MESSAGES_HOLDER,
                        "basket.information.quantity.reducedNumberOfItemsAdded."
                                + cartModification.getStatusCode());
            }

            // Redirect to the cart page on update success so that the browser doesn't re-post again
            return REDIRECT_PREFIX + "/cart";
        } catch (final CommerceCartModificationException ex) {
            LOG.warn("Couldn't update product with the entry number: " + entryNumber + ".", ex);
        }
    }

    prepareDataForPage(model);
    return ControllerConstants.Views.Pages.Cart.CartPage;
}

From source file:org.smigo.species.SpeciesController.java

@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/rest/species/{id:\\d+}", method = RequestMethod.PUT)
@ResponseBody// w w w. ja va 2 s  . c om
public Object updateSpecies(@Valid @RequestBody Species species, BindingResult result, @PathVariable int id,
        @AuthenticationPrincipal AuthenticatedUser user, HttpServletResponse response, Locale locale) {
    log.info("Updating species. Species:" + species);
    if (result.hasErrors()) {
        response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
        return result.getAllErrors();
    }
    Review review = speciesHandler.updateSpecies(id, species, user);
    if (review == Review.MODERATOR) {
        response.setStatus(HttpStatus.ACCEPTED.value());
    }
    return speciesHandler.getSpecies(id);
}

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

@RequestMapping(method = RequestMethod.POST, params = "draft")
public @ResponseBody DomainObjectSavedModel saveAsDraft(@PathVariable String language,
        @Validated @ModelAttribute("form") ArticleEditForm form, BindingResult errors, Model model,
        AuthorizedUser authorizedUser) throws BindException {
    if (errors.hasErrors()) {
        for (ObjectError error : errors.getAllErrors()) {
            if (!"validation.NotNull".equals(error.getCode())) {
                throw new BindException(errors);
            }/*from   w ww .  j  a v  a2  s.co  m*/
        }
    }

    Article article = (Article) model.asMap().get("article");
    try {
        articleService.saveArticleAsDraft(form.buildArticleUpdateRequest(), authorizedUser);
    } catch (EmptyCodeException e) {
        errors.rejectValue("code", "NotNull");
    } catch (DuplicateCodeException e) {
        errors.rejectValue("code", "NotDuplicate");
    }
    if (errors.hasErrors()) {
        logger.debug("Errors: {}", errors);
        throw new BindException(errors);
    }

    return new DomainObjectSavedModel<>(article);
}

From source file:org.wallride.web.controller.admin.page.PageEditController.java

@RequestMapping(method = RequestMethod.POST, params = "draft")
public @ResponseBody DomainObjectSavedModel saveAsDraft(@PathVariable String language,
        @Validated @ModelAttribute("form") PageEditForm form, BindingResult errors, Model model,
        AuthorizedUser authorizedUser) throws BindException {
    if (errors.hasErrors()) {
        for (ObjectError error : errors.getAllErrors()) {
            if (!"validation.NotNull".equals(error.getCode())) {
                throw new BindException(errors);
            }//from  w  w  w .j  a v  a2  s  .  c  o  m
        }
    }

    Page page = (Page) model.asMap().get("page");
    try {
        pageService.savePageAsDraft(form.buildPageUpdateRequest(), authorizedUser);
    } catch (EmptyCodeException e) {
        errors.rejectValue("code", "NotNull");
    } catch (DuplicateCodeException e) {
        errors.rejectValue("code", "NotDuplicate");
    }
    if (errors.hasErrors()) {
        logger.debug("Errors: {}", errors);
        throw new BindException(errors);
    }

    return new DomainObjectSavedModel<>(page);
}