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.easyj.rest.view.EasyView.java

public void setResult(BindingResult result) {
    if (this.result != null) {
        for (ObjectError error : result.getAllErrors()) {
            this.result.addError(error);
        }/*from  w ww  . j ava2  s.  com*/
    } else {
        this.result = result;
    }
}

From source file:com.netflix.genie.web.controllers.GenieExceptionMapperUnitTests.java

/**
 * Test method argument not valid exceptions.
 *
 * @throws IOException on error//from  w ww.j a v a2 s  .  co m
 */
@Test
@SuppressFBWarnings(value = "DM_NEW_FOR_GETCLASS", justification = "It's needed for the test")
public void canHandleMethodArgumentNotValidExceptions() throws IOException {
    // Method is a final class so can't mock it. Just use the current method.
    final Method method = new Object() {
    }.getClass().getEnclosingMethod();
    final MethodParameter parameter = Mockito.mock(MethodParameter.class);
    Mockito.when(parameter.getMethod()).thenReturn(method);

    final BindingResult bindingResult = Mockito.mock(BindingResult.class);
    Mockito.when(bindingResult.getAllErrors()).thenReturn(Lists.newArrayList());

    final MethodArgumentNotValidException exception = new MethodArgumentNotValidException(parameter,
            bindingResult);

    this.mapper.handleMethodArgumentNotValidException(this.response, exception);
    Mockito.verify(this.response, Mockito.times(1))
            .sendError(Mockito.eq(HttpStatus.PRECONDITION_FAILED.value()), Mockito.anyString());
    Mockito.verify(counterId, Mockito.times(1)).withTag(MetricsConstants.TagKeys.EXCEPTION_CLASS,
            exception.getClass().getCanonicalName());
    Mockito.verify(counter, Mockito.times(1)).increment();
}

From source file:com.trlogic.wlagent.web.MessageController.java

@PostMapping
public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) {
    if (result.hasErrors()) {
        return new ModelAndView("messages/form", "formErrors", result.getAllErrors());
    }//from   w  ww.  j  a v  a  2 s.  c  o m
    message = this.messageRepository.save(message);
    redirect.addFlashAttribute("globalMessage", "Successfully created a new message");
    return new ModelAndView("redirect:/{message.id}", "message.id", message.getId());
}

From source file:org.openmrs.module.admintoolsui.page.controller.account.AccountPageController.java

private void sendErrorMessage(BindingResult errors, MessageSource messageSource, HttpServletRequest request) {
    List<ObjectError> allErrors = errors.getAllErrors();
    String message = getMessageErrors(messageSource, allErrors);
    request.getSession().setAttribute(EmrConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, message);
}

From source file:org.parancoe.basicWebApp.controllers.PeopleEditController.java

@RequestMapping
protected String update(@ModelAttribute("person") @Valid Person person, BindingResult result,
        SessionStatus status) {/*from w w  w .j  a v a 2 s  .  c  om*/
    try {
        if (result.hasErrors()) {
            logger.error("Result of validation has errors (" + result.getAllErrors().toString() + ")");
            return "people/edit";
        } else {
            personDao.store(person);
            logger.info("Stored the person (" + person + ")");
            status.setComplete();
            return "redirect:list.html";
        }
    } catch (Exception e) {
        logger.error("Problema salvando Utente " + person, e);
        result.reject("error.generic");
        return "people/edit";
    }
}

From source file:eu.agilejava.mvc.HelloController.java

@RequestMapping(value = "hello", method = POST)
public ModelAndView formPost(@ModelAttribute("form") @Validated HelloBean form, BindingResult bindingResult) {

    if (bindingResult.hasErrors()) {

        Map<String, Object> errorModel = new HashMap<>();
        ObjectError error = bindingResult.getAllErrors().iterator().next();
        errorModel.put("property", ((FieldError) error).getField());
        errorModel.put("value", ((FieldError) error).getRejectedValue());
        errorModel.put("message", error.getDefaultMessage());

        bindingResult.getAllErrors().stream().forEach(v -> {
            errorModel.put(((FieldError) v).getField(), v.getDefaultMessage());
        });/*w  w w .  jav  a 2  s.  com*/

        ModelAndView mv = new ModelAndView("form", errorModel);

        return mv;
    }

    Map<String, Object> helloModel = new HashMap<>();
    helloModel.put("name", form.getFirstName() + " " + form.getLastName());

    ModelAndView mv = new ModelAndView("hello", helloModel);

    return mv;
}

From source file:com.dub.skoolie.web.controller.system.schedule.events.SystemSchoolEventController.java

@RequestMapping(value = "/system/schedule/events/school", method = RequestMethod.POST)
public ModelAndView addSchoolEvent(@Valid SchoolEventBean schoolEventBean, BindingResult result, Model model,
        HttpServletRequest request) {/*from   w ww. j  a  va 2  s .c  om*/
    String referrer = request.getHeader("Referer");
    if (result.hasErrors()) {
        for (ObjectError err : result.getAllErrors()) {
            System.out.println(err.getDefaultMessage());
        }
        if (!referrer.equals("/system/schedule/events/school")) {
            return new ModelAndView("redirect:" + referrer);
        }
        return new ModelAndView("system/schedule/events/index");
    }
    uiSchoolEventServiceImpl.addSchoolEvent(schoolEventBean);
    return new ModelAndView("system/schedule/events/index");
}

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

@RequestMapping(value = "/pass", params = "form", method = RequestMethod.POST)
public ModelAndView changePass(User user, BindingResult bindingResult, Principal principal,
        RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        return new ModelAndView("account", "formErrors", bindingResult.getAllErrors());
    }// w ww .j av a  2 s.c om
    User currentUser = userRepo.findBySsoId(principal.getName());
    currentUser.setPassword(passEncoder.encode(user.getPassword()));
    userRepo.save(currentUser);
    redirectAttributes.addFlashAttribute("globalMessage", "Password changed");
    return new ModelAndView("redirect:/account");
}

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

@RequestMapping(value = "/details", params = "form", method = RequestMethod.POST)
public ModelAndView changeDetails(User user, BindingResult bindingResult, Principal principal,
        RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        return new ModelAndView("account", "formErrors", bindingResult.getAllErrors());
    }//from   w w w.j  a v a2  s  .c om
    User currentUser = userRepo.findBySsoId(principal.getName());
    currentUser.setEmail(user.getEmail());
    currentUser.setFirstName(user.getFirstName());
    currentUser.setLastName(user.getLastName());
    userRepo.save(currentUser);
    redirectAttributes.addFlashAttribute("globalMessage", "Details changed");
    return new ModelAndView("redirect:/account");
}

From source file:org.openmrs.module.hospitalcore.web.controller.concept.DiagnosisImporterController.java

@RequestMapping(method = RequestMethod.POST)
public String create(UploadFile uploadFile, BindingResult result, Model model) {
    if (result.hasErrors()) {
        //ghanshyam 25/06/2012 tag BC_IMPOSSIBLE_CAST code Error error = (Error) obj

        for (ObjectError obj : result.getAllErrors()) {
            ObjectError error = (ObjectError) obj;
            System.err.println("Error: " + error.toString());
        }// w  w  w  .  j a  v a2s . c  o m
        return "/module/hospitalcore/concept/uploadForm";
    }

    System.out.println("Begin importing");
    Integer diagnosisNo = 0;
    try {
        HospitalCoreService hcs = (HospitalCoreService) Context.getService(HospitalCoreService.class);
        diagnosisNo = hcs.importConcepts(uploadFile.getDiagnosisFile().getInputStream(),
                uploadFile.getMappingFile().getInputStream(), uploadFile.getSynonymFile().getInputStream());
        model.addAttribute("diagnosisNo", diagnosisNo);
        System.out.println("Diagnosis imported " + diagnosisNo);
    } catch (Exception e) {
        e.printStackTrace();
        model.addAttribute("fail", true);
        model.addAttribute("error", e.toString());
    }

    return "/module/hospitalcore/concept/uploadForm";
}