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:es.ucm.fdi.dalgs.degree.web.DegreeController.java

@RequestMapping(value = "/degree/upload.htm", method = RequestMethod.POST)
public String uploadPost(@ModelAttribute("newUpload") @Valid UploadForm upload, BindingResult resultBinding,
        Model model, Locale locale, RedirectAttributes attr) {

    if (resultBinding.hasErrors() || upload.getCharset().isEmpty() || upload.getFileData().getSize() == 0) {
        for (ObjectError error : resultBinding.getAllErrors()) {
            System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
        }/*  www .j  a  v  a  2s.c  om*/
        return "upload";
    }
    ResultClass<Boolean> result = serviceDegree.uploadCSV(upload, locale);

    if (!result.hasErrors())
        return "redirect:/degree/page/0.htm";
    else {
        attr.addFlashAttribute("errors", result.getErrorsList());
        return "redirect:/degree/upload.htm";
    }

}

From source file:com.epam.cme.storefront.controllers.pages.TelcoGuidedSellingController.java

@RequestMapping(value = "/addEntry", method = RequestMethod.POST)
public String addToCart(@RequestParam("productCodePost") final String code, final Model model,
        @Valid final UpdateQuantityForm form,
        @RequestParam(value = "bundleNo", required = false) final Integer bundleNo,
        @RequestParam(value = "bundleTemplateId", required = false) final String bundleTemplateId,
        @RequestParam(value = "removeCurrentProducts", required = false, defaultValue = "false") final boolean removeCurrentProducts,
        @RequestParam("navigation") final ComponentNavigation navigation, final BindingResult bindingResult,
        final RedirectAttributes redirectModel) {
    if (bindingResult.hasErrors()) {
        for (final ObjectError error : bindingResult.getAllErrors()) {
            if (error.getCode().equals("typeMismatch")) {
                redirectModel.addFlashAttribute(GlobalMessages.ERROR_MESSAGES_HOLDER,
                        Collections.singletonList("basket.error.quantity.invalid"));
            } else {
                redirectModel.addFlashAttribute(GlobalMessages.ERROR_MESSAGES_HOLDER,
                        Collections.singletonList(error.getDefaultMessage()));
            }//from  www.  j  a v a2  s  . c  o  m
        }
    }

    int finalBundleNo = addProduct(code, model, form.getQuantity().intValue(), bundleNo, bundleTemplateId,
            removeCurrentProducts, redirectModel);

    if (finalBundleNo < 0) {
        finalBundleNo = bundleNo == null ? 0 : bundleNo.intValue();
    }

    return REDIRECT_PREFIX + "/bundle/edit-component/" + finalBundleNo + "/" + navigation.code + "component/"
            + bundleTemplateId;
}

From source file:nl.surfnet.coin.selfservice.control.requests.LinkrequestController.java

@RequestMapping(value = "/question.shtml", method = RequestMethod.POST)
public ModelAndView spQuestionSubmit(@Valid @ModelAttribute("question") Question question, BindingResult result,
        @RequestParam long serviceId, SessionStatus sessionStatus, HttpServletRequest request) {
    denySuperUser(result);/*from www .j av a 2  s .  c o  m*/

    Map<String, Object> m = getModelMapWithService(serviceId, request);
    if (result.hasErrors()) {
        LOG.debug("Errors in data binding, will return to form view: {}", result.getAllErrors());
        return new ModelAndView("requests/question", m);
    } else {
        InstitutionIdentityProvider selectedIdp = getSelectedIdp(request);
        question.setType(JiraTask.Type.QUESTION);
        return doSubmitConfirm(m, question, result, selectedIdp, sessionStatus, "requests/question",
                "requests/linkrequest-thanks", "jsp.sp_question.thankstext");
    }
}

From source file:com.epam.cme.storefront.controllers.pages.TelcoCartPageController.java

@RequestMapping(value = "/update", method = RequestMethod.POST)
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());
            }//w  w  w.j  av a2s .co  m
        }
    } 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
                    redirectModel.addFlashAttribute(GlobalMessages.CONF_MESSAGES_HOLDER,
                            Collections.singletonList("basket.page.message.remove"));
                } else {
                    // Success in update quantity
                    redirectModel.addFlashAttribute(GlobalMessages.CONF_MESSAGES_HOLDER,
                            Collections.singletonList("basket.page.message.update"));
                }
            } else {
                // Less than successful

                if (form.getQuantity().longValue() == 0) {
                    // Failed to remove entry
                    redirectModel.addFlashAttribute(GlobalMessages.ERROR_MESSAGES_HOLDER,
                            Collections.singletonList("basket.information.quantity.reducedNumberOfItemsAdded."
                                    + cartModification.getStatusCode()));
                } else {
                    // Failed to update quantity
                    redirectModel.addFlashAttribute(GlobalMessages.ERROR_MESSAGES_HOLDER,
                            Collections.singletonList("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) {
            redirectModel.addFlashAttribute(GlobalMessages.ERROR_MESSAGES_HOLDER,
                    Collections.singletonList(ex.getMessage()));
            LOG.warn("Couldn't update product with the entry number: " + entryNumber + ".", ex);
        } finally {
            return REDIRECT_PREFIX + "/cart";
        }
    }

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

From source file:es.ucm.fdi.dalgs.module.web.ModuleController.java

@RequestMapping(value = "/degree/{degreeId}/module/upload.htm", method = RequestMethod.POST)
public String uploadPost(@ModelAttribute("newUpload") @Valid UploadForm upload, BindingResult resultBinding,
        Model model, @PathVariable("degreeId") Long id_degree, RedirectAttributes attr, Locale locale) {

    if (resultBinding.hasErrors() || upload.getCharset().isEmpty() || upload.getFileData().getSize() == 0) {
        for (ObjectError error : resultBinding.getAllErrors()) {
            System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
        }//  w w  w  .j  a  v a  2  s  . c om
        return "upload";
    }
    ResultClass<Boolean> result = serviceModule.uploadCSV(upload, id_degree, locale);
    if (!result.hasErrors())
        return "redirect:/degree/" + id_degree + ".htm";
    else {
        attr.addFlashAttribute("errors", result.getErrorsList());
        return "redirect:/degree/" + id_degree + "/module/upload.htm";
    }
}

From source file:com.pw.ism.controllers.AdminstratorController.java

@RequestMapping(value = "user/passchange", params = "form", method = RequestMethod.POST)
public ModelAndView changePassword(User user, BindingResult result, RedirectAttributes redirect,
        final HttpServletRequest req) {
    System.out.println("empty? " + user.getPassword());
    if (result.hasErrors()) {
        System.out.println("true and empty? " + user.getPassword());
        ModelAndView mvc = new ModelAndView("redirect:/admin/userdetails/{user.id}", "user.id", user.getId());
        mvc.addObject("formErrors", result.getAllErrors());
        return mvc;
    }//from  w  w w  . j av  a2s .c  om
    Long id = Long.parseLong(req.getParameter("removeId"));
    User userToChange = userRepository.findOne(id);
    String pass = passwordEncoder.encode(user.getPassword());
    userToChange.setPassword(pass);
    userRepository.save(userToChange);
    return new ModelAndView("redirect:/admin/userdetails/{user.id}", "user.id", userToChange.getId());
}

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

@RequestMapping(value = "/nuevo", method = RequestMethod.POST)
public String nuevo(@ModelAttribute("articulo") Articulo articulo, BindingResult bindingResult,
        RedirectAttributes redirectAttributes, Model model) {
    articuloValidator.validate(articulo, bindingResult);
    if (bindingResult.hasErrors()) {
        log.warn("No se pudo crear el articulo. {}", bindingResult.getAllErrors());
        Usuario autor = usuarioService.obtiene(articulo.getAutor().getId());
        articulo.setAutor(autor);/*from w  ww.  j  a va 2  s .  c  o m*/
        return "admin/articulo/nuevo";
    }

    try {
        articuloService.crea(articulo);
    } catch (Exception e) {
        log.error("No se pudo crear el articulo", e);
        bindingResult.reject("No se pudo crear el articulo. {}", e.getMessage());
        Usuario autor = usuarioService.obtiene(articulo.getAutor().getId());
        articulo.setAutor(autor);
        return "admin/articulo/nuevo";
    }
    return "redirect:/admin/articulo/ver/" + articulo.getId();
}

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

@RequestMapping(value = "/editar", method = RequestMethod.POST)
public String editar(@ModelAttribute("articulo") Articulo articulo, BindingResult bindingResult,
        RedirectAttributes redirectAttributes, Model model) {
    articuloValidator.validate(articulo, bindingResult);
    if (bindingResult.hasErrors()) {
        log.warn("No se pudo editar el articulo. {}", bindingResult.getAllErrors());
        Usuario autor = usuarioService.obtiene(articulo.getAutor().getId());
        articulo.setAutor(autor);//  w  w  w  .j a v  a2  s  . c o m
        return "admin/articulo/editar";
    }

    try {
        articuloService.actualiza(articulo);
    } catch (Exception e) {
        log.error("No se pudo editar el articulo", e);
        bindingResult.reject("No se pudo editar el articulo. {}", e.getMessage());
        Usuario autor = usuarioService.obtiene(articulo.getAutor().getId());
        articulo.setAutor(autor);
        return "admin/articulo/editar";
    }
    return "redirect:/admin/articulo/ver/" + articulo.getId();
}

From source file:com.redhat.rhtracking.web.controller.InvoiceController.java

@RequestMapping(value = "/invoice/add", method = RequestMethod.POST)
public String save(@Valid @ModelAttribute("invoiceInfo") InvoiceInfo invoiceInfo, BindingResult result,
        RedirectAttributes redirectAttributes, Model model, Principal principal) {
    List<String> messages = getFlashMessagesList(model, redirectAttributes);
    if (result.hasErrors()) {
        messages.add("warning::Errors found");
        messages.add("info::" + result.getAllErrors());
        redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.register", result);
        redirectAttributes.addFlashAttribute("invoiceInfo", invoiceInfo);

        redirectAttributes.addAttribute("matrix", invoiceInfo.getDeliveryMatrix());
        return "redirect:/invoice/add";
    }/*  w w w  . j  a v  a  2  s.  c o m*/

    Map<String, Object> request = new HashMap<>();

    request.put("invoiceRequest", invoiceInfo.getRequestNumber().replace(" ", ""));
    String invoiceNumber = invoiceInfo.getInvoiceNumber();
    invoiceNumber = invoiceNumber.replace(" ", "");
    if (!invoiceNumber.equals(""))
        request.put("invoiceNumber", invoiceNumber);

    request.put("platformQuantity", invoiceInfo.getPlatformHours());
    request.put("platformPrice", invoiceInfo.getPlatformPrice());
    request.put("middlewareQuantity", invoiceInfo.getMiddlewareHours());
    request.put("middlewarePrice", invoiceInfo.getMiddlewarePrice());
    request.put("workshopQuantity", invoiceInfo.getWorkshopHours());
    request.put("workshopPrice", invoiceInfo.getWorkshopPrice());

    request.put("date", invoiceInfo.getDate());
    request.put("deliveryMatrixId", invoiceInfo.getDeliveryMatrix());

    Map<String, Object> saveInvoice = invoiceService.saveInvoice(request);
    if ((EventStatus) saveInvoice.get("status") != EventStatus.SUCCESS) {
        messages.add("warning::Errrores encontrados");
        messages.add("info::" + saveInvoice);
        redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.register", result);
        redirectAttributes.addFlashAttribute("invoiceInfo", invoiceInfo);

        redirectAttributes.addAttribute("matrix", invoiceInfo.getDeliveryMatrix());
        return "redirect:/invoice/add";
    }

    return "redirect:/opportunity/show?id=" + invoiceInfo.getOpportunity();
}

From source file:com.acc.storefront.controllers.pages.CartPageController.java

@RequestMapping(value = "/update", method = RequestMethod.POST)
public String updateCartQuantities(@RequestParam("entryNumber") final long entryNumber, final Model model,
        @Valid final UpdateQuantityForm form, final BindingResult bindingResult,
        final HttpServletRequest request, 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());
            }//w  w  w. ja  v  a2  s .  c  o  m
        }
    } 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 if (cartModification.getQuantity() > 0) {
                // Less than successful
                GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.ERROR_MESSAGES_HOLDER,
                        "basket.page.message.update.reducedNumberOfItemsAdded.lowStock",
                        new Object[] { cartModification.getEntry().getProduct().getName(),
                                cartModification.getQuantity(), form.getQuantity(), request.getRequestURL()
                                        .append(cartModification.getEntry().getProduct().getUrl()) });
            } else {
                // No more stock available
                GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.ERROR_MESSAGES_HOLDER,
                        "basket.page.message.update.reducedNumberOfItemsAdded.noStock",
                        new Object[] { cartModification.getEntry().getProduct().getName(), request
                                .getRequestURL().append(cartModification.getEntry().getProduct().getUrl()) });
            }

            // 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;
}