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:org.wallride.web.controller.admin.page.PageCreateController.java

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

    Page page = null;
    try {
        page = pageService.createPage(form.buildPageCreateRequest(), Post.Status.DRAFT, 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);
}

From source file:ch.ralscha.extdirectspring.bean.ExtDirectFormPostResult.java

private void addErrors(Locale locale, MessageSource messageSource, BindingResult bindingResult) {
    if (bindingResult != null && bindingResult.hasFieldErrors()) {
        Map<String, String> errorMap = new HashMap<String, String>();
        for (ObjectError objectError : bindingResult.getAllErrors()) {
            FieldError fieldError = (FieldError) objectError;
            String message = null;
            for (String code : fieldError.getCodes()) {
                message = MessageUtil.getMessage(code, null, locale); // , new Object[] {(fieldError.getObjectName() +"." + fieldError.getField()), fieldError.getRejectedValue()}
                if (StringUtils.isNotBlank(message)) {
                    break;
                }/*from   www  .  j a  v  a  2s.  c o m*/
            }
            errorMap.put(fieldError.getField(),
                    StringUtils.defaultIfBlank(message, fieldError.getDefaultMessage()));
        }
        if (errorMap.isEmpty()) {
            addResultProperty("success", true);
        } else {
            addResultProperty("errors", errorMap);
            addResultProperty("success", false);
        }
    } else {
        setSuccess(true);
    }

    //        if (bindingResult != null && bindingResult.hasFieldErrors()) {
    //            Map<String, List<String>> errorMap = new HashMap<String, List<String>>();
    //            for (FieldError fieldError : bindingResult.getFieldErrors()) {
    //                String message = fieldError.getDefaultMessage();
    //                if (messageSource != null) {
    //                    Locale loc = (locale != null ? locale : Locale.getDefault());
    //                    message = messageSource.getMessage(fieldError.getCode(), fieldError.getArguments(), loc);
    //                }
    //                List<String> fieldErrors = errorMap.get(fieldError.getField());
    //
    //                if (fieldErrors == null) {
    //                    fieldErrors = new ArrayList<String>();
    //                    errorMap.put(fieldError.getField(), fieldErrors);
    //                }
    //
    //                fieldErrors.add(message);
    //            }
    //            if (errorMap.isEmpty()) {
    //                addResultProperty("success", true);
    //            } else {
    //                addResultProperty("errors", errorMap);
    //                addResultProperty("success", false);
    //            }
    //        } else {
    //            setSuccess(true);
    //        }
}

From source file:controller.Crud.java

@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
public ModelAndView update(@Valid @ModelAttribute("hallo") Hallo hallo, BindingResult result,
        @PathVariable("id") String id) {
    if (result.hasErrors()) {
        ModelAndView modelAndView = new ModelAndView("crud/edit");
        modelAndView.addObject("command", hallo);
        modelAndView.addObject("id", id);
        modelAndView.addObject("error", result.getAllErrors());
        return modelAndView;
    } else {/*from w  ww.j  a v  a  2 s  . c o m*/
        config.simpanUpdate(hallo);
        return new ModelAndView("redirect:/show");
    }
}

From source file:org.mzd.shap.spring.web.DataSearchController.java

@RequestMapping("/query_json")
@ResponseBody//w  ww .  j  a v a  2  s .  co m
public SearchResult<Report> searchJson(@Valid LuceneQueryPaged luceneQuery, BindingResult result)
        throws ApplicationException {
    if (result.hasErrors()) {
        List<ObjectError> errors = result.getAllErrors();
        for (ObjectError e : errors) {
            getLogger().warn(e);
        }
        return null;
    }
    return getDataAdmin().getReports(luceneQuery.getQueryText(), luceneQuery.getFirst(), luceneQuery.getMax());
}

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

@RequestMapping(value = "/nuevo", method = RequestMethod.POST)
public String nuevo(@ModelAttribute("trimestre") Trimestre trimestre, BindingResult bindingResult,
        RedirectAttributes redirectAttributes, Model model) {
    trimestreValidator.validate(trimestre, bindingResult);
    if (bindingResult.hasErrors()) {
        log.warn("No se pudo crear trimestre. {}", bindingResult.getAllErrors());
        return "admin/trimestre/nuevo";
    }/*www .  j a v a2 s.c o  m*/

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

From source file:org.openmrs.module.billing.web.controller.main.AmbulanceBillEditController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(Model model, @RequestParam("ambulanceBillId") Integer ambulanceBillId,
        @RequestParam("driverId") Integer driverId, @RequestParam("ambulanceIds") Integer[] ambulanceIds,
        @RequestParam("action") String action, HttpServletRequest request, Object command,
        BindingResult binding) {

    validate(ambulanceIds, binding, request);
    if (binding.hasErrors()) {
        model.addAttribute("errors", binding.getAllErrors());
        return "module/billing/main/ambulanceBillAdd";
    }/*ww w.j  av  a  2 s .  c  om*/

    BillingService billingService = (BillingService) Context.getService(BillingService.class);

    AmbulanceBill ambulanceBill = billingService.getAmbulanceBillById(ambulanceBillId);

    if ("void".equalsIgnoreCase(action)) {
        ambulanceBill.setVoided(true);
        ambulanceBill.setVoidedDate(new Date());
        for (AmbulanceBillItem item : ambulanceBill.getBillItems()) {
            item.setVoided(true);
            item.setVoidedDate(new Date());
        }
        billingService.saveAmbulanceBill(ambulanceBill);
        return "redirect:/module/billing/ambulanceBill.list?driverId=" + driverId;
    }

    ambulanceBill.setPrinted(false);

    // void old items and reset amount
    Map<Integer, AmbulanceBillItem> mapOldItems = new HashMap<Integer, AmbulanceBillItem>();
    for (AmbulanceBillItem item : ambulanceBill.getBillItems()) {
        item.setVoided(true);
        item.setVoidedDate(new Date());
        mapOldItems.put(item.getAmbulanceBillItemId(), item);
    }
    ambulanceBill.setAmount(BigDecimal.ZERO);

    Ambulance ambulance = null;
    Money itemAmount;
    Money totalAmount = new Money(BigDecimal.ZERO);
    AmbulanceBillItem item;
    for (Integer id : ambulanceIds) {

        ambulance = billingService.getAmbulanceById(id);
        BigDecimal amount = new BigDecimal(request.getParameter(id + "_amount"));
        itemAmount = new Money(amount);
        totalAmount = totalAmount.plus(itemAmount);

        Integer numberOfTrip = Integer.parseInt(request.getParameter(id + "_numOfTrip"));

        //ghanshyam 9-august-2012 New Requirement #333 [Billing]Edit ambulance bill with all details
        String patientName = (request.getParameter(id + "_patientName"));
        String receiptNumber = (request.getParameter(id + "_receiptNumber"));
        String origin = (request.getParameter(id + "_origin"));
        String destination = (request.getParameter(id + "_destination"));

        String sItemId = request.getParameter(id + "_itemId");

        if (sItemId != null) {
            item = mapOldItems.get(Integer.parseInt(sItemId));
            item.setVoided(false);
            item.setVoidedDate(null);
            item.setAmount(itemAmount.getAmount());
            item.setNumberOfTrip(numberOfTrip);
            //ghanshyam 9-august-2012 New Requirement #333 [Billing]Edit ambulance bill with all details
            item.setPatientName(patientName);
            item.setReceiptNumber(receiptNumber);
            item.setOrigin(origin);
            item.setDestination(destination);
        } else {
            item = new AmbulanceBillItem();
            item.setName(ambulance.getName());
            item.setCreatedDate(new Date());
            item.setAmbulance(ambulance);
            item.setAmbulanceBill(ambulanceBill);
            item.setAmount(itemAmount.getAmount());
            item.setNumberOfTrip(numberOfTrip);
            //ghanshyam 9-august-2012 New Requirement #333 [Billing]Edit ambulance bill with all details
            item.setPatientName(patientName);
            item.setReceiptNumber(receiptNumber);
            item.setOrigin(origin);
            item.setDestination(destination);
            ambulanceBill.addBillItem(item);
        }
    }
    ambulanceBill.setAmount(totalAmount.getAmount());
    ambulanceBill = billingService.saveAmbulanceBill(ambulanceBill);

    return "redirect:/module/billing/ambulanceBill.list?driverId=" + driverId + "&ambulanceBillId="
            + ambulanceBill.getAmbulanceBillId();
}

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

@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/rest/species", method = RequestMethod.POST)
@ResponseBody/*from w  w  w . j ava 2  s  . c om*/
public Object addSpecies(@Valid @RequestBody Species species, BindingResult result,
        @AuthenticationPrincipal AuthenticatedUser user, Locale locale, HttpServletResponse response) {
    log.info("Adding species. Name:" + species);
    if (result.hasErrors()) {
        response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
        return result.getAllErrors();
    }
    return speciesHandler.addSpecies(species, user, locale);
}

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

@RequestMapping(value = "/editar", method = RequestMethod.POST)
public String editar(@ModelAttribute("trimestre") Trimestre trimestre, BindingResult bindingResult,
        RedirectAttributes redirectAttributes, Model model) {
    trimestreValidator.validate(trimestre, bindingResult);
    if (bindingResult.hasErrors()) {
        log.warn("No se pudo actualizar trimestre. {}", bindingResult.getAllErrors());
        return "admin/trimestre/editar";
    }/*from w w  w .ja va2s  .c  o  m*/

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

From source file:mx.com.quadrum.contratos.controller.service.user.EmpleadoQuadrumController.java

@ResponseBody
@RequestMapping(value = "addContrato", method = RequestMethod.POST)
public String addContrato(@Valid @ModelAttribute("contrato") Contrato contrato, BindingResult result,
        HttpSession session) {/*  www. j a  v a2 s  .  com*/
    Usuario usuario = (Usuario) session.getAttribute("usuario");
    if (usuario == null) {
        return SESION_CADUCA;
    }
    if (result.hasErrors()) {
        for (ObjectError e : result.getAllErrors()) {
            System.out.println(e);
        }
        return ERROR_DATOS;
    }
    Firma firma = new Firma();
    firma.setContrato(contrato);
    firma.setContacto(contactoService.buscarPorId(contrato.getContacto().getId()));
    return contratoService.agregar(contrato, usuario, firma);
}

From source file:org.smigo.species.vernacular.VernacularController.java

@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/rest/vernacular", method = RequestMethod.POST)
@ResponseBody//from www .j ava 2 s  .  co  m
public Object addVernacular(@Valid @RequestBody Vernacular vernacular, BindingResult result,
        @AuthenticationPrincipal AuthenticatedUser user, Locale locale, HttpServletResponse response) {
    log.info("Adding vernacular:" + vernacular);
    if (result.hasErrors()) {
        response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
        return result.getAllErrors();
    }
    CrudResult review = vernacularHandler.addVernacular(vernacular, user, locale);
    if (review.getReview() == Review.MODERATOR) {
        response.setStatus(HttpStatus.ACCEPTED.value());
    }
    return review.getId();
}