Example usage for org.springframework.validation BindingResult getFieldErrors

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

Introduction

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

Prototype

List<FieldError> getFieldErrors();

Source Link

Document

Get all errors associated with a field.

Usage

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractTenantController.java

protected void parseResult(BindingResult result, ModelMap map) {
    if (result.getFieldErrors().size() > 0) {
        List<String> errorMsgList = new ArrayList<String>();
        for (FieldError fieldError : result.getFieldErrors()) {
            String fieldName = fieldError.getField();
            if (fieldName.contains(".")) {
                fieldName = fieldName.substring(fieldName.lastIndexOf(".") + 1);
            }/*from www .  j av a  2 s  .  c o m*/
            errorMsgList.add(fieldName + " field value '" + fieldError.getRejectedValue() + "' is not valid.");
        }

        map.addAttribute("errorMsgList", errorMsgList);
        map.addAttribute("errormsg", true);
    }
}

From source file:com.jd.survey.web.settings.QuestionController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@RequestParam(value = "_proceed", required = false) String proceed,
        @Valid Question question, BindingResult bindingResult, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("update(): handles PUT");
    try {//from  w ww.j  ava  2  s  . co m
        //User user = userService.user_findByLogin(principal.getName());
        String login = principal.getName();
        User user = userService.user_findByLogin(login);

        //SurveyDefinitionPage surveyDefinitionPage = surveySettingsService.surveyDefinitionPage_findById(surveyDefinitionPageId); surveySettingsService.question_findById(question.getId()).getPage().getSurveyDefinition().getId()
        //Check if the user is authorized
        if (!securityService.userIsAuthorizedToManageSurvey(question.getPage().getSurveyDefinition().getId(),
                user)
                && !securityService.userBelongsToDepartment(
                        question.getPage().getSurveyDefinition().getDepartment().getId(), user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }
        if (proceed != null) {
            if (bindingResult.hasErrors()) {
                populateEditForm(uiModel, question, user);
                log.info("-------------------------------------------"
                        + bindingResult.getFieldErrors().toString());
                return "settings/questions/update";
            }
            if (!surveySettingsService.question_ValidateDateRange(question)) {
                populateEditForm(uiModel, question, user);
                bindingResult.rejectValue("dateMinimum", "date_format_validation_range");
                return "settings/questions/update";
            }
            if (!surveySettingsService.question_ValidateMinMaxDoubleValues(question)) {
                populateEditForm(uiModel, question, user);
                bindingResult.rejectValue("decimalMinimum", "field_min_invalid");
                return "settings/questions/update";
            }
            if (!surveySettingsService.question_ValidateMinMaxValues(question)) {
                populateEditForm(uiModel, question, user);
                bindingResult.rejectValue("integerMinimum", "field_min_invalid");
                return "settings/questions/update";
            }
            if (question.getSuportsOptions()) {
                //If user wants to modify and existent question without options to Rating type, then use the default values
                int NumberOfQuestionOptions = 0;
                Set<QuestionOption> qOpts = surveySettingsService
                        .questionOption_findByQuestionId(question.getId());
                for (QuestionOption q : qOpts) {
                    NumberOfQuestionOptions++;
                }
                if ((question.getType().toString() == "SMILEY_FACES_RATING"
                        || question.getType().toString() == "STAR_RATING") && NumberOfQuestionOptions != 5) {
                    log.info(
                            "Removing Question Options since the amount of Questions Options for Rating Type cannot be longer than 5 Qoptions");
                    surveySettingsService.questionOption_removeQuestionOptionsByQuestionId(question.getId());
                    SortedSet<QuestionOption> options = new TreeSet<QuestionOption>();
                    options.add(new QuestionOption(question, (short) 1, "1", messageSource
                            .getMessage(EXTREMELY_UNSATISFIED_LABEL, null, LocaleContextHolder.getLocale())));
                    options.add(new QuestionOption(question, (short) 2, "2", messageSource
                            .getMessage(UNSATISFIED_LABEL, null, LocaleContextHolder.getLocale())));
                    options.add(new QuestionOption(question, (short) 3, "3",
                            messageSource.getMessage(NEUTRAL_LABEL, null, LocaleContextHolder.getLocale())));
                    options.add(new QuestionOption(question, (short) 4, "4",
                            messageSource.getMessage(SATISFIED_LABEL, null, LocaleContextHolder.getLocale())));
                    options.add(new QuestionOption(question, (short) 5, "5", messageSource
                            .getMessage(EXTREMELY_SATISFIED_LABEL, null, LocaleContextHolder.getLocale())));
                    //Adding default values to Rating Type Question
                    log.info("Adding default values to Rating Type Question");
                    question = surveySettingsService.question_merge(question, options);
                    uiModel.asMap().clear();
                    return "settings/questions/saved";
                } else {
                    Policy questionTextPolicy = Policy
                            .getInstance(this.getClass().getResource(POLICY_FILE_LOCATION));
                    AntiSamy emailAs = new AntiSamy();
                    CleanResults crQuestionText = emailAs.scan(question.getQuestionText(), questionTextPolicy);
                    question.setQuestionText(crQuestionText.getCleanHTML());

                    Policy questionTipPolicy = Policy
                            .getInstance(this.getClass().getResource(POLICY_FILE_LOCATION));
                    AntiSamy completedSurveyAs = new AntiSamy();
                    CleanResults crQuestionTip = completedSurveyAs.scan(question.getTip(), questionTipPolicy);
                    question.setTip(crQuestionTip.getCleanHTML());

                    question = surveySettingsService.question_merge(question);
                    uiModel.asMap().clear();
                    return "settings/questions/saved";
                }
            }

            question = surveySettingsService.question_merge(question);
            uiModel.asMap().clear();
            return "settings/questions/saved";

        } else {
            return "redirect:/settings/surveyDefinitions/" + encodeUrlPathSegment(
                    question.getPage().getSurveyDefinition().getId().toString(), httpServletRequest);
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.octanner.controllers.AbstractProductConfigController.java

protected Map<String, FieldError> handleValidationErrorsBeforeUpdate(final ConfigurationData configData,
        final BindingResult bindingResult) {
    Map<String, FieldError> userInputToRestore;
    final int capacity = (int) (bindingResult.getErrorCount() / 0.75) + 1;
    userInputToRestore = new HashMap(capacity);
    for (final FieldError error : bindingResult.getFieldErrors()) {
        final String fieldPath = error.getField();
        final PathExtractor extractor = new PathExtractor(fieldPath);
        final int groupIndex = extractor.getGroupIndex();
        final int csticIndex = extractor.getCsticsIndex();
        UiGroupData group = configData.getGroups().get(groupIndex);
        for (int i = 0; i < extractor.getSubGroupCount(); i++) {
            group = group.getSubGroups().get(extractor.getSubGroupIndex(i));
        }/*from w  ww.j  a  va  2  s  .com*/
        final CsticData cstic = group.getCstics().get(csticIndex);
        userInputToRestore.put(cstic.getKey(), error);
        cstic.setValue(cstic.getLastValidValue());
        cstic.setAdditionalValue("");
    }
    return userInputToRestore;
}

From source file:com.vmware.bdd.rest.advice.RestValidationErrorHandler.java

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)//from   w w  w  . j  a  v a  2 s .com
@ResponseBody
public BddErrorMessage processValidationError(MethodArgumentNotValidException ex) {
    BindingResult result = ex.getBindingResult();
    List<FieldError> fieldErrors = result.getFieldErrors();

    BddException validationException = new ValidationException(processFieldErrors(fieldErrors).getErrors());
    return ServerErrorMessages.fromException(validationException);
}

From source file:com.zb.app.web.controller.login.LoginController.java

/**
 * ,???,?//from   w ww  .  j a  va 2s . co  m
 * 
 * @param travelCompanyVO
 * @param travelMemberVO
 * @return
 */
@RequestMapping(value = "/doRegister.htm")
@TokenPolicy(remove = true, data = ",token,??!")
public ModelAndView doRegister(@Valid TravelCompanyVO travelCompanyVO, @Valid TravelMemberVO travelMemberVO,
        BindingResult bindingResult, ModelAndView mav) {
    Map<String, Object> model = new HashMap<String, Object>();
    if (bindingResult.hasErrors()) {
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            model.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return createErrorJsonMav("!", model);
    }

    // ?
    TravelCompanyDO travelCompanyDO = new TravelCompanyDO();
    BeanUtils.copyProperties(travelCompanyDO, travelCompanyVO);
    travelCompanyDO.setcState(0);
    travelCompanyDO.setcSpell(PinyinParser.converterToFirstSpell(travelCompanyDO.getcName()));
    companyService.insert(travelCompanyDO);

    // 
    TravelMemberDO travelMemberDO = new TravelMemberDO();
    BeanUtils.copyProperties(travelMemberDO, travelMemberVO);
    travelMemberDO.setmState(0);
    travelMemberDO.setmPassword(EncryptBuilder.getInstance().encrypt(travelMemberVO.getmPassword()));
    travelMemberDO.setcId(travelCompanyDO.getcId());
    travelMemberDO.setmUserName(StringUtils.lowerCase(travelMemberVO.getmUserName()));
    travelMemberDO.setmType(MemberTypeEnum.SUPERADMIN.getValue());
    memberService.insert(travelMemberDO);
    Map<String, String> map = new HashMap<String, String>();
    map.put("cName", travelCompanyDO.getcName());
    map.put("mUserName", travelMemberDO.getmUserName());
    map.put("mEmail", travelMemberDO.getmEmail());
    return createSuccessJsonMav("?!", map);
}

From source file:de.hybris.platform.sap.productconfig.frontend.controllers.AbstractProductConfigController.java

protected Map<String, FieldError> handleValidationErrorsBeforeUpdate(final ConfigurationData configData,
        final BindingResult bindingResult) {
    Map<String, FieldError> userInputToRestore;
    final int capacity = (int) (bindingResult.getErrorCount() / 0.75) + 1;
    userInputToRestore = new HashMap(capacity);
    for (final FieldError error : bindingResult.getFieldErrors()) {
        final String fieldPath = error.getField();
        final PathExtractor extractor = new PathExtractor(fieldPath);
        final int groupIndex = extractor.getGroupIndex();
        final int csticIndex = extractor.getCsticsIndex();
        UiGroupData group = configData.getGroups().get(groupIndex);
        for (int i = 0; i < extractor.getSubGroupCount(); i++) {
            group = group.getSubGroups().get(extractor.getSubGroupIndex(i));
        }//  ww  w.j  a  va  2 s.  c  o m
        final CsticData cstic = group.getCstics().get(csticIndex);
        userInputToRestore.put(cstic.getKey(), error);
        cstic.setValue(cstic.getLastValidValue());
    }
    return userInputToRestore;
}

From source file:it.smartcommunitylab.aac.controller.AdminController.java

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)/*from  w ww . ja v a 2s  . c o m*/
@ResponseBody
public Response processValidationError(MethodArgumentNotValidException ex) {
    BindingResult br = ex.getBindingResult();
    List<FieldError> fieldErrors = br.getFieldErrors();
    StringBuilder builder = new StringBuilder();

    fieldErrors.forEach(fe -> builder.append(fe.getDefaultMessage()).append("\n"));

    return Response.error(builder.toString());
}