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:com.epam.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());
            }//from   w  w w  .j a va  2  s  . co  m
        }
    } else if (cartFacade.hasEntries()) {
        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;
}

From source file:com.aestheticsw.jobkeywords.web.html.JobController.java

/**
 * The search page relies on an AJAX call to submit the form-parameters and redraw only a
 * portion of the HTML page./*  w ww. j  a  va  2s  .co m*/
 * 
 * If a validation error occurs for an initial search then the Javascript must correctly handle
 * the case where a subsequent search corrects the validation error and draws the response.
 * Correcting a validation error requires the Javascript to redraw both the <form> and the
 * results <div> HTML.
 *
 * If the search page is in a clean state then the search results only require redrawing the
 * <div> that contains the results. When an initial validation error occurs, only the <div> that
 * contains the form must be redrawn. When an initial valication is subsequencly corrected then
 * both <div>s must be redrawn.
 */
@RequestMapping(value = "/search", method = RequestMethod.POST)
public ModelAndView getTermListForSearchParameters(@Valid SearchFormBean searchFormBean, BindingResult result,
        RedirectAttributes redirect, @RequestParam(required = false) boolean isAjaxRequest) {

    Map<String, Object> modelMap = new HashMap<>();
    modelMap.put("searchFormBean", searchFormBean);
    if (result.hasErrors()) {
        searchFormBean.setHadFormErrors(true);
        modelMap.put("formErrors", result.getAllErrors());

        // Return the whole HTML page and let the Javascript select which <div> tags it wants to render. 
        return new ModelAndView("keywords", modelMap);
    }

    Locale locale = Locale.US;
    if (StringUtils.isNoneEmpty(searchFormBean.getCountry())) {
        locale = SearchUtils.lookupLocaleByCountry(searchFormBean.getCountry());
    }
    SearchParameters params = new SearchParameters(
            new QueryKey(searchFormBean.getQuery(), locale, searchFormBean.getCity()),
            searchFormBean.getJobCount(), searchFormBean.getStart(), searchFormBean.getRadius(),
            searchFormBean.getSort());

    TermFrequencyList termFrequencyList;
    try {
        termFrequencyList = termExtractorService.extractTerms(params);
    } catch (IndeedQueryException e) {
        searchFormBean.setHadFormErrors(true);
        result.addError(new FieldError("searchFormBean", "query",
                "No results found, check query expression: " + params));
        modelMap.put("formErrors", result.getAllErrors());

        // Return the whole HTML page and let the Javascript select which <div> tags it wants to render. 
        return new ModelAndView("keywords", modelMap);
    }

    searchFormBean.setHadFormErrors(false);
    modelMap.put("results", termFrequencyList);
    if (isAjaxRequest) {
        // Return only the results fragment. 
        return new ModelAndView("keywords :: query-results", modelMap);
    }
    return new ModelAndView("keywords", modelMap);
}

From source file:es.ucm.fdi.dalgs.topic.web.TopicController.java

@RequestMapping(value = "/degree/{degreeId}/module/{moduleId}/topic/upload.htm", method = RequestMethod.POST)
public String uploadPost(@ModelAttribute("newUpload") @Valid UploadForm upload, BindingResult resultBinding,
        Model model, @PathVariable("moduleId") Long id_module, @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());
        }//from   w  ww .  j a  v  a 2s .c o m
        return "upload";
    }
    ResultClass<Boolean> result = serviceTopic.uploadCSV(upload, id_module, id_degree, locale);
    if (!result.hasErrors())
        return "redirect:/degree/" + id_degree + "/module/" + id_module + ".htm";

    else {
        attr.addFlashAttribute("errors", result.getErrorsList());
        return "redirect:/degree/" + id_degree + "/module/" + id_module + "/topic/upload.htm";
    }
}

From source file:mx.edu.um.mateo.general.web.EmpresaController.java

@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpSession session, @Valid Empresa empresa, BindingResult bindingResult, Errors errors,
        Model modelo, RedirectAttributes redirectAttributes,
        @RequestParam(value = "cuentaId", required = false) String centroDeCostoId) {
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        for (ObjectError error : bindingResult.getAllErrors()) {
            log.debug("Error: {}", error);
        }/*w  w  w.  j a va2 s  . c  om*/
        return "admin/empresa/nueva";
    }

    try {
        Usuario usuario = ambiente.obtieneUsuario();
        if (StringUtils.isNotBlank(centroDeCostoId)) {
            CentroCosto centroCosto = centroCostoDao.obtiene(centroDeCostoId, usuario);
            empresa.setCentroCosto(centroCosto);
        }

        empresa = empresaDao.crea(empresa, usuario);

        ambiente.actualizaSesion(session, usuario);
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear al empresa", e);
        errors.rejectValue("codigo", "campo.duplicado.message", new String[] { "codigo" }, null);
        errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null);
        return "admin/empresa/nueva";
    }

    redirectAttributes.addFlashAttribute("message", "empresa.creada.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { empresa.getNombre() });

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

From source file:mx.edu.um.mateo.general.web.EmpresaController.java

@RequestMapping(value = "/actualiza", method = RequestMethod.POST)
public String actualiza(HttpSession session, @Valid Empresa empresa, BindingResult bindingResult, Errors errors,
        Model modelo, RedirectAttributes redirectAttributes,
        @RequestParam(value = "cuentaId", required = false) String centroDeCostoId) {
    if (bindingResult.hasErrors()) {
        log.error("Hubo algun error en la forma, regresando");
        for (ObjectError error : bindingResult.getAllErrors()) {
            log.debug("Error: {}", error);
        }/* w w w  .ja va 2s. com*/
        return "admin/empresa/edita";
    }

    try {
        Usuario usuario = ambiente.obtieneUsuario();
        if (StringUtils.isNotBlank(centroDeCostoId)) {
            CentroCosto centroCosto = centroCostoDao.obtiene(centroDeCostoId, usuario);
            empresa.setCentroCosto(centroCosto);
        }

        empresa = empresaDao.actualiza(empresa, usuario);

        ambiente.actualizaSesion(session, usuario);
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear la empresa", e);
        errors.rejectValue("codigo", "campo.duplicado.message", new String[] { "codigo" }, null);
        errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null);
        return "admin/empresa/nueva";
    }

    redirectAttributes.addFlashAttribute("message", "empresa.actualizada.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { empresa.getNombre() });

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

From source file:cz.PA165.vozovyPark.controller.DriveController.java

@RequestMapping(value = "/drive/new", method = RequestMethod.POST)
public String addDrive(@Valid @ModelAttribute("drive") DriveDTO drive, BindingResult result, ModelMap model,
        HttpServletRequest req) throws ParseException { // @Valid validates model after binding user input to it
    if (result.hasErrors()) {
        model.put("state", DriveStateEnum.values());
        model.put("user", userService.getEnabledUsers());
        model.put("vehicle", vehicleService.findAll());
        req.getSession().setAttribute("message", result.getAllErrors().toString());
        return "/drive/driveForm";
    }/*from  w ww .j av a2 s .co m*/

    if (!isIntervalFree(drive)) {
        model.put("state", DriveStateEnum.values());
        model.put("vehicle", vehicleService.findAll());
        model.put("user", userService.getEnabledUsers());
        req.getSession().setAttribute("message",
                "Selected car is not available for this date, please select a vehicle or date.");
        return "/drive/driveForm";
    }
    driveService.createDrive(drive);
    return "redirect:/drive/all";
}

From source file:mx.edu.um.mateo.contabilidad.web.EjercicioController.java

@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, HttpServletResponse response, @Valid Ejercicio ejercicio,
        BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }/*from   ww w . j  a  v a 2 s . c  o  m*/
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        for (ObjectError error : bindingResult.getAllErrors()) {
            log.debug("Error: {}", error);
        }
        return "admin/ejercicio/nueva";
    }

    try {
        Usuario usuario = ambiente.obtieneUsuario();
        ejercicio = ejercicioDao.crea(ejercicio, usuario);
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear al ejercicio", e);
        errors.rejectValue("id", "campo.duplicado.message", new String[] { "id" }, null);
        errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null);
        return "contabilidad/ejercicio/nuevo";
    }

    redirectAttributes.addFlashAttribute("message", "ejercicio.creado.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { ejercicio.getNombre() });

    return "redirect:/contabilidad/ejercicio/ver/" + ejercicio.getId().getIdEjercicio();
}

From source file:com.device.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 ("typeMismatch".equals(error.getCode())) {
                GlobalMessages.addErrorMessage(model, "basket.error.quantity.invalid");
            } else {
                GlobalMessages.addErrorMessage(model, error.getDefaultMessage());
            }/*from w w w . j  av a2s .c  o m*/
        }
    } else if (getCartFacade().hasEntries()) {
        try {
            final CartModificationData cartModification = getCartFacade().updateCartEntry(entryNumber,
                    form.getQuantity().longValue());
            addFlashMessage(form, request, redirectModel, cartModification);

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

    prepareDataForPage(model);

    model.addAttribute(WebConstants.BREADCRUMBS_KEY,
            resourceBreadcrumbBuilder.getBreadcrumbs("breadcrumb.cart"));
    model.addAttribute("pageType", PageType.CART.name());

    return ControllerConstants.Views.Pages.Cart.CartPage;
}

From source file:mx.edu.um.mateo.general.web.AsociacionController.java

@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, HttpServletResponse response, @Valid Asociacion asociacion,
        BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }//  w  w w . j  a  v  a 2s. c o  m
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        for (ObjectError error : bindingResult.getAllErrors()) {
            log.debug("Error: {}", error);
        }
        return Constantes.PATH_ASOCIACION_NUEVA;
    }
    try {
        Usuario usuario = null;
        if (ambiente.obtieneUsuario() != null) {
            usuario = ambiente.obtieneUsuario();
        }
        asociacion = asociacionDao.crea(asociacion, usuario);
        ambiente.actualizaSesion(request, usuario);
    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear al Asociacion", e);
        errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null);
        return Constantes.PATH_ASOCIACION_NUEVA;
    }
    redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE, "asociacion.creada.message");
    redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE_ATTRS,
            new String[] { asociacion.getNombre() });
    return "redirect:" + Constantes.PATH_ASOCIACION_VER + "/" + asociacion.getId();
}

From source file:com.searchbox.framework.web.admin.SearchElementDefinitionController.java

@RequestMapping(method = RequestMethod.POST)
public ModelAndView update(@Valid SearchElementEntity elementDefinition, BindingResult bindingResult,
        HttpServletRequest httpServletRequest, ServerHttpResponse response) {
    LOGGER.info("Creating an filed element: " + elementDefinition.getClazz().getSimpleName() + " for preset: "
            + elementDefinition.getPreset().getSlug());

    ModelAndView model = new ModelAndView("admin/SearchElementDefinition/updateForm");

    if (bindingResult.hasErrors()) {
        LOGGER.error("Bindding has error...");
        for (ObjectError error : bindingResult.getAllErrors()) {
            LOGGER.error("Error: " + error.getDefaultMessage());
        }//  ww w . j  a v a 2  s.  c om
        response.setStatusCode(HttpStatus.PRECONDITION_FAILED);
        return model;
    }
    try {
        elementDefinition = repository.save(elementDefinition);
    } catch (Exception e) {
        LOGGER.error("Could not save elementDefinition", e);
    }
    model.addObject("searchElementDefinition", elementDefinition);
    return model;
}