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.openmrs.module.cohort.web.controller.AddCohortController.java

@RequestMapping(value = "module/cohort/addcohort.form", method = RequestMethod.POST)
public String onSubmit(WebRequest request, HttpSession httpSession, HttpServletRequest request1,
        @RequestParam(required = false, value = "name") String cohort_name,
        @RequestParam(required = false, value = "description") String description,
        @RequestParam(required = false, value = "startDate") String start_date,
        @RequestParam(required = false, value = "endDate") String end_date,
        @ModelAttribute("cohortmodule") CohortM cohortmodule, BindingResult errors, ModelMap model) {
    CohortType cohort1 = new CohortType();
    CohortProgram prg = new CohortProgram();
    Location loc = new Location();
    String cohort_program = request.getParameter("format1");
    String cohort_type_name = request.getParameter("format");
    String location = request.getParameter("location");
    CohortService departmentService = Context.getService(CohortService.class);
    if (!Context.isAuthenticated()) {
        errors.reject("Required");
    }/* w ww.  j  a  v a  2  s.  c o  m*/
    this.validator.validate(cohortmodule, errors);
    System.out.println("Before BR");
    if (errors.hasErrors()) {
        System.out.println("BR has errors: " + errors.getErrorCount());
        System.out.println(errors.getAllErrors());
        return "/module/cohort/addcohort";
    } else {
        /*try {
        java.util.Date start = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH).parse(start_date);
         java.util.Date end = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH).parse(end_date);
         if (start.compareTo(end) < 0 || start.compareTo(end)==0) {*/
        //cohortmodule.setLocation(location);
        List<CohortProgram> list2 = departmentService.findCohortProgram(cohort_program);
        List<CohortType> cohorttype1 = departmentService.findCohortType(cohort_type_name);
        LocationService service = Context.getLocationService();
        List<Location> formats = service.getLocations(location);
        for (int j = 0; j < formats.size(); j++) {
            loc = formats.get(j);
        }
        for (int i = 0; i < cohorttype1.size(); i++) {
            cohort1 = cohorttype1.get(i);
        }
        for (int a = 0; a < list2.size(); a++) {
            prg = list2.get(a);
        }
        cohortmodule.setCohortProgram(prg);
        cohortmodule.setClocation(loc);
        cohortmodule.setCohortType(cohort1);
        departmentService.saveCohort(cohortmodule);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "insertion success");
        model.addAttribute("locations", formats);
        model.addAttribute("formats", cohorttype1);
        model.addAttribute("formats1", list2);
        model.addAttribute("cohortmodule", cohortmodule);
        if ("Next".equalsIgnoreCase(request.getParameter("next"))) {
            departmentService.saveCohort(cohortmodule);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "insertion success");
            String redirectUrl = "/module/cohort/addcohortattributes.form?ca=" + cohortmodule.getCohortId();
            return "redirect:" + redirectUrl;
        }

    }
    //}
    /*catch (ParseException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }     
    }*/
    return null;
}

From source file:org.openmrs.module.cohort.web.controller.AddCohortProgramController.java

@RequestMapping(value = "/module/cohort/addcohortprogram.form", method = RequestMethod.POST)
public String onSearch(WebRequest request, HttpSession httpSession, ModelMap model,
        @RequestParam(required = false, value = "name") String cohort_name,
        @RequestParam(required = false, value = "description") String description,
        @ModelAttribute("cohortprogram") CohortProgram cp, BindingResult errors) {
    CohortService departmentService = Context.getService(CohortService.class);
    if (!Context.isAuthenticated()) {
        errors.reject("Required");
    }/*from   w ww .  ja  v a 2 s. com*/
    this.validator.validate(cp, errors);
    System.out.println("Before BR");
    if (errors.hasErrors()) {
        System.out.println("BR has errors: " + errors.getErrorCount());
        System.out.println(errors.getAllErrors());
        return "/module/cohort/addcohortprogram";
    }
    if (cohort_name.length() > 20) {
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "name cannot be greater than 20");
    } else {
        departmentService.saveCohortProgram(cp);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "insertion success");
    }
    return null;
}

From source file:org.openmrs.module.cohort.web.controller.AddCohortTypeController.java

@RequestMapping(value = "/module/cohort/addcohorttype.form", method = RequestMethod.POST)
public String onSearch(WebRequest request, HttpSession httpSession, ModelMap model,
        @RequestParam(required = false, value = "name") String cohort_name,
        @RequestParam(required = false, value = "description") String description,
        @ModelAttribute("cohorttype") CohortType cohorttype, BindingResult errors) {
    CohortService departmentService = Context.getService(CohortService.class);
    if (!Context.isAuthenticated()) {
        errors.reject("Required");
    }//from   w  w w  .  jav a  2s.  c o m
    this.validator.validate(cohorttype, errors);
    System.out.println("Before BR");
    if (errors.hasErrors()) {
        System.out.println("BR has errors: " + errors.getErrorCount());
        System.out.println(errors.getAllErrors());
        return "/module/cohort/addcohorttype";
    }
    if (cohort_name.length() > 20) {
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "name cannot be greater than 20");
    } else {
        departmentService.saveCohort(cohorttype);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "insertion success");
    }
    return null;
}

From source file:org.openmrs.module.cohort.web.controller.AddRoleController.java

@RequestMapping(value = "module/cohort/arole.form", method = RequestMethod.POST)
public String onSubmit(WebRequest request, HttpSession httpSession, HttpServletRequest request1,
        @RequestParam(required = false, value = "name") String cohort_name,
        @ModelAttribute("cohortrole") CohortRole cohortrole, BindingResult errors, ModelMap model) {
    CohortRole cr = new CohortRole();
    CohortType cohort1 = new CohortType();
    String cohort_type_name = request.getParameter("format");
    CohortService departmentService = Context.getService(CohortService.class);
    if (!Context.isAuthenticated()) {
        errors.reject("Required");
    }/* w w  w.  j  a va  2 s. c  om*/
    this.validator.validate(cohortrole, errors);
    System.out.println("Before BR");
    if (errors.hasErrors()) {
        System.out.println("BR has errors: " + errors.getErrorCount());
        System.out.println(errors.getAllErrors());
        return "/module/cohort/arole";
    }
    if (cohort_name.length() > 20) {
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "name cannot be greater than 20");
    } else {
        List<CohortType> cohorttype1 = departmentService.findCohortType(cohort_type_name);
        for (int i = 0; i < cohorttype1.size(); i++) {
            cohort1 = cohorttype1.get(i);
        }
        cohortrole.setCohortType(cohort1);
        departmentService.saveCohortRole(cohortrole);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "insertion success");
        model.addAttribute("formats", cohorttype1);
    }
    //}
    /*catch (ParseException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }     
    }*/
    return null;
}

From source file:org.openmrs.module.registrationapp.page.controller.EditPatientContactInfoPageController.java

/**
 * @should void the old person address and replace it with a new one when it is edited
 * @should void the old person address and replace it with a new one when it is edited
 * @should not void the existing address if there are no changes
 *//*w w w .  j  av  a2 s . co m*/
public String post(UiSessionContext sessionContext, PageModel model,
        @RequestParam("patientId") @BindParams Patient patient, @BindParams PersonAddress address,
        @SpringBean("patientService") PatientService patientService, @RequestParam("appId") AppDescriptor app,
        @RequestParam("returnUrl") String returnUrl,
        @SpringBean("adminService") AdministrationService administrationService, HttpServletRequest request,
        @SpringBean("messageSourceService") MessageSourceService messageSourceService, Session session,
        @SpringBean("patientValidator") PatientValidator patientValidator, UiUtils ui) throws Exception {

    sessionContext.requireAuthentication();

    if (patient.getPersonAddress() != null && address != null) {
        PersonAddress currentAddress = patient.getPersonAddress();
        if (!currentAddress.equalsContent(address)) {
            //void the old address and replace it with the new one
            patient.addAddress(address);
            currentAddress.setVoided(true);
        }
    }

    NavigableFormStructure formStructure = RegisterPatientFormBuilder.buildFormStructure(app);

    BindingResult errors = new BeanPropertyBindingResult(patient, "patient");
    patientValidator.validate(patient, errors);
    RegistrationAppUiUtils.validateLatitudeAndLongitudeIfNecessary(address, errors);

    if (formStructure != null) {
        RegisterPatientFormBuilder.resolvePersonAttributeFields(formStructure, patient,
                request.getParameterMap());
    }

    if (!errors.hasErrors()) {
        try {
            //The person address changes get saved along as with the call to save patient
            patientService.savePatient(patient);
            InfoErrorMessageUtil.flashInfoMessage(request.getSession(),
                    ui.message("registrationapp.editContactInfoMessage.success", patient.getPersonName()));

            return "redirect:" + returnUrl;
        } catch (Exception e) {
            log.warn("Error occurred while saving patient's contact info", e);
            session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE,
                    "registrationapp.save.fail");
        }

    } else {
        model.addAttribute("errors", errors);
        StringBuffer errorMessage = new StringBuffer(
                messageSourceService.getMessage("error.failed.validation"));
        errorMessage.append("<ul>");
        for (ObjectError error : errors.getAllErrors()) {
            errorMessage.append("<li>");
            errorMessage.append(messageSourceService.getMessage(error.getCode(), error.getArguments(),
                    error.getDefaultMessage(), null));
            errorMessage.append("</li>");
        }
        errorMessage.append("</ul>");
        session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, errorMessage.toString());
    }

    addModelAttributes(model, patient, formStructure, administrationService, returnUrl, app);
    //redisplay the form
    return null;
}

From source file:org.openmrs.module.registrationapp.page.controller.EditPatientDemographicsPageController.java

/**
 * @should void the old person name and replace it with a new one when it is edited
 * @should not void the existing name if there are no changes in the name
 *//* w w w . j a  v a2s . co m*/
public String post(UiSessionContext sessionContext, PageModel model,
        @SpringBean("patientService") PatientService patientService,
        @RequestParam("patientId") @BindParams Patient patient, @BindParams PersonName name,
        @RequestParam("returnUrl") String returnUrl,
        @SpringBean("nameTemplateGivenFamily") NameTemplate nameTemplate, HttpServletRequest request,
        @SpringBean("messageSourceService") MessageSourceService messageSourceService, Session session,
        @SpringBean("patientValidator") PatientValidator patientValidator, UiUtils ui) throws Exception {

    sessionContext.requireAuthentication();

    if (patient.getPersonName() != null && name != null) {
        PersonName currentName = patient.getPersonName();
        if (!currentName.equalsContent(name)) {
            //void the old name and replace it with the new one
            patient.addName(name);
            currentName.setVoided(true);
        }
    }

    BindingResult errors = new BeanPropertyBindingResult(patient, "patient");
    patientValidator.validate(patient, errors);

    if (!errors.hasErrors()) {
        try {
            patientService.savePatient(patient);
            InfoErrorMessageUtil.flashInfoMessage(request.getSession(),
                    ui.message("registrationapp.editDemographicsMessage.success", patient.getPersonName()));

            return "redirect:" + returnUrl;
        } catch (Exception e) {
            log.warn("Error occurred while saving patient demographics", e);
            session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE,
                    "registrationapp.save.fail");
        }

    } else {
        model.addAttribute("errors", errors);
        StringBuffer errorMessage = new StringBuffer(
                messageSourceService.getMessage("error.failed.validation"));
        errorMessage.append("<ul>");
        for (ObjectError error : errors.getAllErrors()) {
            errorMessage.append("<li>");
            errorMessage.append(messageSourceService.getMessage(error.getCode(), error.getArguments(),
                    error.getDefaultMessage(), null));
            errorMessage.append("</li>");
        }
        errorMessage.append("</ul>");
        session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, errorMessage.toString());
    }

    model.addAttribute("patient", patient);
    model.addAttribute("nameTemplate", nameTemplate);
    model.addAttribute("returnUrl", returnUrl);
    //redisplay the form
    return null;
}

From source file:org.springframework.boot.autoconfigure.web.BasicErrorController.java

protected void addMessage(Map<String, Object> map, Throwable error) {
    if (error instanceof BindingResult) {
        BindingResult result = (BindingResult) error;
        if (result.getErrorCount() > 0) {
            map.put("errors", result.getAllErrors());
            map.put("message", "Validation failed for object='" + result.getObjectName() + "'. Error count: "
                    + result.getErrorCount());
        } else {/* w ww  .  j  a v a2s. c o  m*/
            map.put("message", "No errors");
        }
    } else {
        map.put("message", error.getMessage());
    }
}

From source file:org.springframework.boot.bind.PropertiesConfigurationFactory.java

private void validate(RelaxedDataBinder dataBinder) throws BindException {
    dataBinder.validate();/*from   w  w  w . j  a  v  a2 s .c o m*/
    BindingResult errors = dataBinder.getBindingResult();
    if (errors.hasErrors()) {
        this.logger.error("Properties configuration failed validation");
        for (ObjectError error : errors.getAllErrors()) {
            this.logger.error(this.messageSource != null
                    ? this.messageSource.getMessage(error, Locale.getDefault()) + " (" + error + ")"
                    : error);
        }
        if (this.exceptionIfInvalid) {
            throw new BindException(errors);
        }
    }
}

From source file:org.springframework.boot.bind.YamlConfigurationFactory.java

private void validate() throws BindException {
    BindingResult errors = new BeanPropertyBindingResult(this.configuration, "configuration");
    this.validator.validate(this.configuration, errors);
    if (errors.hasErrors()) {
        this.logger.error("YAML configuration failed validation");
        for (ObjectError error : errors.getAllErrors()) {
            this.logger.error(this.messageSource != null
                    ? this.messageSource.getMessage(error, Locale.getDefault()) + " (" + error + ")"
                    : error);// ww w.j  a  va  2s. c o m
        }
        if (this.exceptionIfInvalid) {
            BindException summary = new BindException(errors);
            throw summary;
        }
    }
}

From source file:org.springframework.faces.mvc.bind.ReverseDataBinder.java

/**
 * Perform the reverse bind on the <tt>dataBinder</tt> provided in the constructor. Note: Calling with method will
 * also trigger a <tt>bind</tt> operation on the <tt>dataBinder</tt>. This method returns {@link PropertyValues}
 * containing a name/value pairs for each property that can be bound. Property values are encoded as Strings using
 * the property editors bound to the original dataBinder.
 * @return property values that could be re-bound using the data binder
 * @throws IllegalStateException if the target object values cannot be bound
 *//*ww  w . j a  v  a2 s.  c om*/
public PropertyValues reverseBind() {
    Assert.notNull(dataBinder.getTarget(),
            "ReverseDataBinder.reverseBind can only be used with a DataBinder that has a target object");
    MutablePropertyValues rtn = new MutablePropertyValues();
    BeanWrapper target = PropertyAccessorFactory.forBeanPropertyAccess(dataBinder.getTarget());
    PropertyDescriptor[] propertyDescriptors = target.getPropertyDescriptors();

    BeanWrapper defaultValues = null;
    if (skipDefaultValues) {
        defaultValues = newDefaultTargetValues(dataBinder.getTarget());
    }

    for (int i = 0; i < propertyDescriptors.length; i++) {
        PropertyDescriptor property = propertyDescriptors[i];
        String propertyName = getPropertyName(property);
        Object propertyValue = target.getPropertyValue(propertyName);

        if (isSkippedProperty(property)) {
            continue;
        }

        if (!isMutableProperty(property)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Ignoring '" + propertyName + "' due to missing read/write methods");
            }
            continue;
        }

        if (defaultValues != null
                && ObjectUtils.nullSafeEquals(defaultValues.getPropertyValue(propertyName), propertyValue)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Skipping '" + propertyName + "' as property contains default value");
            }
            continue;
        }

        // Find a property editor
        PropertyEditorRegistrySupport propertyEditorRegistrySupport = null;
        if (target instanceof PropertyEditorRegistrySupport) {
            propertyEditorRegistrySupport = (PropertyEditorRegistrySupport) target;
        }
        PropertyEditor propertyEditor = findEditor(propertyEditorRegistrySupport, target.getWrappedInstance(),
                target.getPropertyType(propertyName), property);

        // Convert and store the value
        String convertedPropertyValue = convertToStringUsingPropertyEditor(propertyValue, propertyEditor);
        if (convertedPropertyValue != null) {
            rtn.addPropertyValue(propertyName, convertedPropertyValue);
        }
    }

    dataBinder.bind(rtn);
    BindingResult bindingResult = dataBinder.getBindingResult();
    if (bindingResult.hasErrors()) {
        throw new IllegalStateException("Unable to reverse bind from target '" + dataBinder.getObjectName()
                + "', the properties '" + rtn + "' will result in binding errors when re-bound "
                + bindingResult.getAllErrors());
    }
    return rtn;
}