Example usage for org.springframework.validation BindingResult getErrorCount

List of usage examples for org.springframework.validation BindingResult getErrorCount

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult getErrorCount.

Prototype

int getErrorCount();

Source Link

Document

Return the total number of errors.

Usage

From source file:io.ignitr.springboot.common.error.IgnitionErrorAttributes.java

/**
 * Adds field-level error messages to the error response.
 *
 * @param errorAttributes error attributes collection
 * @param requestAttributes request attributes collection
 *///from w w w. j av  a 2 s.  c o  m
private void addFieldErrors(Map<String, Object> errorAttributes, RequestAttributes requestAttributes) {
    Throwable error = getError(requestAttributes);

    // Checking to see if the exception contains JSR-303 bean validation errors
    BindingResult result = extractBindingResult(error);
    if (result != null) {
        if (result.getErrorCount() > 0) {
            List<IgnitionFieldError> fieldErrors = new ArrayList<>(result.getErrorCount());

            for (ObjectError objError : result.getAllErrors()) {
                String field = ((FieldError) objError).getField();
                String message = objError.getDefaultMessage();

                fieldErrors.add(new IgnitionFieldError(field, message));
            }

            errorAttributes.put("fieldErrors", fieldErrors);
        }
    }

    // Checking to see if the exception is an ignition compatible exception and thus could
    // potentially contain field-level errors
    if (error instanceof IgnitionException) {
        if (((IgnitionException) error).hasFieldErrors()) {
            errorAttributes.put("fieldErrors", ((IgnitionException) error).getFieldErrors());
        }
    }
}

From source file:org.encuestame.mvc.page.ForgetPasswordController.java

/**
 * Process Submit.//from w  w  w  . jav  a2  s. co  m
 *
 * @param req
 * @param challenge
 * @param response
 * @param user
 * @param result
 * @param status
 * @return
 * @throws EnMeNoResultsFoundException
 */
@RequestMapping(value = "/user/forgot", method = RequestMethod.POST)
public String forgotSubmitForm(HttpServletRequest req, ModelMap model,
        @RequestParam(value = "recaptcha_challenge_field", required = false) String challenge,
        @RequestParam(value = "recaptcha_response_field", required = false) String response,
        @ModelAttribute ForgotPasswordBean user, BindingResult result, SessionStatus status)
        throws EnMeNoResultsFoundException {
    log.info("recaptcha_challenge_field " + challenge);
    log.info("recaptcha_response_field " + response);
    log.info("result erros  " + result.getAllErrors().size());
    log.info("result erros  " + result.getErrorCount());
    final String email = user.getEmail() == null ? "" : user.getEmail();
    setCss(model, "user");
    if (!email.isEmpty()) {
        log.debug("email " + email);
        final ReCaptchaResponse reCaptchaResponse = getReCaptcha().checkAnswer(req.getRemoteAddr(), challenge,
                response);
        final ValidateOperations validation = new ValidateOperations(getSecurityService());
        boolean _isValidEmailFormat = validation.validateEmail(email);
        log.info("EMAIL FORMAT NOT VALID --> " + _isValidEmailFormat);
        if (_isValidEmailFormat) {
            final UserAccount userValidate = validation.checkifEmailExist(email);
            if (userValidate == null) {
                result.rejectValue("email", "secure.email.notvalid", new Object[] { user.getEmail() }, "");
            }
            log.info("reCaptchaResponse " + reCaptchaResponse.isValid());
            //validate reCaptcha
            validation.validateCaptcha(reCaptchaResponse, result);
            if (reCaptchaResponse.getErrorMessage() != null) {
                RequestSessionMap.getCurrent(req).put("resetError", Boolean.TRUE);
                RequestSessionMap.getCurrent(req).put("resetErrorMessage", reCaptchaResponse.getErrorMessage());
                log.fatal("reCaptcha Fatal Error: " + reCaptchaResponse.getErrorMessage());
            }
            log.info("result.hasErrors() " + result.hasErrors());
            if (result.hasErrors()) {
                return "forgot";
            } else {
                final String password = PasswordGenerator.getPassword(6);
                try {
                    /*
                     * Stuffs to change;
                     * 1. user should be to change own password, not auto generate
                     * 2. instead redirect to sign in page, should be to success page.
                     */
                    getSecurityService().renewPassword(
                            ConvertDomainBean.convertBasicSecondaryUserToUserBean(userValidate), password);
                } catch (EnMeException e) {
                    log.error("Error Renewd password " + e.getMessage());
                    return "forgot";
                }
                status.setComplete();
                log.info("password generated: " + password);
                final ForgotPasswordBean forgot = new ForgotPasswordBean();
                model.addAttribute("forgotPasswordBean", forgot);
                return "/user/checkyouremail";
            }
        } else {
            log.info("EMAIL FORMAT NOT VALID");
            result.rejectValue("email", "secure.email.notvalid", new Object[] { user.getEmail() }, "");
            return "forgot";
        }
    } else {
        result.rejectValue("email", "secure.email.emtpy", null, "");
        return "forgot";
    }
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * This is the entry point for the AJAX call to update the resource
 *///from www.  j ava  2  s  . c  o m
@SuppressWarnings("unchecked")
public ModelAndView updateDataResource(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    logger.info("Updating a resource...");
    debugRequestParams(request);
    ResourceDetail resource = new ResourceDetail();
    ServletRequestDataBinder binder = createBinder(request, resource);
    binder.bind(request);
    String businessKey = request.getParameter(REQUEST_BUSINESS_UDDI_KEY);
    BindingResult result = binder.getBindingResult();
    validateDataResource(resource, result);

    if (result.getErrorCount() == 0) {
        // it is always the last one, due to the fact that only one is ever submitted
        // although it's id may be something other than 0
        if (logger.isDebugEnabled()) {
            logger.debug("Resource name: " + resource.getName());
            logger.debug("Resource description: " + resource.getDescription());
        }
        uddiUtils.updateResource(resource, request.getParameter(REQUEST_BUSINESS_UDDI_KEY));
        return new ModelAndView(new RedirectView(
                request.getContextPath() + "/register/showDataResources?businessKey=" + businessKey));
    } else {
        logger.error(result.getAllErrors());
        // put the errors in the request
        Map<String, Object> data = new HashMap<String, Object>();
        data.putAll(referenceDataForResource(request, resource));
        data.put(RegistrationController.REQUEST_RESOURCE, resource);
        data.put(BindingResult.MODEL_KEY_PREFIX + RegistrationController.REQUEST_RESOURCE, result);
        List<String> beanProperties = retrieveReadonlyPropertiesForResource(resource);
        data.putAll(referenceDataForResourceList(request));
        data.put("readonlyProperties", beanProperties);
        return new ModelAndView("registrationResourceDetail", data);
    }
}

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

@RequestMapping(value = "/module/cohort/addcohortattributestype.form", method = RequestMethod.POST)
public String onSubmit(WebRequest request, HttpSession httpSession, ModelMap model,
        @RequestParam(required = false, value = "name") String attribute_type,
        @RequestParam(required = false, value = "description") String description,
        @ModelAttribute("cohortattributes") CohortAttributeType cohortattributes, BindingResult errors) {
    CohortService departmentService = Context.getService(CohortService.class);
    //PatientService patientService=Context.getService(PatientService.class);
    String voided = request.getParameter("voided");
    String format = request.getParameter("format");
    this.validator.validate(cohortattributes, errors);
    System.out.println("Before BR");
    if (errors.hasErrors()) {
        System.out.println("BR has errors: " + errors.getErrorCount());
        System.out.println(errors.getAllErrors());

        model.addAttribute("cohortattributes", new CohortAttributeType());
        List<String> formats = new ArrayList<String>(
                FieldGenHandlerFactory.getSingletonInstance().getHandlers().keySet());
        formats.add("java.lang.Character");
        formats.add("java.lang.Integer");
        formats.add("java.lang.Float");
        formats.add("java.lang.Boolean");
        model.addAttribute("formats", formats);
        return "/module/cohort/addcohortattributestype";
    }/*from  w  w  w .  ja  v a2 s . c  o m*/
    if (attribute_type.length() > 20) {
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "attribute type cannot be greater than 20");
    } else {
        cohortattributes.setFormat(format);
        departmentService.saveCohort(cohortattributes);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "insertion success");
    }
    return null;
}

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  va  2  s . c om
    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 w w  . j a  va 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   ww w  . j a  va  2 s. 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  ava  2s.  c o  m*/
    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.orcid.frontend.web.forms.validate.ChangePersonalInfoValidatorTest.java

@Test
public void lengthGreaterThan100NotAcceptedForBio() throws Exception {
    String fiveThousandAndOneChars = StringUtils.repeat("a", 5001);
    assertTrue(fiveThousandAndOneChars.length() == 5001);

    ChangePersonalInfoForm form = new ChangePersonalInfoForm();
    form.setFirstName("firstName");
    form.setLastName("lastName");
    form.setBiography(fiveThousandAndOneChars);

    BindingResult bindingResult = new BeanPropertyBindingResult(form, "changePersonalInfoForm");

    localValidatorFactoryBean.validate(form, bindingResult);
    String tooLong = resolveFieldErrorMessage(bindingResult, "biography");
    assertEquals("Should be 1 error", 1, bindingResult.getErrorCount());
    assertEquals("The maximum length for biography is 5000 characters, including line breaks", tooLong);

    String fiveThousandChars = StringUtils.repeat("z", 5000);
    form.setBiography(fiveThousandChars);
    bindingResult = new BeanPropertyBindingResult(form, "changePersonalInfoForm");
    localValidatorFactoryBean.validate(form, bindingResult);
    assertEquals("Should be valid", 0, bindingResult.getErrorCount());

}

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 {/*ww  w  .  j av  a 2 s .c om*/
            map.put("message", "No errors");
        }
    } else {
        map.put("message", error.getMessage());
    }
}