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.exxonmobile.ace.hybris.storefront.controllers.pages.PermissionManagementPageController.java

@RequestMapping(value = "/add/save", method = RequestMethod.POST)
@RequireHardLogIn//  ww  w.  j a  v a2 s . c o  m
public String saveNewPermissionDetails(@Valid 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 getAddPermissionPage(model);
    }

    final B2BPermissionData b2BPermissionData = populateB2BPermissionDataFromForm(b2BPermissionForm);
    try {
        b2bCommercePermissionFacade.addPermission(b2BPermissionData);
    } catch (final Exception e) {
        LOG.warn("Exception while saving the permission details " + e);
        if (e instanceof DuplicateUidException) {
            model.addAttribute(b2BPermissionForm);
            bindingResult.rejectValue("code", "text.company.managePermissions.code.exists.error.title");
            GlobalMessages.addErrorMessage(model, "form.global.error");
            return getAddPermissionPage(model);
        }
    }

    storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManagePermissionsBreadcrumb();
    model.addAttribute("breadcrumbs", breadcrumbs);
    GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
            "text.confirmation.permission.created");
    return String.format(REDIRECT_TO_PERMISSION_DETAILS, b2BPermissionData.getCode());
}

From source file:com.trenako.web.controllers.admin.AdminBrandsController.java

/**
 * It creates a new {@code Brand} using the posted form values.
 * <p/>//from w ww.  j a  va2s .com
 * <p>
 * <pre><blockquote>
 * {@code POST /brands}
 * </blockquote></pre>
 * </p>
 *
 * @param form          the form for {@code Brand} to be created
 * @param bindingResult the validation results
 * @param model         the model
 * @param redirectAtts  the redirect attributes
 * @return the view name
 * @throws IOException
 */
@RequestMapping(method = RequestMethod.POST)
public String create(@Valid @ModelAttribute BrandForm form, BindingResult bindingResult, ModelMap model,
        RedirectAttributes redirectAtts) throws IOException {

    if (bindingResult.hasErrors()) {
        LogUtils.logValidationErrors(log, bindingResult);
        model.addAttribute(BrandForm.rejectedForm(form, formService));
        return "brand/new";
    }

    Brand brand = form.getBrand();
    MultipartFile file = form.getFile();
    try {
        service.save(brand);
        if (!file.isEmpty()) {
            imgService.saveImageWithThumb(UploadRequest.create(brand, file), 50);
        }

        BRAND_CREATED_MSG.appendToRedirect(redirectAtts);
        return "redirect:/admin/brands";
    } catch (DuplicateKeyException dke) {
        LogUtils.logException(log, dke);
        bindingResult.rejectValue("brand.name", "brand.name.already.used");
    } catch (DataAccessException dae) {
        LogUtils.logException(log, dae);
        BRAND_DB_ERROR_MSG.appendToModel(model);
    }

    model.addAttribute(BrandForm.rejectedForm(form, formService));
    return "brand/new";
}

From source file:com.miserablemind.butter.apps.butterApp.controller.guest.SignUpController.java

/**
 * Handles POST data after user submits sign up form.
 *
 * @param signUpForm   the data of the form user submitted signing up
 * @param result       result of the binding data to SignUpForm
 * @param request      HTTP request to get the user session for manual log in in case of sign up success
 * @param redirectData autowired RedirectAttributes object to pass flash attributes to, so the method after redirect knows it was not accessed directly.
 * @return in case of failure logical name of the same view, otherwise redirect to a thank you page
 *//*from  ww  w  . j a v  a 2  s.  c om*/
@RequestMapping(method = RequestMethod.POST)
public String handlePost(@ModelAttribute("signUpForm") @Valid SignUpForm signUpForm, BindingResult result,
        HttpServletRequest request, RedirectAttributes redirectData) {

    if (result.hasErrors())
        return "guest/signup";

    try {
        String encodedPassword = this.passwordEncoder.encode(signUpForm.getPassword());
        AppUser userForRegistration = new AppUser(null, encodedPassword, signUpForm.getEmail(), false,
                signUpForm.getUsername(), true, new Date(), new Date());

        String verificationToken = Utilities.generateUUID();
        this.userManager.registerUser(userForRegistration, verificationToken);

        AppUser appUser = this.manuallyLogUserIn(signUpForm, request);
        this.emailManager.sendEmailVerification(appUser, verificationToken, this.appConfig);

        redirectData.addFlashAttribute(REDIRECTED_FROM_POST, true);

        return "redirect:" + "/signup/thank-you";
    } catch (UserTakenException e) {
        if (e.isUsernameTaken())
            result.rejectValue("username", "UsernameExists");
        if (e.isEmailTaken())
            result.rejectValue("email", "EmailExists");
    }

    return "guest/signup";
}

From source file:com.trenako.web.controllers.admin.AdminRailwaysController.java

/**
 * It creates a new {@code Railway} using the posted form values.
 * <p/>/*  w w w .ja  v a  2  s .c om*/
 * <p>
 * <pre><blockquote>
 * {@code POST /admin/railways}
 * </blockquote></pre>
 * </p>
 *
 * @param railwayForm   the form for the {@code Railway} to be added
 * @param bindingResult the validation results
 * @param model         the model
 * @param redirectAtts  the redirect attributes
 * @return the view name
 * @throws IOException
 */
@RequestMapping(method = RequestMethod.POST)
public String create(@Valid @ModelAttribute RailwayForm railwayForm, BindingResult bindingResult,
        ModelMap model, RedirectAttributes redirectAtts) throws IOException {

    if (bindingResult.hasErrors()) {
        LogUtils.logValidationErrors(log, bindingResult);
        model.addAttribute(railwayForm);
        return "railway/new";
    }

    Railway railway = railwayForm.getRailway();
    MultipartFile file = railwayForm.getFile();
    try {
        service.save(railway);
        if (file != null && !file.isEmpty()) {
            imgService.saveImageWithThumb(UploadRequest.create(railway, file), 50);
        }

        RAILWAY_CREATED_MSG.appendToRedirect(redirectAtts);
        return "redirect:/admin/railways";
    } catch (DuplicateKeyException dke) {
        LogUtils.logException(log, dke);
        bindingResult.rejectValue("railway.name", "railway.name.already.used");
    } catch (DataAccessException dae) {
        LogUtils.logException(log, dae);
        RAILWAY_DB_ERROR_MSG.appendToModel(model);
    }

    model.addAttribute(railwayForm);
    return "railway/new";
}

From source file:org.jtalks.common.web.controller.UserController.java

/**
 * Update user profile info. Check if the user enter valid data and update profile in database.
 * In error case return into the edit profile page and draw the error.
 *
 * @param userDto dto populated by user/*from  www.jav a 2s . com*/
 * @param result  binding result which contains the validation result
 * @return in case of errors return back to edit profile page, in another case return to user detalis page
 * @throws NotFoundException   - throws if current logged in user was not found
 * @throws java.io.IOException - throws in case of access errors (if the temporary store fails)
 */
@RequestMapping(value = "/user/edit", method = RequestMethod.POST)
public ModelAndView editProfile(@Valid @ModelAttribute(EDITED_USER) EditUserProfileDto userDto,
        BindingResult result) throws NotFoundException, IOException {

    User user = securityService.getCurrentUser();

    if (result.hasErrors()) {
        //we should show current user avatar (if any)
        //if no file was uploaded, or if there were validation errors on avatar field
        if ((userDto.getAvatar().getSize() == 0) || (result.hasFieldErrors("avatar"))) {
            userDto.setAvatar(
                    new MockMultipartFile("avatar", "", ImageFormats.JPG.getContentType(), user.getAvatar()));
        }
        return new ModelAndView(EDIT_PROFILE, EDITED_USER, userDto);
    }

    User editedUser;
    try {
        editedUser = userService.editUserProfile(userDto.getEmail(), userDto.getFirstName(),
                userDto.getLastName(), userDto.getCurrentUserPassword(), userDto.getNewUserPassword(),
                userDto.getAvatar().getBytes());
    } catch (DuplicateEmailException e) {
        result.rejectValue("email", "validation.duplicateemail");
        return new ModelAndView(EDIT_PROFILE);
    } catch (WrongPasswordException e) {
        result.rejectValue("currentUserPassword", "label.incorrectCurrentPassword",
                "Password does not match to the current password");
        return new ModelAndView(EDIT_PROFILE);
    }
    return new ModelAndView(new StringBuilder().append("redirect:/user/")
            .append(editedUser.getEncodedUsername()).append(".html").toString());
}

From source file:com.virtusa.akura.common.controller.ManageGradeController.java

/**
 * This method handles Add/Edit Grade and ClassGrade details.
 * //  w  ww .  j a  v a2  s. com
 * @param grade - Grade obj.
 * @param request - HttpServletRequest
 * @param model {@link ModelMap}
 * @param bindingResult - holds errors
 * @return name of the view which is redirected to.
 * @throws AkuraAppException - throw detailed exception.
 */
@RequestMapping(value = REQ_MAP_VALUE_SAVEORUPDATE, method = RequestMethod.POST)
public String saveOrUpdateClassGrade(@ModelAttribute(MODEL_ATT_GRADE) Grade grade, BindingResult bindingResult,
        HttpServletRequest request, ModelMap model) throws AkuraAppException {

    gradeValidator.validate(grade, bindingResult);
    String gradeName = grade.getDescription().trim();
    String selectedGradeName = request.getParameter(REQ_SELECTEDGRADE);

    if (bindingResult.hasErrors() || (request.getParameterValues(REQ_CLASS_ID) == null)
            || "".equals(gradeName)) {
        if ((request.getParameterValues(REQ_CLASS_ID) == null) || "".equals(gradeName)) {

            model.addAttribute(EDITPANE, EDITPANE);
            model.addAttribute(SELECTED_OBJ_ID, selectedGradeName);
            bindingResult.rejectValue(FIELD_NAME, AkuraWebConstant.MANDATORY_FIELD_ERROR_CODE);
        }
        // model.addAttribute(EDITPANE, grade.getGradeId());
        model.addAttribute(EDITPANE, EDITPANE);
        model.addAttribute(SELECTED_OBJ_ID, selectedGradeName);
        return VIEW_GET_MANAGE_GRADE;
    } else {

        // Check whether the grade is already exist and populate a message
        // to user.
        if (isExistsGrade(gradeName, selectedGradeName)) {
            String message = new ErrorMsgLoader().getErrorMessage(ERROR_MSG_KEY);
            Grade newGrade = new Grade();

            model.addAttribute(EDITPANE, EDITPANE);
            model.addAttribute(SELECTED_OBJ_ID, selectedGradeName);
            model.addAttribute(MODEL_ATT_GRADE, newGrade);
            model.addAttribute(MESSAGE, message);
            return VIEW_GET_MANAGE_GRADE;
        } else {

            try {
                // If selectedGradeName is empty, add a new grade otherwise
                // update already existing grade.
                grade = saveorUpdateGrade(grade, gradeName, selectedGradeName);

                // Gets the classes for the selected grade.
                String[] oldClassIds = getClassesForGrade(grade);

                // There is no update for class_grade table, we have
                // add/remove or add&remove, so that we use the below logic to be done.

                // checked(from check boxes) new ids of classes
                String[] classIds = request.getParameterValues(REQ_CLASS_ID);

                // add new classes for the garde.
                addClassesForGrade(grade, classIds, oldClassIds);

                // Remove old clsses from the grade.
                removeClassesFromGrade(grade, oldClassIds, classIds);

                // update ClassGrade description of existing records.
                updateClassGradeDescription(grade);

            } catch (AkuraAppException e) {
                if (e.getCause() instanceof DataIntegrityViolationException) {
                    String message = new ErrorMsgLoader().getErrorMessage(ERROR_MSG_EDIT);
                    Grade newGrade = new Grade();
                    model.addAttribute(EDITPANE, EDITPANE);
                    model.addAttribute(SELECTED_OBJ_ID, selectedGradeName);
                    model.addAttribute(MODEL_ATT_GRADE, newGrade);
                    model.addAttribute(MESSAGE, message);

                    return VIEW_GET_MANAGE_GRADE;
                } else {
                    throw e;
                }
            }
        }
    }
    return VIEW_POST_MANAGE_GRADE;
}

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

@RequestMapping(value = "/upload_logo", method = RequestMethod.POST)
@ResponseBody//from w  w  w . ja  va2 s . c  om
public String uploadServiceInstanceLogo(@ModelAttribute("serviceInstanceLogoForm") ServiceInstanceLogoForm form,
        BindingResult result, HttpServletRequest request, ModelMap map) {

    logger.debug("### upload service instance logo method starting...(POST)");
    String fileSize = checkFileUploadMaxSizeException(request);
    if (fileSize != null) {
        result.rejectValue("logo", "error.image.max.upload.size.exceeded");

        return messageSource.getMessage(result.getFieldError("logo").getCode(), new Object[] { fileSize },
                request.getLocale());

    }
    String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    if (StringUtils.isNotBlank(rootImageDir)) {
        ServiceInstance serviceInstance = form.getServiceInstance();
        ServiceInstanceLogoFormValidator validator = new ServiceInstanceLogoFormValidator();
        validator.validate(form, result);
        if (result.hasErrors()) {
            return messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale());
        } else {
            setImagePath(rootImageDir, serviceInstance, form.getLogo());
        }
        return "success";
    } else {
        result.rejectValue("logo", "error.custom.image.upload.dir");
        return messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale());
    }
}

From source file:com.spd.ukraine.lucenewebsearch1.web.IndexingController.java

/**
 * Method used to create indexing for entered web page content and web 
 * pages referenced from given web page.
 *
 * @param webPage webPage.url == entered web-page url
 * @param result used to detect errors in form
 * @param request for future code/* ww  w. ja  v  a2  s .  co m*/
 * @param errors for future code
 * @return model of the success view or that of the create indexing page
 */
@RequestMapping(value = "/indexing", method = RequestMethod.POST)
public ModelAndView startIndexing(@ModelAttribute("q") @Valid WebPage webPage, BindingResult result,
        WebRequest request, Errors errors) {
    System.out.println("start indexing q = " + webPage.getUrl());
    int maxRecursion = MAX_RECURSION_SEARCH_NUMBER;
    try {
        maxRecursion = Integer.parseInt(webPage.getTitle());
    } catch (NumberFormatException e) {

    }
    MAX_RECURSION_SEARCH_NUMBER = Math.abs(maxRecursion);
    WebPage created = new WebPage();
    if (!result.hasErrors()) {
        System.out.println("!result.hasErrors()");
        created = createWebPageRecord(webPage);
    }
    if (created == null) {
        System.out.println("created == null");
        result.rejectValue("url", "label.not.reached.address");
    }
    if (result.hasErrors()) {
        System.out.println("result.hasErrors()");
        ModelAndView model = new ModelAndView("index");
        model.addObject("q", webPage);
        return model;
    } else {
        ModelAndView model = new ModelAndView("root");
        model.addObject("q", new WebPage());
        return model;
    }
}

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

/**
 * Add staffEducationQualification details in to system.
 * //from  w ww  .j  a va  2  s . com
 * @param wrapperQualification - {@link wrapperQualification}
 * @param bindingResult - {@link BindingResult}
 * @param model - {@link ModelMap}
 * @return view of the staff qualifications details.
 * @throws AkuraAppException - throw detailed exception.
 */
@RequestMapping(value = SAVE_STAFF_EDUCATION_QUALIFICATION, method = RequestMethod.POST)
public String saveStaffEducationQualificationDetails(
        @ModelAttribute(MODEL_ATT_WRAPPER_QUALIFICATION) WrapperQualification wrapperQualification,
        BindingResult bindingResult, ModelMap model) throws AkuraAppException {

    StaffEducation staffEducation = wrapperQualification.getStaffEducation();
    staffEducationValidator.validate(staffEducation, bindingResult);

    if (bindingResult.hasErrors()) {
        return VIEW_STAFF_MEMBER_QUALIFICATION;
    } else {
        // save Education qualification
        boolean isNew = false;
        try {
            if (staffEducation.getStaffEducationId() != 0) {
                staffService.updateStaffEducation(staffEducation);
            } else {
                isNew = true;
                staffService.addStaffEducation(staffEducation);
            }

        } catch (AkuraAppException e) {
            if (e.getCause() instanceof DataIntegrityViolationException) {
                bindingResult.rejectValue(ERROR_EDUCATIONAL_QUALIFICATION_ID, STQ_UI_DUPLICATE_DESCRIPTION);
            }
            if (isNew) {
                staffEducation.setStaffEducationId(0);
                wrapperQualification.setStaffEducation(staffEducation);
                model.addAttribute(MODEL_ATT_WRAPPER_QUALIFICATION, wrapperQualification);
            }
            return VIEW_STAFF_MEMBER_QUALIFICATION;
        }
    }
    return REDIRECT_STAFF_QUALIFICATIONS;
}

From source file:org.jasig.portlet.cms.controller.EditPostController.java

private void savePost(final ActionRequest request, final BindingResult result, Post post,
        boolean postIsScheduled, String scheduledDate, boolean removeExistingPost)
        throws PortletRequestBindingException, JcrRepositoryException {

    final PortletPreferencesWrapper pref = new PortletPreferencesWrapper(request);
    final Calendar cldr = Calendar.getInstance(request.getLocale());

    final DateTimeZone zone = DateTimeZone.forTimeZone(cldr.getTimeZone());
    final DateTime today = new DateTime(zone);

    final DateTimeFormatter fmt = DateTimeFormat.forPattern(PortletPreferencesWrapper.DEFAULT_POST_DATE_FORMAT);
    post.setLastModifiedDate(today.toString(fmt));

    post.setLanguage(request.getLocale().getLanguage());

    if (postIsScheduled) {
        if (StringUtils.isBlank(scheduledDate))
            result.rejectValue("scheduledDate", "invalid.scheduled.post.publish.date");
        else {/*from w w  w  . java  2  s.c  o  m*/

            logDebug("Post is scheduled to be published on " + scheduledDate);
            final DateTime dt = DateTime.parse(scheduledDate, fmt);
            post.setScheduledDate(dt.toString(fmt));

            if (removeExistingPost) {
                if (getRepositoryDao().exists(post.getPath())) {
                    logDebug("Preparing scheduled post. Removing existing post at " + post.getPath());
                    getRepositoryDao().removePost(post.getPath());
                }
            }

            getRepositoryDao().schedulePost(post, pref.getPortletRepositoryRoot());
            ensureRepositoryRootIsScheduled(pref);
        }
    } else {
        post = preparePost(post, request);

        getRepositoryDao().setPost(post);
    }
}