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.virtusa.akura.staff.controller.StaffDetailsController.java

/**
 * Validtaes the core subjects./*from ww  w  . ja  va2s  . co  m*/
 * 
 * @param staff the staff
 * @param bindingResult the binding results.
 * @return the validate.
 * @throws AkuraAppException AkuraAppException.
 */
private boolean validateCoreSubject(Staff staff, BindingResult bindingResult) throws AkuraAppException {

    boolean isAcademicCategory = false;
    int cID = staff.getStaffCategory().getCatogaryID();
    if (cID != 0) {
        isAcademicCategory = staffCommonService.isAcademicStaffCategory(cID);
    }
    if (isAcademicCategory) {
        if (staff.getCoreSubject().getSubjectId() == 0) {

            bindingResult.rejectValue(CORE_SUBJECT, AkuraWebConstant.MANDATORY_FIELD_ERROR_CODE);

        } else if (staff.getStudyMedium().getStudyMediumId() == 0) {

            bindingResult.rejectValue(STUDY_MEDIUM, AkuraWebConstant.MANDATORY_FIELD_ERROR_CODE);

        }
    }
    return isAcademicCategory;
}

From source file:com.virtusa.akura.staff.controller.StaffDetailsController.java

/**
 * handles when DataIntegrity violation occur.
 * // w  ww .  ja va  2 s .c  o m
 * @param staff -Staff
 * @param bindingResult -BindingResult
 * @param model -ModelMap
 * @param isNew -boolean
 * @throws AkuraAppException - detail exception during the processing
 */
private void handleDataIntegrityViolation(Staff staff, BindingResult bindingResult, ModelMap model,
        boolean isNew) throws AkuraAppException {

    String imagePath = RESOURCES_NO_PROFILE_IMAGE;
    if (staff != null) {
        Staff staffDB = staffService.findStaff(staff.getStaffId());
        if (staffDB != null) {
            imagePath = getImagePath(staff, imagePath, staffDB);
        }
    }
    bindingResult.rejectValue(STAFF_ID, DUPLICATE_DESCRIPTION_MESSAGE);
    if (isNew) {
        staff.setStaffId(0);
        model.addAttribute(MODEL_ATT_STAFF, staff);
    }
    model.addAttribute(IMAGE_PATH, imagePath);

}

From source file:org.training.storefront.controllers.pages.AbstractRegisterPageController.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./*from   w w  w . ja  v a 2  s . c om*/
 * 
 * @return true if there are no binding errors or the account does not already exists.
 * @throws CMSItemNotFoundException
 */
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());
    data.setMaritalStatus(form.getMaritalStatus());
    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());
        bindingResult.rejectValue("email", "registration.error.account.exists.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return handleRegistrationError(model);
    }

    return REDIRECT_PREFIX + getSuccessRedirect(request, response);
}

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

@RequestMapping(value = "/create", method = RequestMethod.POST)
@RequireHardLogIn/*from   w w w .j a v a2 s.  c o m*/
public String createUserGroup(@Valid final B2BUserGroupForm userGroupForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectModel) throws CMSItemNotFoundException {
    storeCmsPageInModel(model, getContentPageForLabelOrId(MANAGE_USERGROUPS_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(MANAGE_USERGROUPS_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManageUserGroupBreadCrumbs();
    breadcrumbs.add(new Breadcrumb("/my-company/organization-management/manage-usergroups/create",
            getMessageSource().getMessage("text.company.manageUsergroups.createUsergroup.breadcrumb", null,
                    "Create Usergroup ", getI18nService().getCurrentLocale()),
            null));
    model.addAttribute("breadcrumbs", breadcrumbs);

    if (bindingResult.hasErrors()) {
        GlobalMessages.addErrorMessage(model, "form.global.error");
        model.addAttribute(userGroupForm);
        return createUserGroup(model);

    }
    if (b2bUserGroupFacade.getUserGroupDataForUid(userGroupForm.getUid()) != null) {
        // a unit uid is not unique
        GlobalMessages.addErrorMessage(model, "form.global.error");
        bindingResult.rejectValue("uid", "form.b2busergroup.notunique");
        model.addAttribute(userGroupForm);
        return createUserGroup(model);
    }

    final B2BUserGroupData userGroupData = new B2BUserGroupData();
    userGroupData.setUid(userGroupForm.getUid());
    userGroupData.setName(userGroupForm.getName());
    if (StringUtils.isNotBlank(userGroupForm.getParentUnit())) {
        userGroupData.setUnit(b2bUnitFacade.getUnitForUid(userGroupForm.getParentUnit()));
    }

    b2bUserGroupFacade.updateUserGroup(userGroupForm.getUid(), userGroupData);

    GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
            "form.b2busergroup.success");

    return String.format(REDIRECT_TO_USERGROUP_DETAILS, urlEncode(userGroupForm.getUid()));
}

From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.B2BUserGroupManagementPageController.java

@RequestMapping(value = "/create", method = RequestMethod.POST)
@RequireHardLogIn//from   w  w  w. j  ava 2s .c om
public String createUserGroup(@Valid final B2BUserGroupForm userGroupForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectModel) throws CMSItemNotFoundException {
    storeCmsPageInModel(model, getContentPageForLabelOrId(MANAGE_USERGROUPS_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(MANAGE_USERGROUPS_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManageUserGroupBreadCrumbs();
    breadcrumbs.add(new Breadcrumb("/my-company/organization-management/manage-usergroups/create",
            getMessageSource().getMessage("text.company.manageUsergroups.createUsergroup.breadcrumb", null,
                    "Create Usergroup ", getI18nService().getCurrentLocale()),
            null));
    model.addAttribute("breadcrumbs", breadcrumbs);

    if (bindingResult.hasErrors()) {
        GlobalMessages.addErrorMessage(model, "form.global.error");
        model.addAttribute(userGroupForm);
        return createUserGroup(model);

    }
    if (b2bCommerceB2BUserGroupFacade.getUserGroupDataForUid(userGroupForm.getUid()) != null) {
        // a unit uid is not unique
        GlobalMessages.addErrorMessage(model, "form.global.error");
        bindingResult.rejectValue("uid", "form.b2busergroup.notunique");
        model.addAttribute(userGroupForm);
        return createUserGroup(model);
    }

    final B2BUserGroupData userGroupData = new B2BUserGroupData();
    userGroupData.setUid(userGroupForm.getUid());
    userGroupData.setName(userGroupForm.getName());
    if (StringUtils.isNotBlank(userGroupForm.getParentUnit())) {
        userGroupData.setUnit(companyB2BCommerceFacade.getUnitForUid(userGroupForm.getParentUnit()));
    }

    try {
        b2bCommerceB2BUserGroupFacade.updateUserGroup(userGroupForm.getUid(), userGroupData);
    } catch (final DuplicateUidException e) {
        GlobalMessages.addErrorMessage(model, "form.global.error");
        bindingResult.rejectValue("uid", "form.b2busergroup.notunique");
        return createUserGroup(model);
    }

    GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
            "form.b2busergroup.success");

    return String.format(REDIRECT_TO_USERGROUP_DETAILS, urlEncode(userGroupForm.getUid()));
}

From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.MyCompanyPageController.java

public String editPermission(final B2BPermissionForm b2BPermissionForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectModel)
        throws CMSItemNotFoundException, ParseException {
    b2BPermissionFormValidator.validate(b2BPermissionForm, bindingResult);
    if (bindingResult.hasErrors()) {
        model.addAttribute(b2BPermissionForm);
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return editPermission(b2BPermissionForm.getOriginalCode(), model);
    }/*ww w  . j a va  2  s. co m*/

    final B2BPermissionData b2BPermissionData = populateB2BPermissionDataFromForm(b2BPermissionForm);
    try {
        b2bCommercePermissionFacade.updatePermissionDetails(b2BPermissionData);
    } catch (final Exception e) {
        LOG.warn("Exception while saving the permission details " + e);
        model.addAttribute(b2BPermissionForm);
        GlobalMessages.addErrorMessage(model, "form.global.error");
        bindingResult.rejectValue("code", "text.company.managePermissions.code.exists.error.title");
        return editPermission(b2BPermissionForm.getOriginalCode(), model);
    }
    storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManagePermissionsBreadcrumb();
    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.permission.updated");
    return String.format(REDIRECT_TO_PERMISSION_DETAILS, urlEncode(b2BPermissionData.getCode()));
}

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

@RequestMapping(value = ("/editlogo"), method = RequestMethod.POST)
@ResponseBody/*  w  w  w.ja  v a2  s  .  co m*/
public String editProductLogo(@ModelAttribute("productLogoForm") ProductLogoForm form, BindingResult result,
        HttpServletRequest request, ModelMap map) {
    logger.debug("### edit product logo method starting...(POST)");
    String fileSize = checkFileUploadMaxSizeException(request);
    if (fileSize != null) {
        result.rejectValue("logo", "error.image.max.upload.size.exceeded");
        JsonObject error = new JsonObject();
        error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(),
                new Object[] { fileSize }, request.getLocale()));
        return error.toString();
    }

    String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    if (rootImageDir != null && !rootImageDir.trim().equals("")) {
        Product product = form.getProduct();
        ProductLogoFormValidator validator = new ProductLogoFormValidator();
        validator.validate(form, result);
        if (result.hasErrors()) {
            setPage(map, Page.PRODUCTS);
            JsonObject error = new JsonObject();
            error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(),
                    null, request.getLocale()));
            return error.toString();
        } else {
            try {
                product = productService.editProductLogo(product, form.getLogo());
            } catch (FileUploadException e) {
                logger.debug("###IO Exception in writing custom image file", e);
                result.rejectValue("logo", "error.uploading.file");
                JsonObject error = new JsonObject();
                error.addProperty("errormessage", messageSource
                        .getMessage(result.getFieldError("logo").getCode(), null, request.getLocale()));
                return error.toString();
            }
        }
        String response = null;
        try {
            response = JSONUtils.toJSONString(product);
        } catch (JsonGenerationException e) {
            logger.debug("###IO Exception in writing custom image file");
        } catch (JsonMappingException e) {
            logger.debug("###IO Exception in writing custom image file");
        } catch (IOException e) {
            logger.debug("###IO Exception in writing custom image file");
        }
        return response;
    } else {
        result.rejectValue("logo", "error.custom.image.upload.dir");
        setPage(map, Page.PRODUCTS);
        JsonObject error = new JsonObject();
        error.addProperty("errormessage",
                messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale()));
        return error.toString();
    }
}

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

public String editPermission(final B2BPermissionForm b2BPermissionForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectModel)
        throws CMSItemNotFoundException, ParseException {
    b2BPermissionFormValidator.validate(b2BPermissionForm, bindingResult);
    if (bindingResult.hasErrors()) {
        model.addAttribute(b2BPermissionForm);
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return editPermission(b2BPermissionForm.getOriginalCode(), model);
    }//from  w w  w.j  a va2 s.  c o  m

    final B2BPermissionData b2BPermissionData = populateB2BPermissionDataFromForm(b2BPermissionForm);
    try {
        b2bPermissionFacade.updatePermissionDetails(b2BPermissionData);
    } catch (final Exception e) {
        LOG.warn("Exception while saving the permission details " + e);
        model.addAttribute(b2BPermissionForm);
        GlobalMessages.addErrorMessage(model, "form.global.error");
        bindingResult.rejectValue("code", "text.company.managePermissions.code.exists.error.title");
        return editPermission(b2BPermissionForm.getOriginalCode(), model);
    }
    storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManagePermissionsBreadcrumb();
    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.permission.updated");
    return String.format(REDIRECT_TO_PERMISSION_DETAILS, urlEncode(b2BPermissionData.getCode()));
}

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

@RequestMapping(value = ("/editlogo"), method = RequestMethod.POST)
@ResponseBody/* w w w.  j a  va  2s . c  om*/
public String editChannelLogo(@ModelAttribute("channelLogoForm") ChannelLogoForm form, BindingResult result,
        HttpServletRequest request, ModelMap map) {
    logger.debug("### editChannelLogo method starting...(POST)");
    String fileSize = checkFileUploadMaxSizeException(request);
    if (fileSize != null) {
        result.rejectValue("logo", "error.image.max.upload.size.exceeded");
        JsonObject error = new JsonObject();
        error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(),
                new Object[] { fileSize }, request.getLocale()));
        return error.toString();
    }
    String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    if (rootImageDir != null && !rootImageDir.trim().equals("")) {
        Channel channel = channelService.getChannelById(form.getChannel().getId().toString());
        ChannelLogoFormValidator validator = new ChannelLogoFormValidator();
        validator.validate(form, result);
        if (result.hasErrors()) {
            JsonObject error = new JsonObject();
            setPage(map, Page.CHANNELS);
            error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(),
                    null, request.getLocale()));
            return error.toString();
        } else {
            String channelsDir = "channels";
            File file = new File(FilenameUtils.concat(rootImageDir, channelsDir));
            if (!file.exists()) {
                file.mkdir();
            }
            String channelsAbsoluteDir = FilenameUtils.concat(rootImageDir, channelsDir);
            String relativeImageDir = FilenameUtils.concat(channelsDir, channel.getId().toString());
            File file1 = new File(FilenameUtils.concat(channelsAbsoluteDir, channel.getId().toString()));
            if (!file1.exists()) {
                file1.mkdir();
            }

            MultipartFile logoFile = form.getLogo();
            try {
                if (!logoFile.getOriginalFilename().trim().equals("")) {
                    String logoFileRelativePath = writeMultiPartFileToLocalFile(rootImageDir, relativeImageDir,
                            logoFile);
                    channel.setImagePath(logoFileRelativePath);
                }
                channelService.updateChannel(channel);
            } catch (IOException e) {
                logger.debug("###IO Exception in writing custom image file");
            }
        }
        String response = null;
        try {
            response = JSONUtils
                    .toJSONString(channelService.getChannelById(form.getChannel().getId().toString()));
        } catch (JsonGenerationException e) {
            logger.debug("###IO Exception in writing custom image file");
        } catch (JsonMappingException e) {
            logger.debug("###IO Exception in writing custom image file");
        } catch (IOException e) {
            logger.debug("###IO Exception in writing custom image file");
        }
        logger.debug("### editChannelLogo method ending (Success)...(POST)");
        return response;
    } else {
        result.rejectValue("logo", "error.custom.image.upload.dir");
        setPage(map, Page.CHANNELS);
        JsonObject error = new JsonObject();
        error.addProperty("errormessage",
                messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale()));
        logger.debug("### editChannelLogo method ending (No Image Logo Dir Defined)...(POST)");
        return error.toString();
    }
}

From source file:com.virtusa.akura.user.controller.CreateSystemUserController.java

/**
 * This method handles add new system user.
 * /*from  ww w. ja  va 2  s  .  c o m*/
 * @param userLogin - UserLogin obj.
 * @param result - BindingResult.
 * @param model - {@link ModelMap}
 * @param session - {@link HttpSession}
 * @param request - {@link HttpServletRequest}
 * @throws AkuraAppException - AkuraAppException.
 * @return name of the view which is redirected to.
 */
@RequestMapping(value = CREATE_OR_UPDATE_URL, method = RequestMethod.POST)
public String createOrUpdateSystemUser(@ModelAttribute(MODEL_ATT_USER_DETAIL) UserLogin userLogin,
        BindingResult result, ModelMap model, HttpSession session, HttpServletRequest request)
        throws AkuraAppException {

    /* initialize the variables */
    String dispatchUrl = VIEW_CREATE_SYSTEM_USER;
    String identificationNo = "";
    String message = "";
    String successMessage = "";
    String confirmPassword = request.getParameter(REQ_CONFIRM_PASSWORD);
    boolean isNewUser = true;

    /* get the user Identification no and replace with identification key */
    identificationNo = userLogin.getUserIdentificationNo();

    /* validate the userLogin */
    systemUserValidator.validate(userLogin, result);

    if (result.hasErrors() || !userLogin.getPassword().equals(confirmPassword)) {
        // validate the password
        if (!result.hasErrors() && !userLogin.getPassword().equals(confirmPassword)) {
            result.rejectValue(PASSWORD, ERROR_MSG_PASSWORD_ERROR);
        }
    } else {
        try {

            /* save or update user */
            if (userLogin.getUserLoginId() == 0) {
                userService.createSystemUser(userLogin);
            } else {
                isNewUser = false;
                userService.editSystemUser(userLogin);
            }

            /* send the mail */
            boolean status = this.sendConfirmationMailNew(userLogin, userLogin.getPassword(), session, model);

            if (status && isNewUser) {
                successMessage = new ErrorMsgLoader().getErrorMessage(SUCCESS_MSG_SYS_USER);
                dispatchUrl = showSystemUserDetailForm(model);
            } else if (status && !isNewUser) {
                successMessage = new ErrorMsgLoader().getErrorMessage(SUCCESS_MSG_SYS_USER_EDIT);
                dispatchUrl = showSystemUserDetailForm(model);
            }

        } catch (MailException e) {
            LOG.error("Err or Sending Mail ( createOrUpdateSystemUser method )" + e);
            if (!isNewUser) {
                message = new ErrorMsgLoader().getErrorMessage(MSG_SYSTEM_USER_EDITED_MAIL);
            } else {
                message = new ErrorMsgLoader().getErrorMessage(MSG_SYSTEM_USER_MAIL);
            }
        } catch (IllegalArgumentException e) {
            LOG.error("Error Sending Mail ( createOrUpdateSystemUser method )" + e);
            message = new ErrorMsgLoader().getErrorMessage(MSG_SYSTEM_USER_MAIL);
        } catch (ResourceNotFoundException e) {
            LOG.error("Error Sending Mail ( createOrUpdateSystemUser method )" + e);
            message = new ErrorMsgLoader().getErrorMessage(MSG_SYSTEM_USER_MAIL);
        } catch (UniqueUserNameEmailException e) {
            message = e.getErrorCode();
            dispatchUrl = showSystemUserDetailForm(model);
        } catch (InvalidIdentificationNoException e) {
            message = e.getErrorCode();
            dispatchUrl = showSystemUserDetailForm(model);
        } catch (PastStaffException e) {
            message = e.getErrorCode();
            dispatchUrl = showSystemUserDetailForm(model);
        } catch (NonCurrentStudentUserLoginCreationException e) {
            message = e.getErrorCode();
            dispatchUrl = showSystemUserDetailForm(model);
        } catch (AkuraAppException e) {
            message = e.getErrorCode();
            dispatchUrl = showSystemUserDetailForm(model);
        }
    }

    /* set model attributes */
    model.addAttribute(MODEL_ATT_MESSAGE, message);
    model.addAttribute(MODEL_ATT_MESSAGE_SUCCESS, successMessage);
    model.addAttribute(MODEL_ATT_USER_IDENTIFICATION_NO, identificationNo);

    return dispatchUrl;
}