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.jnj.b2b.storefront.controllers.pages.BudgetManagementPageController.java

@RequestMapping(value = "/update", method = RequestMethod.POST)
@RequireHardLogIn/* ww w  . j ava 2 s  . com*/
public String updateBudgetsDetails(@RequestParam("budgetCode") final String budgetCode,
        @Valid final B2BBudgetForm b2BBudgetForm, final BindingResult bindingResult, final Model model,
        final RedirectAttributes redirectModel) throws CMSItemNotFoundException, ParseException {
    b2BBudgetFormValidator.validate(b2BBudgetForm, bindingResult);
    if (bindingResult.hasErrors()) {
        model.addAttribute(b2BBudgetForm);
        return editBudgetsDetails(b2BBudgetForm.getOriginalCode(), model);
    }
    if (checkEndDateIsBeforeStartDateForBudget(b2BBudgetForm)) {
        model.addAttribute(b2BBudgetForm);
        bindingResult.rejectValue("endDate", "text.company.budget.endDateLesser.error.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return editBudgetsDetails(b2BBudgetForm.getOriginalCode(), model);
    }
    final B2BBudgetData b2BBudgetData = populateB2BBudgetDataFromForm(b2BBudgetForm);
    try {
        budgetFacade.updateBudget(b2BBudgetData);

    } catch (final Exception e) {
        LOG.warn("Exception while saving the budget details " + e);
        model.addAttribute(b2BBudgetForm);
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return editBudgetsDetails(b2BBudgetForm.getOriginalCode(), model);
    }
    storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManageBudgetsBreadCrumbs();
    breadcrumbs.add(new Breadcrumb("/my-company/organization-management/manage-budgets/update",
            getMessageSource().getMessage("text.company.budget.editPage", null,
                    getI18nService().getCurrentLocale()),
            null));
    model.addAttribute("breadcrumbs", breadcrumbs);
    GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
            "text.confirmation.budget.updated");
    return String.format(REDIRECT_TO_BUDGET_DETAILS, urlEncode(b2BBudgetData.getCode()));
}

From source file:org.wallride.web.controller.admin.page.PageEditController.java

@RequestMapping(method = RequestMethod.POST, params = "draft")
public @ResponseBody DomainObjectSavedModel saveAsDraft(@PathVariable String language,
        @Validated @ModelAttribute("form") PageEditForm form, BindingResult errors, Model model,
        AuthorizedUser authorizedUser) throws BindException {
    if (errors.hasErrors()) {
        for (ObjectError error : errors.getAllErrors()) {
            if (!"validation.NotNull".equals(error.getCode())) {
                throw new BindException(errors);
            }/* www . ja v  a 2  s.  co  m*/
        }
    }

    Page page = (Page) model.asMap().get("page");
    try {
        pageService.savePageAsDraft(form.buildPageUpdateRequest(), authorizedUser);
    } catch (EmptyCodeException e) {
        errors.rejectValue("code", "NotNull");
    } catch (DuplicateCodeException e) {
        errors.rejectValue("code", "NotDuplicate");
    }
    if (errors.hasErrors()) {
        logger.debug("Errors: {}", errors);
        throw new BindException(errors);
    }

    return new DomainObjectSavedModel<>(page);
}

From source file:de.hybris.platform.commerceorgaddon.controllers.pages.BudgetManagementPageController.java

@RequestMapping(value = "/update", method = RequestMethod.POST)
@RequireHardLogIn/*  ww  w  .  j  a  v  a  2 s.  co  m*/
public String updateBudgetsDetails(@RequestParam("budgetCode") final String budgetCode,
        @Valid final B2BBudgetForm b2BBudgetForm, final BindingResult bindingResult, final Model model,
        final RedirectAttributes redirectModel) throws CMSItemNotFoundException, ParseException {
    b2BBudgetFormValidator.validate(b2BBudgetForm, bindingResult);
    if (bindingResult.hasErrors()) {
        model.addAttribute(b2BBudgetForm);
        return editBudgetsDetails(b2BBudgetForm.getOriginalCode(), model);
    }
    if (checkEndDateIsBeforeStartDateForBudget(b2BBudgetForm)) {
        model.addAttribute(b2BBudgetForm);
        bindingResult.rejectValue("endDate", "text.company.budget.endDateLesser.error.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return editBudgetsDetails(b2BBudgetForm.getOriginalCode(), model);
    }
    final B2BBudgetData b2BBudgetData = populateB2BBudgetDataFromForm(b2BBudgetForm);
    try {
        budgetFacade.updateBudget(b2BBudgetData);
    } catch (final Exception e) {
        LOG.warn("Exception while saving the budget details " + e);
        model.addAttribute(b2BBudgetForm);
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return editBudgetsDetails(b2BBudgetForm.getOriginalCode(), model);
    }
    storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManageBudgetsBreadCrumbs();
    breadcrumbs.add(new Breadcrumb("/my-company/organization-management/manage-budgets/update",
            getMessageSource().getMessage("text.company.budget.editPage", null,
                    getI18nService().getCurrentLocale()),
            null));
    model.addAttribute("breadcrumbs", breadcrumbs);
    GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
            "text.confirmation.budget.updated");
    return String.format(REDIRECT_TO_BUDGET_DETAILS, urlEncode(b2BBudgetData.getCode()));
}

From source file:org.wallride.web.controller.admin.article.ArticleEditController.java

@RequestMapping(method = RequestMethod.POST, params = "draft")
public @ResponseBody DomainObjectSavedModel saveAsDraft(@PathVariable String language,
        @Validated @ModelAttribute("form") ArticleEditForm form, BindingResult errors, Model model,
        AuthorizedUser authorizedUser) throws BindException {
    if (errors.hasErrors()) {
        for (ObjectError error : errors.getAllErrors()) {
            if (!"validation.NotNull".equals(error.getCode())) {
                throw new BindException(errors);
            }/*from   w  w w  .  jav a  2  s  .c o m*/
        }
    }

    Article article = (Article) model.asMap().get("article");
    try {
        articleService.saveArticleAsDraft(form.buildArticleUpdateRequest(), authorizedUser);
    } catch (EmptyCodeException e) {
        errors.rejectValue("code", "NotNull");
    } catch (DuplicateCodeException e) {
        errors.rejectValue("code", "NotDuplicate");
    }
    if (errors.hasErrors()) {
        logger.debug("Errors: {}", errors);
        throw new BindException(errors);
    }

    return new DomainObjectSavedModel<>(article);
}

From source file:net.bafeimao.umbrella.web.controller.UserController.java

@RequestMapping(value = "/register1", method = RequestMethod.POST)
public String register(@Valid User user, Model model, BindingResult result)
        throws DuplicateEmailException, DuplicateNameException {

    // User????//from  w w  w.ja  v  a2s.co  m
    if (!result.hasErrors()) {

        // // ???
        // String sessionChaptcha = (String)
        // session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        // if (captcha == null || !captcha.equalsIgnoreCase(sessionChaptcha)) {
        // result.rejectValue("chaptcha", "chaptcha is incorrect");
        // return "user/register";
        // }

        if (user != null) {
            if (user.getName() == null) {
                result.rejectValue("name", "name is required");
                return "user/register";
            }

            if (user.getEmail() == null) {
                result.rejectValue("email", "email is required");
                return "user/register";
            }
        }

        userService.register(user);
        if (user.getId() != null) {
            model.addAttribute("user", user);
            return "user/register";
        }
    }

    return "user/register-success.jsp";
}

From source file:com.excilys.ebi.bank.web.controller.account.transfer.operations.TransferPerformController.java

@RequestMapping(method = RequestMethod.POST)
public String performTransfer(@PathVariable String accountNumber,
        @ModelAttribute @Valid TransferCommand command, BindingResult result, ModelMap model,
        RedirectAttributes redirectAttributes) {

    if (!result.hasErrors()) {
        try {/*from   w w  w.  j  a va  2s.co m*/
            Integer debitedAccountId = bankService.findAccountIdByNumber(command.getDebitedAccountNumber());
            Integer creditedAccountId = bankService.findAccountIdByNumber(command.getCreditedAccountNumber());
            bankService.performTransfer(debitedAccountId, creditedAccountId, command.getAmount());

            MessageHelper.addFlashMessage(redirectAttributes, new Message("message.info.transfer.success"));

            return "redirect:/private/bank/accounts.html";

        } catch (UnsufficientBalanceException e) {
            logger.info("insufficient amount");
            result.rejectValue("amount", "message.error.transfer.amount.unsufficientBalance");
        }
    }

    return displayForm(accountNumber, command, model);
}

From source file:org.wallride.web.controller.guest.user.ProfileUpdateController.java

@RequestMapping(method = RequestMethod.PUT)
public String update(@Validated @ModelAttribute(FORM_MODEL_KEY) ProfileUpdateForm form, BindingResult errors,
        AuthorizedUser authorizedUser, RedirectAttributes redirectAttributes) {
    redirectAttributes.addFlashAttribute(FORM_MODEL_KEY, form);
    redirectAttributes.addFlashAttribute(ERRORS_MODEL_KEY, errors);

    if (errors.hasErrors()) {
        return "redirect:/settings/profile?step.edit";
    }//from   w w w.  jav  a 2  s.  co m

    ProfileUpdateRequest request = new ProfileUpdateRequest().withUserId(authorizedUser.getId())
            .withEmail(form.getEmail()).withLoginId(form.getLoginId())
            .withName(form.getName().getFirstName(), form.getName().getLastName());

    User updatedUser;
    try {
        updatedUser = userService.updateProfile(request, authorizedUser);
    } catch (DuplicateLoginIdException e) {
        errors.rejectValue("loginId", "NotDuplicate");
        return "redirect:/settings/profile?step.edit";
    } catch (DuplicateEmailException e) {
        errors.rejectValue("email", "NotDuplicate");
        return "redirect:/settings/profile?step.edit";
    }

    redirectAttributes.getFlashAttributes().clear();
    redirectAttributes.addFlashAttribute("updatedUser", updatedUser);
    return "redirect:/settings/profile";
}

From source file:org.homiefund.web.controllers.SignUpController.java

@PostMapping("/signup/")
public String submit(@Valid @ModelAttribute UserRegistrationForm userRegistrationForm, BindingResult result,
        Model model) {/*from w  ww.  java  2s .c o m*/
    log.info(userRegistrationForm.getName());
    if (result.hasErrors()) {
        clearPasswords(userRegistrationForm);

        return "signup";
    }

    try {
        Optional<InvitationDTO> invitation;
        if (StringUtils.isEmpty(userRegistrationForm.getInviteToken())) {
            invitation = Optional.empty();
        } else {
            InvitationDTO invite = new InvitationDTO();
            invite.setHash(userRegistrationForm.getInviteToken());

            invitation = Optional.of(invite);
        }

        userRegistrationForm.setPassword(bCryptPasswordEncoder.encode(userRegistrationForm.getPassword()));
        registrationService.register(mapper.map(userRegistrationForm, UserDTO.class), invitation);
    } catch (FieldException fe) {
        result.rejectValue(fe.getField(), fe.getMessage());

        clearPasswords(userRegistrationForm);

        return "signup";
    }

    return "redirect:/";
}

From source file:com.wisemapping.ncontroller.UsersController.java

private BindingResult validateRegistrationForm(@NotNull UserBean userBean, @NotNull HttpServletRequest request,
        @NotNull BindingResult bindingResult) {
    final UserValidator userValidator = new UserValidator();
    userValidator.setUserService(userService);
    userValidator.setCaptchaService(captchaService);
    userValidator.validate(userBean, bindingResult);

    // If captcha is enabled, generate it ...
    if (captchaEnabled) {
        final String challenge = request.getParameter("recaptcha_challenge_field");
        final String uresponse = request.getParameter("recaptcha_response_field");

        if (challenge != null && uresponse != null) {
            final String remoteAddr = request.getRemoteAddr();
            final ReCaptchaResponse reCaptchaResponse = captchaService.checkAnswer(remoteAddr, challenge,
                    uresponse);//from   w  w  w. j  a  v  a2 s.c o  m

            if (!reCaptchaResponse.isValid()) {
                bindingResult.rejectValue("captcha", Messages.CAPTCHA_ERROR);
            }

        } else {
            bindingResult.rejectValue("captcha", Messages.CAPTCHA_LOADING_ERROR);
        }
    }
    return bindingResult;
}

From source file:org.wallride.web.controller.guest.user.PasswordResetController.java

@RequestMapping(value = "/{token}", method = RequestMethod.PUT)
public String reset(@PathVariable String token,
        @Validated @ModelAttribute(FORM_MODEL_KEY) PasswordResetForm form, BindingResult errors,
        BlogLanguage blogLanguage, RedirectAttributes redirectAttributes) {
    redirectAttributes.addFlashAttribute(FORM_MODEL_KEY, form);
    redirectAttributes.addFlashAttribute(ERRORS_MODEL_KEY, errors);

    PasswordResetToken passwordResetToken = userService.getPasswordResetToken(token);
    if (passwordResetToken == null) {
        redirectAttributes.addFlashAttribute(INVALID_PASSOWRD_RESET_LINK_ATTR_NAME, true);
        return "redirect:/password-reset";
    }/*from w  ww .ja v  a  2 s . c  o m*/
    LocalDateTime now = LocalDateTime.now();
    if (now.isAfter(passwordResetToken.getExpiredAt())) {
        redirectAttributes.addFlashAttribute(INVALID_PASSOWRD_RESET_LINK_ATTR_NAME, true);
        return "redirect:/password-reset";
    }

    if (!errors.hasFieldErrors("newPassword")) {
        if (!ObjectUtils.nullSafeEquals(form.getNewPassword(), form.getNewPasswordRetype())) {
            errors.rejectValue("newPasswordRetype", "MatchRetype");
        }
    }
    if (errors.hasFieldErrors("newPassword*")) {
        return "redirect:/password-reset/{token}";
    }

    PasswordUpdateRequest request = new PasswordUpdateRequest().withUserId(passwordResetToken.getUser().getId())
            .withPassword(form.getNewPassword()).withLanguage(blogLanguage.getLanguage());
    userService.updatePassword(request, passwordResetToken);

    redirectAttributes.getFlashAttributes().clear();
    return "redirect:/login";
}