Example usage for org.springframework.validation BindingResult rejectValue

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

Introduction

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

Prototype

void rejectValue(@Nullable String field, String errorCode);

Source Link

Document

Register a field error for the specified field of the current object (respecting the current nested path, if any), using the given error description.

Usage

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

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String createPost(Question question, BindingResult bindingResult,
        @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("create(): handles " + RequestMethod.POST.toString());
    try {/*from w w w.  ja  va 2 s.  c o  m*/
        log.info("-------------------------------------------------");
        String login = principal.getName();
        User user = userService.user_findByLogin(login);

        SurveyDefinition surveyDefinition = surveySettingsService.question_findById(question.getId()).getPage()
                .getSurveyDefinition();
        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinition.getId(), user)
                && !securityService.userBelongsToDepartment(surveyDefinition.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) {
            boolean hasNoOptions = true;
            boolean isValid = true;
            int i = 0;
            for (QuestionOption questionOption : question.getOptionsList2()) {

                //if the value or text is not null and not a blank string
                if ((questionOption.getValue() != null && questionOption.getText() != null)
                        && (questionOption.getValue().trim().length() > 0
                                || questionOption.getText().trim().length() > 0)) {
                    hasNoOptions = false;
                    //validate the length
                    if (questionOption.getValue().trim().length() == 0
                            || questionOption.getValue().trim().length() > 5) {
                        bindingResult.rejectValue("optionsList2[" + i + "].value", "nullvalue");
                        isValid = false;

                    }
                    //validate the length
                    if (questionOption.getText().trim().length() == 0
                            || questionOption.getText().trim().length() > 250) {
                        bindingResult.rejectValue("optionsList2[" + i + "].text", "nullvalue");
                        isValid = false;
                    }
                }
                i++;
            }

            if (hasNoOptions) {
                isValid = false;
                bindingResult.rejectValue("optionsList2[" + 0 + "].value", "nullValueEntered");
                //re-populate the place holders for options
                for (int j = 1; j <= EMPTY_OPTIONS_COUNT; j++) {
                    question.getOptions()
                            .add(new QuestionOption(question, (short) (question.getOptions().size() + j)));
                }
            }

            if (!isValid) {
                return "settings/questionOptions/update";
            } else {
                question = surveySettingsService.question_updateOptions(question);
                return "settings/questionOptions/saved";
            }
        }

        //cancel button handler
        else {
            question = surveySettingsService.question_updateOptions(question);
            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.jd.survey.web.settings.QuestionRowLabelController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String createPost(Question question, BindingResult bindingResult,
        @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("create(): handles " + RequestMethod.POST.toString());
    try {//w  ww. ja  va  2  s  .  c o  m

        String login = principal.getName();
        User user = userService.user_findByLogin(login);
        //Check if the user is authorized
        if (!securityService.userIsAuthorizedToManageSurvey(surveySettingsService
                .question_findById(question.getId()).getPage().getSurveyDefinition().getId(), user)
                && !securityService
                        .userBelongsToDepartment(surveySettingsService.question_findById(question.getId())
                                .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) {
            boolean isValid = true;
            for (int i = 0; i < question.getRowLabelsList().size(); i++) {
                if (question.getRowLabelsList().get(i).getLabel() != null
                        && question.getRowLabelsList().get(i).getLabel().trim().length() > 0) {

                    if (question.getRowLabelsList().get(i).getLabel().trim().length() == 0
                            || question.getRowLabelsList().get(i).getLabel().trim().length() > 75) {
                        bindingResult.rejectValue("rowLabelsList[" + i + "].label", "invalidEntry");
                        isValid = false;

                    }
                } else {
                    //User is trying to save an empty MC form
                    if (i == 0) {
                        bindingResult.rejectValue("rowLabelsList[" + i + "].label", "invalidEntry");
                        isValid = false;
                    }
                }
            }

            if (!isValid) {
                return "settings/questionRows/update";
            } else {
                question = surveySettingsService.question_updateRowLabels(question);
                return "settings/questionRows/saved";

            }
        } else {
            question = surveySettingsService.question_updateRowLabels(question);
            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.jd.survey.web.settings.RegularExpressionController.java

@Secured({ "ROLE_ADMIN" })
@RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String createPost(@RequestParam(value = "_proceed", required = false) String proceed,
        @Valid RegularExpression regularExpression, BindingResult bindingResult, Principal principal,
        Model uiModel, HttpServletRequest httpServletRequest) {
    log.info("create(): handles " + RequestMethod.POST.toString());
    try {/*from   w  ww . j  a va  2s  .  c o m*/
        User user = userService.user_findByLogin(principal.getName());
        if (proceed != null) {
            if (bindingResult.hasErrors()) {
                populateEditForm(uiModel, regularExpression, user);
                return "admin/masks/create";
            }
            if (surveySettingsService.regularExpression_findByName(regularExpression.getName()) != null) {
                bindingResult.rejectValue("name", "field_unique");
                populateEditForm(uiModel, regularExpression, user);
                return "admin/masks/create";
            }
            uiModel.asMap().clear();
            regularExpression = surveySettingsService.regularExpression_merge(regularExpression);
            return "redirect:/admin/masks";//+ encodeUrlPathSegment(regularExpression.getId().toString(), httpServletRequest);
        } else {
            return "redirect:/admin/masks";
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }

}

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

@Secured({ "ROLE_ADMIN" })
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@RequestParam(value = "_proceed", required = false) String proceed,
        @Valid RegularExpression regularExpression, BindingResult bindingResult, Principal principal,
        Model uiModel, HttpServletRequest httpServletRequest) {
    log.info("update(): handles PUT");
    try {//w  w  w .j  a va 2 s . c  o m
        User user = userService.user_findByLogin(principal.getName());
        if (proceed != null) {
            if (bindingResult.hasErrors()) {
                populateEditForm(uiModel, regularExpression, user);
                return "admin/masks/update";
            }

            if (surveySettingsService.regularExpression_findByName(regularExpression.getName()) != null
                    && !surveySettingsService.regularExpression_findByName(regularExpression.getName()).getId()
                            .equals(regularExpression.getId())) {
                bindingResult.rejectValue("name", "field_unique");
                populateEditForm(uiModel, regularExpression, user);
                return "admin/masks/update";
            }
            uiModel.asMap().clear();
            regularExpression = surveySettingsService.regularExpression_merge(regularExpression);
            return "redirect:/admin/masks"; // + encodeUrlPathSegment(regularExpression.getId().toString(), httpServletRequest);
        } else {
            return "redirect:/admin/masks";
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

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

@Secured({ "ROLE_ADMIN" })
@RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String createPost(@RequestParam(value = "_proceed", required = false) String proceed,
        @Valid Sector sector, BindingResult bindingResult, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("create(): handles " + RequestMethod.POST.toString());
    try {//from ww w .ja  v  a2 s  .  co  m
        User user = userService.user_findByLogin(principal.getName());
        if (!user.isAdmin()) {
            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, sector, user);
                return "admin/sectors/create";
            }

            if (surveySettingsService.dataset_findByName(sector.getName()) != null && !surveySettingsService
                    .dataset_findByName(sector.getName()).getId().equals(sector.getId())) {
                bindingResult.rejectValue("name", "field_unique");
                populateEditForm(uiModel, sector, user);
                return "admin/sectors/update";
            }

            uiModel.asMap().clear();
            sector = surveySettingsService.sector_merge(sector);
            return "redirect:/admin/sectors/"
                    + encodeUrlPathSegment(sector.getId().toString(), httpServletRequest);
        } else {
            return "redirect:/admin/sectors";
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }

}

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

@Secured({ "ROLE_ADMIN" })
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@RequestParam(value = "_proceed", required = false) String proceed, @Valid Sector sector,
        BindingResult bindingResult, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("update(): handles PUT");
    try {//from  w ww. ja v  a  2s .  c  om
        User user = userService.user_findByLogin(principal.getName());

        if (!user.isAdmin()) {
            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, sector, user);
                return "admin/sectors/update";
            }

            if (surveySettingsService.dataset_findByName(sector.getName()) != null && !surveySettingsService
                    .dataset_findByName(sector.getName()).getId().equals(sector.getId())) {
                bindingResult.rejectValue("name", "field_unique");
                populateEditForm(uiModel, sector, user);
                return "admin/sectors/update";
            }
            uiModel.asMap().clear();
            sector = surveySettingsService.sector_merge(sector);
            return "redirect:/admin/sectors/"
                    + encodeUrlPathSegment(sector.getId().toString(), httpServletRequest);
        } else {
            return "redirect:/admin/sectors";
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

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

/**
 * creates a new survey definition//from w  ww  . j  av  a2s  .  c o m
 * @param proceed
 * @param surveyDefinition
 * @param bindingResult
 * @param uiModel
 * @param httpServletRequest
 * @param principal
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String createPost(@RequestParam(value = "_proceed", required = false) String proceed,
        @Valid SurveyDefinition surveyDefinition, BindingResult bindingResult, Principal principal,
        Model uiModel, HttpServletRequest httpServletRequest) {
    try {
        String login = principal.getName();
        User user = userService.user_findByLogin(login);
        //Check if the user is authorized
        if (!securityService.userBelongsToDepartment(surveyDefinition.getDepartment().getId(), user)
                && !securityService.userIsAuthorizedToManageSurvey(surveyDefinition.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, surveyDefinition, user);
                return "settings/surveyDefinitions/create";
            }
            if (!surveySettingsService.surveyDefinition_ValidateNameIsUnique(surveyDefinition)) {
                bindingResult.rejectValue("name", "field_unique");
                populateEditForm(uiModel, surveyDefinition, user);
                return "settings/surveyDefinitions/create";
            }

            //if(surveyDefinition.getSendAutoReminders() == true){
            //bindingResult.rejectValue("autoRemindersWeeklyOccurrence", "field_unique");

            //   }   

            Policy emailTemplatePolicy = Policy.getInstance(this.getClass().getResource(POLICY_FILE_LOCATION));
            AntiSamy emailAs = new AntiSamy();
            CleanResults crEmail = emailAs.scan(surveyDefinition.getEmailInvitationTemplate(),
                    emailTemplatePolicy);
            surveyDefinition.setEmailInvitationTemplate(crEmail.getCleanHTML());

            Policy completedSurveyPolicy = Policy
                    .getInstance(this.getClass().getResource(POLICY_FILE_LOCATION));
            AntiSamy completedSurveyAs = new AntiSamy();
            CleanResults crCompletedSurvey = completedSurveyAs
                    .scan(surveyDefinition.getCompletedSurveyTemplate(), completedSurveyPolicy);
            surveyDefinition.setCompletedSurveyTemplate(crCompletedSurvey.getCleanHTML());

            uiModel.asMap().clear();
            surveyDefinition = surveySettingsService.surveyDefinition_merge(surveyDefinition);
            return "redirect:/settings/surveyDefinitions/"
                    + encodeUrlPathSegment(surveyDefinition.getId().toString(), httpServletRequest);
        } else {
            return "redirect:/settings/surveyDefinitions";
        }
    }

    catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

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

/**
 * Updates a survey definition   //from  w  w  w.  ja v  a2s.  co  m
 * @param proceed
 * @param surveyDefinition
 * @param bindingResult
 * @param uiModel
 * @param httpServletRequest
 * @param principal
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@RequestParam(value = "_proceed", required = false) String proceed,
        @Valid SurveyDefinition surveyDefinition, BindingResult bindingResult, Principal principal,
        Model uiModel, HttpServletRequest httpServletRequest) {

    try {
        String login = principal.getName();
        User user = userService.user_findByLogin(login);
        //Check if the user is authorized
        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinition.getId(), user)
                && !securityService.userBelongsToDepartment(surveyDefinition.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, surveyDefinition, user);
                return "settings/surveyDefinitions/update";
            }
            if (!surveySettingsService.surveyDefinition_ValidateNameIsUnique(surveyDefinition)) {
                bindingResult.rejectValue("name", "field_unique");
                populateEditForm(uiModel, surveyDefinition, user);
                return "settings/surveyDefinitions/update";
            }
            System.out.println("!!!!!!!!! MD: " + surveyDefinition.getAllowMultipleSubmissions()
                    + " #################### PUB: " + surveyDefinition.getIsPublic());
            Policy emailTemplatePolicy = Policy.getInstance(this.getClass().getResource(POLICY_FILE_LOCATION));
            AntiSamy emailAs = new AntiSamy();
            CleanResults crEmail = emailAs.scan(surveyDefinition.getEmailInvitationTemplate(),
                    emailTemplatePolicy);
            surveyDefinition.setEmailInvitationTemplate(crEmail.getCleanHTML());

            Policy completedSurveyPolicy = Policy
                    .getInstance(this.getClass().getResource(POLICY_FILE_LOCATION));
            AntiSamy completedSurveyAs = new AntiSamy();
            CleanResults crCompletedSurvey = completedSurveyAs
                    .scan(surveyDefinition.getCompletedSurveyTemplate(), completedSurveyPolicy);
            surveyDefinition.setCompletedSurveyTemplate(crCompletedSurvey.getCleanHTML());

            uiModel.asMap().clear();
            surveyDefinition = surveySettingsService.surveyDefinition_merge(surveyDefinition);
            System.out.println("!!!!!!!!! MD: " + surveyDefinition.getAllowMultipleSubmissions()
                    + " #################### PUB: " + surveyDefinition.getIsPublic());
            return "settings/surveyDefinitions/saved";

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

From source file:com.razorfish.controllers.pages.LoginPageController.java

protected String processRegisterUserRequest(final String referer, final RegisterForm form,
        final BindingResult bindingResult, final Model model, final HttpServletRequest request,
        final HttpServletResponse response, final RedirectAttributes redirectModel)
        throws CMSItemNotFoundException {
    if (bindingResult.hasErrors()) {
        model.addAttribute(form);/*  ww w .  j  a  v  a2 s  .  c  o  m*/
        model.addAttribute(new LoginForm());
        model.addAttribute(new GuestForm());
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return handleRegistrationError(model);
    }

    final RegisterData data = new RegisterData();
    data.setFirstName(form.getFirstName());
    data.setLastName(form.getLastName());
    data.setLogin(form.getEmail());
    data.setPassword(form.getPwd());
    data.setTitleCode(form.getTitleCode());
    data.setMobileNumber(form.getMobileNumber());
    try {
        getCustomerFacade().register(data);
        getAutoLoginStrategy().login(form.getEmail().toLowerCase(), form.getPwd(), request, response);

        GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
                "registration.confirmation.message.title");
    } catch (final DuplicateUidException e) {
        LOG.warn("registration failed: " + e);
        model.addAttribute(form);
        model.addAttribute(new LoginForm());
        model.addAttribute(new GuestForm());
        if (e.getCause().getCause() instanceof InterceptorException
                && ((InterceptorException) e.getCause().getCause()).getInterceptor().getClass()
                        .equals(UniqueAttributesInterceptor.class)) {
            bindingResult.rejectValue("email", "registration.error.account.exists.title");
        } else if (e.getCause().getCause() instanceof InterceptorException
                && ((InterceptorException) e.getCause().getCause()).getInterceptor().getClass()
                        .equals(CustomerMobileNumberValidateInterceptor.class)) {
            bindingResult.rejectValue("mobileNumber", "registration.error.mobileNumber.exists.title");
        }

        GlobalMessages.addErrorMessage(model, "form.global.error");
        return handleRegistrationError(model);
    }

    return REDIRECT_PREFIX + getSuccessRedirect(request, response);
}

From source file:com.sap.sapbasket.storefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/update-profile", method = RequestMethod.POST)
@RequireHardLogIn//from ww w .j a v  a 2 s.  co m
public String updateProfile(final ExtendedUpdateProfileForm extendedupdateProfileForm,
        final BindingResult bindingResult, final Model model, final RedirectAttributes redirectAttributes)
        throws CMSItemNotFoundException {
    getProfileValidator().validate(extendedupdateProfileForm, bindingResult);

    String returnAction = REDIRECT_TO_UPDATE_PROFILE;
    final CustomerData currentCustomerData = customerFacade.getCurrentCustomer();
    final CustomerData customerData = new CustomerData();
    customerData.setTitleCode(extendedupdateProfileForm.getTitleCode());
    customerData.setFirstName(extendedupdateProfileForm.getFirstName());
    customerData.setLastName(extendedupdateProfileForm.getLastName());

    customerData.setEmail(extendedupdateProfileForm.getEmail());
    customerData.setDate_of_birth(extendedupdateProfileForm.getDate_of_birth());
    customerData.setMobile_number(extendedupdateProfileForm.getMobile_number());
    customerData.setLandline_number(extendedupdateProfileForm.getLandline_number());

    customerData.setUid(currentCustomerData.getUid());
    customerData.setDisplayUid(currentCustomerData.getDisplayUid());

    model.addAttribute(TITLE_DATA_ATTR, userFacade.getTitles());

    storeCmsPageInModel(model, getContentPageForLabelOrId(UPDATE_PROFILE_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(UPDATE_PROFILE_CMS_PAGE));

    if (bindingResult.hasErrors()) {
        returnAction = setErrorMessagesAndCMSPage(model, UPDATE_PROFILE_CMS_PAGE);
    } else {
        try {
            customerFacade.updateProfile(customerData);
            GlobalMessages.addFlashMessage(redirectAttributes, GlobalMessages.CONF_MESSAGES_HOLDER,
                    "text.account.profile.confirmationUpdated", null);

        } catch (final DuplicateUidException e) {
            bindingResult.rejectValue("email", "registration.error.account.exists.title");
            returnAction = setErrorMessagesAndCMSPage(model, UPDATE_PROFILE_CMS_PAGE);
        }
    }

    model.addAttribute(BREADCRUMBS_ATTR, accountBreadcrumbBuilder.getBreadcrumbs(TEXT_ACCOUNT_PROFILE));
    return returnAction;
}