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:cz.strmik.cmmitool.web.controller.UsersController.java

@RequestMapping(method = RequestMethod.POST, value = "/edit-{userId}.do")
public String processSubmitEdit(@ModelAttribute("user") User user, BindingResult result, ModelMap model,
        SessionStatus status) {//from  ww w .j av  a 2s  .c  o  m
    new UserValidator(userDao).validate(user, result);
    if (getLoggeduserId().equals(user.getUsername())
            && (!user.isEnabled() || !user.isAccountNonExpired() || !user.isCredentialsNonExpired())) {
        result.rejectValue("enabled", "can-not-disable-yourself");
    }
    if (result.hasErrors()) {
        return USER_FORM;
    }
    userDao.updateUser(user);
    status.setComplete();
    model.addAttribute("users", userDao.findAll());
    return USER_LIST;
}

From source file:de.blizzy.documentr.web.access.RoleController.java

@RequestMapping(value = "/save", method = RequestMethod.POST)
@PreAuthorize("hasApplicationPermission(ADMIN)")
public String saveRole(@ModelAttribute @Valid RoleForm form, BindingResult bindingResult,
        Authentication authentication) throws IOException {

    if (StringUtils.isNotBlank(form.getName()) && (StringUtils.isBlank(form.getOriginalName())
            || !form.getName().equals(form.getOriginalName()))) {

        try {//from w  w  w  . j  a v a 2 s .  com
            if (userStore.getRole(form.getName()) != null) {
                bindingResult.rejectValue("name", "role.name.exists"); //$NON-NLS-1$ //$NON-NLS-2$
            }
        } catch (RoleNotFoundException e) {
            // okay
        }
    }

    if (bindingResult.hasErrors()) {
        return "/user/role/edit"; //$NON-NLS-1$
    }

    EnumSet<Permission> permissions = EnumSet.noneOf(Permission.class);
    for (String permission : form.getPermissions()) {
        permissions.add(Permission.valueOf(permission));
    }
    String newRoleName = form.getOriginalName();
    if (StringUtils.isBlank(newRoleName)) {
        newRoleName = form.getName();
    }
    Role role = new Role(newRoleName, permissions);
    User user = userStore.getUser(authentication.getName());
    userStore.saveRole(role, user);

    if (StringUtils.isNotBlank(form.getOriginalName()) && StringUtils.isNotBlank(form.getName())
            && !StringUtils.equals(form.getName(), form.getOriginalName())) {

        userStore.renameRole(form.getOriginalName(), form.getName(), user);
    }

    return "redirect:/roles"; //$NON-NLS-1$
}

From source file:de.blizzy.documentr.web.access.UserController.java

@RequestMapping(value = "/save", method = RequestMethod.POST)
@PreAuthorize("hasApplicationPermission(ADMIN)")
public String saveUser(@ModelAttribute @Valid UserForm form, BindingResult bindingResult,
        Authentication authentication) throws IOException {

    User user = userStore.getUser(authentication.getName());

    if (StringUtils.isNotBlank(form.getOriginalLoginName())
            && !form.getOriginalLoginName().equals(UserStore.ANONYMOUS_USER_LOGIN_NAME)
            && StringUtils.equals(form.getLoginName(), UserStore.ANONYMOUS_USER_LOGIN_NAME)) {

        bindingResult.rejectValue("loginName", "user.loginName.invalid"); //$NON-NLS-1$ //$NON-NLS-2$
        return "/user/edit"; //$NON-NLS-1$
    }/*from   w  ww. j a  v  a  2 s .c  o  m*/

    if (!form.getLoginName().equals(UserStore.ANONYMOUS_USER_LOGIN_NAME)) {
        if (StringUtils.isNotBlank(form.getLoginName()) && (StringUtils.isBlank(form.getOriginalLoginName())
                || !form.getLoginName().equals(form.getOriginalLoginName()))) {

            try {
                if (userStore.getUser(form.getLoginName()) != null) {
                    bindingResult.rejectValue("loginName", "user.loginName.exists"); //$NON-NLS-1$ //$NON-NLS-2$
                }
            } catch (UserNotFoundException e) {
                // okay
            }
        }

        if (StringUtils.isBlank(form.getOriginalLoginName()) && StringUtils.isBlank(form.getPassword1())) {

            bindingResult.rejectValue("password1", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        if (StringUtils.isBlank(form.getOriginalLoginName()) && StringUtils.isBlank(form.getPassword2())) {

            bindingResult.rejectValue("password2", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        if (StringUtils.isBlank(form.getPassword1()) && StringUtils.isNotBlank(form.getPassword2())) {
            bindingResult.rejectValue("password1", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        if (StringUtils.isNotBlank(form.getPassword1()) && StringUtils.isBlank(form.getPassword2())) {
            bindingResult.rejectValue("password2", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        if (StringUtils.isNotBlank(form.getPassword1()) && StringUtils.isNotBlank(form.getPassword2())
                && !StringUtils.equals(form.getPassword1(), form.getPassword2())) {

            bindingResult.rejectValue("password1", "user.password.passwordsNotEqual"); //$NON-NLS-1$ //$NON-NLS-2$
            bindingResult.rejectValue("password2", "user.password.passwordsNotEqual"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        if (bindingResult.hasErrors()) {
            return "/user/edit"; //$NON-NLS-1$
        }

        User existingUser = null;
        String password = null;
        if (StringUtils.isNotBlank(form.getOriginalLoginName())) {
            try {
                existingUser = userStore.getUser(form.getOriginalLoginName());
                password = existingUser.getPassword();
            } catch (UserNotFoundException e) {
                // okay
            }
        }

        if (StringUtils.isNotBlank(form.getPassword1())) {
            password = passwordEncoder.encodePassword(form.getPassword1(), form.getLoginName());
        }

        if (StringUtils.isBlank(password)) {
            bindingResult.rejectValue("password1", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$
            bindingResult.rejectValue("password2", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        if (bindingResult.hasErrors()) {
            return "/user/edit"; //$NON-NLS-1$
        }

        String newUserName = form.getOriginalLoginName();
        if (StringUtils.isBlank(newUserName)) {
            newUserName = form.getLoginName();
        }

        User newUser = new User(newUserName, password, form.getEmail(), form.isDisabled());
        if (existingUser != null) {
            for (OpenId openId : existingUser.getOpenIds()) {
                newUser.addOpenId(openId);
            }
        }
        userStore.saveUser(newUser, user);

        if (StringUtils.isNotBlank(form.getOriginalLoginName())
                && !StringUtils.equals(form.getLoginName(), form.getOriginalLoginName())) {

            userStore.renameUser(form.getOriginalLoginName(), form.getLoginName(), user);
        }
    }

    String[] authorityStrs = StringUtils.defaultString(form.getAuthorities()).split("\\|"); //$NON-NLS-1$
    Set<RoleGrantedAuthority> authorities = Sets.newHashSet();
    for (String authorityStr : authorityStrs) {
        if (StringUtils.isNotBlank(authorityStr)) {
            String[] parts = authorityStr.split(":"); //$NON-NLS-1$
            Assert.isTrue(parts.length == 3);
            Type type = Type.valueOf(parts[0]);
            String targetId = parts[1];
            String roleName = parts[2];
            authorities.add(new RoleGrantedAuthority(new GrantedAuthorityTarget(targetId, type), roleName));
        }
    }
    userStore.saveUserAuthorities(form.getLoginName(), authorities, user);

    return "redirect:/users"; //$NON-NLS-1$
}

From source file:de.blizzy.documentr.web.account.AccountController.java

@RequestMapping(value = "/save", method = RequestMethod.POST)
@PreAuthorize("isAuthenticated()")
public String saveMyAccount(@ModelAttribute @Valid AccountForm form, BindingResult bindingResult, Model model,
        Authentication authentication) throws IOException {

    if (StringUtils.isNotBlank(form.getNewPassword1()) || StringUtils.isNotBlank(form.getNewPassword2())) {
        User user = userStore.getUser(authentication.getName());
        if (StringUtils.isBlank(form.getPassword())) {
            bindingResult.rejectValue("password", "user.password.blank"); //$NON-NLS-1$ //$NON-NLS-2$
        } else if (!passwordEncoder.matches(form.getPassword(), user.getPassword())) {
            bindingResult.rejectValue("password", "user.password.wrong"); //$NON-NLS-1$ //$NON-NLS-2$
        }/*from www. java2s  . co  m*/
        if (!StringUtils.equals(form.getNewPassword1(), form.getNewPassword2())) {
            bindingResult.rejectValue("newPassword1", "user.password.passwordsNotEqual"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        if (!bindingResult.hasErrors()) {
            String encodedPassword = passwordEncoder.encode(form.getNewPassword1());
            User newUser = new User(user.getLoginName(), encodedPassword, user.getEmail(), user.isDisabled());
            for (OpenId openId : user.getOpenIds()) {
                newUser.addOpenId(openId);
            }
            userStore.saveUser(newUser, user);
        }
    }

    if (!bindingResult.hasErrors()) {
        model.addAttribute("messageKey", "dataSaved"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    return "/account/index"; //$NON-NLS-1$
}

From source file:de.blizzy.documentr.web.branch.BranchController.java

@RequestMapping(value = "/save/{projectName:" + DocumentrConstants.PROJECT_NAME_PATTERN
        + "}", method = RequestMethod.POST)
@PreAuthorize("hasBranchPermission(#form.projectName, #form.name, EDIT_BRANCH)")
public String saveBranch(@ModelAttribute @Valid BranchForm form, BindingResult bindingResult,
        Authentication authentication) throws IOException, GitAPIException {

    List<String> branches = globalRepositoryManager.listProjectBranches(form.getProjectName());
    boolean firstBranch = branches.isEmpty();
    if (branches.contains(form.getName())) {
        bindingResult.rejectValue("name", "branch.name.exists"); //$NON-NLS-1$ //$NON-NLS-2$
    }//from   w  w w . j  a va2s .c  o m

    if (bindingResult.hasErrors()) {
        return "/project/branch/edit"; //$NON-NLS-1$
    }

    ILockedRepository repo = null;
    try {
        repo = globalRepositoryManager.createProjectBranchRepository(form.getProjectName(), form.getName(),
                form.getStartingBranch());
    } finally {
        Closeables.closeQuietly(repo);
    }

    if (firstBranch) {
        Page page = Page.fromText("Home", StringUtils.EMPTY); //$NON-NLS-1$
        User user = userStore.getUser(authentication.getName());
        pageStore.savePage(form.getProjectName(), form.getName(), DocumentrConstants.HOME_PAGE_NAME, page, null,
                user);
        return "redirect:/page/edit/" + form.getProjectName() + "/" + form.getName() + //$NON-NLS-1$ //$NON-NLS-2$
                "/" + DocumentrConstants.HOME_PAGE_NAME; //$NON-NLS-1$
    }

    return "redirect:/page/" + form.getProjectName() + "/" + form.getName() + //$NON-NLS-1$ //$NON-NLS-2$
            "/" + DocumentrConstants.HOME_PAGE_NAME; //$NON-NLS-1$
}

From source file:de.blizzy.documentr.web.page.PageController.java

@RequestMapping(value = "/save/{projectName:" + DocumentrConstants.PROJECT_NAME_PATTERN + "}/" + "{branchName:"
        + DocumentrConstants.BRANCH_NAME_PATTERN + "}", method = RequestMethod.POST)
@PreAuthorize("hasBranchPermission(#form.projectName, #form.branchName, EDIT_PAGE)")
public String savePage(@ModelAttribute @Valid PageForm form, BindingResult bindingResult, Model model,
        Authentication authentication) throws IOException {

    String projectName = form.getProjectName();
    String branchName = form.getBranchName();
    User user = userStore.getUser(authentication.getName());

    if (!globalRepositoryManager.listProjectBranches(projectName).contains(branchName)) {
        bindingResult.rejectValue("branchName", "page.branch.nonexistent"); //$NON-NLS-1$ //$NON-NLS-2$
    }/*from ww w.  j  a va  2 s .  com*/

    if (bindingResult.hasErrors()) {
        return "/project/branch/page/edit"; //$NON-NLS-1$
    }

    String parentPagePath = form.getParentPagePath();
    if (StringUtils.isBlank(parentPagePath)) {
        parentPagePath = null;
    }
    parentPagePath = Util.toRealPagePath(parentPagePath);
    Page page = Page.fromText(form.getTitle(), form.getText());
    String path = form.getPath();
    if (StringUtils.isBlank(path)) {
        path = parentPagePath + "/" + Util.simplifyForUrl(form.getTitle()); //$NON-NLS-1$
    }
    page.setTags(Sets.newHashSet(form.getTags()));
    page.setViewRestrictionRole(
            StringUtils.isNotBlank(form.getViewRestrictionRole()) ? form.getViewRestrictionRole() : null);

    Page oldPage = null;
    try {
        oldPage = pageStore.getPage(projectName, branchName, path, true);
    } catch (PageNotFoundException e) {
        // okay
    }
    if ((oldPage == null) || !page.equals(oldPage)) {
        MergeConflict conflict = pageStore.savePage(projectName, branchName, path, page,
                Strings.emptyToNull(form.getCommit()), user);
        if (conflict != null) {
            form.setText(conflict.getText());
            form.setCommit(conflict.getNewBaseCommit());
            model.addAttribute("mergeConflict", Boolean.TRUE); //$NON-NLS-1$
            return "/project/branch/page/edit"; //$NON-NLS-1$
        }
    }

    Integer start = form.getParentPageSplitRangeStart();
    Integer end = form.getParentPageSplitRangeEnd();
    if (StringUtils.isNotBlank(parentPagePath) && (start != null) && (end != null) && permissionEvaluator
            .hasBranchPermission(authentication, projectName, branchName, Permission.EDIT_PAGE)) {

        log.info("splitting off {}-{} of {}/{}/{}", //$NON-NLS-1$
                start, end, projectName, branchName, parentPagePath);

        Page parentPage = pageStore.getPage(projectName, branchName, parentPagePath, true);
        String text = ((PageTextData) parentPage.getData()).getText();
        end = Math.min(end, text.length());
        text = text.substring(0, start) + text.substring(end);
        parentPage.setData(new PageTextData(text));
        pageStore.savePage(projectName, branchName, parentPagePath, parentPage, null, user);
    }

    return "redirect:/page/" + projectName + "/" + branchName + "/" + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            Util.toUrlPagePath(path);
}

From source file:de.blizzy.documentr.web.project.ProjectController.java

@RequestMapping(value = "/save", method = RequestMethod.POST)
@PreAuthorize("projectExists(#form.name) ? " + "hasProjectPermission(#form.name, EDIT_PROJECT) : "
        + "hasApplicationPermission(EDIT_PROJECT)")
public String saveProject(@ModelAttribute @Valid ProjectForm form, BindingResult bindingResult,
        Authentication authentication) throws IOException, GitAPIException {

    String name = form.getName();
    String originalName = form.getOriginalName();
    List<String> projects = globalRepositoryManager.listProjects();
    if (StringUtils.isNotBlank(originalName)) {
        if (!projects.contains(originalName)) {
            bindingResult.rejectValue("originalName", "project.name.nonexistent"); //$NON-NLS-1$ //$NON-NLS-2$
        }// w  w  w  .  j a  v a2 s .c  o m
        if (!StringUtils.equals(name, originalName) && projects.contains(name)) {

            bindingResult.rejectValue("name", "project.name.exists"); //$NON-NLS-1$ //$NON-NLS-2$
        }
    } else {
        if (projects.contains(name)) {
            bindingResult.rejectValue("name", "project.name.exists"); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }

    if (bindingResult.hasErrors()) {
        return "/project/edit"; //$NON-NLS-1$
    }

    User user = userStore.getUser(authentication.getName());

    if (StringUtils.isNotBlank(originalName) && !StringUtils.equals(name, originalName)) {

        globalRepositoryManager.renameProject(originalName, name, user);
    } else if (StringUtils.isBlank(originalName)) {
        ILockedRepository repo = null;
        try {
            repo = globalRepositoryManager.createProjectCentralRepository(name, user);
        } finally {
            Util.closeQuietly(repo);
        }
    }
    return "redirect:/project/" + name; //$NON-NLS-1$
}

From source file:de.hybris.platform.chineseprofile.controllers.pages.ChineseLoginPageController.java

/**
 * This method takes data from the registration form and create a new customer account and attempts to log in using
 * the credentials of this new user./*  www.  j  a v  a  2s  .c o  m*/
 *
 * @return true if there are no binding errors or the account does not already exists.
 * @throws CMSItemNotFoundException
 */
@Override
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);
        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());
    try {
        getCustomerFacade().register(data);
        getAutoLoginStrategy().login(form.getEmail().toLowerCase(), form.getPwd(), request, response);
    } catch (final DuplicateUidException e) {
        LOGGER.warn("registration failed: " + e);
        model.addAttribute(form);
        model.addAttribute(new LoginForm());
        model.addAttribute(new GuestForm());
        bindingResult.rejectValue("email", "registration.error.account.exists.title");
        GlobalMessages.addErrorMessage(model, FORM_GLOBAL_ERROR);
        return handleRegistrationError(model);
    }

    return REDIRECT_PREFIX + MOBILE_BIND_URL;
}

From source file:easycare.web.password.ChangePasswordController.java

protected ModelAndView changePassword(HttpServletRequest request, HttpSession session,
        ChangePasswordForm changePasswordForm, BindingResult result, String view) {
    User user = this.sessionSecurityService.getCurrentUser();

    boolean validPassword = true;
    if (!result.hasErrors()) {
        // Check Password history
        if (userService.hasUsedPassword(user, changePasswordForm.getPassword())) {
            result.rejectValue("password", "password.change.history.error");
            validPassword = false;//www  .  j a  v a  2  s .c  o  m
            userPasswordService.fireChangePasswordFailAlreadyUsedEvent(changePasswordForm.getUsername());
        }
    }

    if (result.hasErrors() || !validPassword) {
        // If password is in error, add the message code to be displayed
        ModelAndView mav = new ModelAndView(view);
        mav.addObject("changePasswordBean", changePasswordForm);
        if (!validPassword) {
            result.reject("password.change.fail");
        } else {
            userPasswordService.fireChangePasswordFailValidationEvent(changePasswordForm.getUsername(), result);
        }
        return mav;
    }

    // Update password token
    if (!updatePasswordToken(session)) {
        return new ModelAndView(INVALID_TOKEN_VIEW);
    }

    // Update user password
    user = userService.changePassword(user, changePasswordForm.getPassword());
    userPasswordService.fireChangePasswordSuccessfulEvent(changePasswordForm.getUsername());

    if (BooleanUtils.isTrue((Boolean) session.getAttribute(LOGOUT_AFTER_PASSWORD_CHANGE_KEY))) {
        return forceRelogin(request, user);
    }

    // Redirect to License Agreement page if needed
    if (!user.isLicenseAgreementAccepted()) {
        return new ModelAndView(new RedirectView("/licenseAgreement", true));
    }
    // Refresh User authorities
    sessionSecurityService.refreshUserContext(request, user, null);
    // Redirect to Home page
    return new ModelAndView(new RedirectView("/", true));
}

From source file:easycare.web.user.UserController.java

private boolean areMandatoryFieldsPresentForInterpretingPhysician(NewUserForm newUserForm,
        BindingResult result) {
    boolean valid = true;

    if (!newUserForm.hasRole(RoleEnum.ROLE_INTERPRETING_PHYSICIAN)) {
        return valid;
    }//w w  w. ja  v  a2  s .c  om

    if (StringUtils.isEmpty(newUserForm.getEmail())) {
        // this will already be validated by the user form.  Don't reject email value again as will see duplicate errors...
        valid = false;
    }

    if (newUserForm.hasNoEmail()) {
        result.rejectValue("noEmail", NEW_USER_CREATION_INTERPRETING_PHYSICIAN_FAILURE_MESSAGE);
        valid = false;
    }

    if (StringUtils.isEmpty(newUserForm.getLicenseNumber())) {
        result.rejectValue("licenseNumber", NEW_USER_CREATION_INTERPRETING_PHYSICIAN_FAILURE_MESSAGE);
        valid = false;
    }

    return valid;
}