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:org.hoteia.qalingo.core.web.mvc.controller.AbstractQalingoController.java

protected void addMessageError(BindingResult result, Exception e, String formKey, String fieldKey,
        String errorMessage) {//from   w  w  w. j  av  a 2 s  . c  o  m
    if (StringUtils.isEmpty(errorMessage)) {
        errorMessage = ""; // EMPTY VALUE TO EVENT VELOCITY MethodInvocationException
    }
    FieldError error = new FieldError(formKey, fieldKey, errorMessage);
    result.addError(error);
    result.rejectValue(error.getField(), "");
    if (e != null) {
        logger.error(errorMessage, e);
    } else {
        logger.warn(errorMessage);
    }
}

From source file:org.ojbc.web.portal.validators.ArrestSubscriptionAddValidator.java

public void validate(Subscription subscription, BindingResult errors) {

    logger.info("* * * inside validate()");

    if (subscription == null) {
        return;//ww w.ja  v a 2 s. c  o  m
    }

    Map<String, String> fieldToErrorMap = getValidationErrorsList(subscription);

    if (fieldToErrorMap == null) {
        return;
    }

    for (String iField : fieldToErrorMap.keySet()) {

        String errorMessage = fieldToErrorMap.get(iField);

        errors.rejectValue(iField, errorMessage);
    }

}

From source file:org.ojbc.web.portal.validators.IncidentSubscriptionAddValidator.java

public void validate(Subscription subscription, BindingResult errors) {

    logger.info("* * * inside validate()");

    String topic = subscription.getSubscriptionType();
    if (StringUtils.isBlank(topic)) {
        errors.rejectValue("subscriptionType", "Subscription type must be specified");
    }/*www  . ja  va 2 s. co m*/

    String fName = subscription.getFirstName();
    if (StringUtils.isBlank(fName)) {
        errors.rejectValue("firstName", "First name must be specified");
    }

    String lName = subscription.getLastName();
    if (StringUtils.isBlank(lName)) {
        errors.rejectValue("lastName", "Last name must be specified");
    }

    Date dob = subscription.getDateOfBirth();
    if (dob == null) {
        errors.rejectValue("dateOfBirth", "DOB must be specified");
    }

    Date subStartDate = subscription.getSubscriptionStartDate();
    if (subStartDate == null) {
        errors.rejectValue("subscriptionStartDate", "Start date must be specified");
    }

    Date subEndDate = subscription.getSubscriptionEndDate();
    if (subEndDate != null && subStartDate != null) {
        if (subEndDate.before(subStartDate)) {
            errors.rejectValue("subscriptionEndDate", "End date may not occur before start date");
        }
    }

    boolean hasEmail = false;

    for (String iEmail : subscription.getEmailList()) {
        if (StringUtils.isNotBlank(iEmail)) {
            hasEmail = true;
        }
    }

    if (!hasEmail) {
        errors.rejectValue("emailList", "Email Address must be specified");
    }
}

From source file:org.openmrs.module.reporting.web.reports.renderers.TextTemplateFormController.java

@SuppressWarnings("unchecked")
@RequestMapping(value = "/module/reporting/reports/renderers/previewTextTemplateReportRenderer", method = RequestMethod.POST)
public void previewScript(ModelMap model, HttpServletRequest request,
        @RequestParam(required = true, value = "reportDefinition") String reportDefinitionUuid,
        @RequestParam(required = true, value = "uuid") String uuid,
        @RequestParam(required = false, value = "iframe") String iframe,
        @RequestParam(required = true, value = "script") String script,
        @RequestParam(required = true, value = "scriptType") String scriptType,
        @RequestParam(required = true, value = "rendererType") Class<? extends TextTemplateRenderer> rendererType,
        @ModelAttribute("userParams") UserParams userParams, BindingResult bindingResult)
        throws EvaluationException, UnsupportedEncodingException, ClassNotFoundException,
        InstantiationException, IllegalAccessException {

    ReportDefinitionService rds = Context.getService(ReportDefinitionService.class);
    ReportDefinition reportDefinition = rds.getDefinitionByUuid(reportDefinitionUuid);

    // validate parameters
    if (!reportDefinition.getParameters().isEmpty()) {

        Set<String> requiredParams = new HashSet<String>();
        for (Parameter parameter : reportDefinition.getParameters()) {
            requiredParams.add(parameter.getName());
        }/*from  ww w.  j  a  v a 2s.  c  o m*/
        for (Map.Entry<String, Object> e : userParams.getUserEnteredParams().entrySet()) {
            if (e.getValue() instanceof Iterable || e.getValue() instanceof Object[]) {
                Object iterable = e.getValue();
                if (e.getValue() instanceof Object[]) {
                    iterable = Arrays.asList((Object[]) e.getValue());
                }

                boolean hasNull = true;

                for (Object value : (Iterable<Object>) iterable) {
                    hasNull = !ObjectUtil.notNull(value);
                }

                if (!hasNull) {
                    requiredParams.remove(e.getKey());
                }
            } else if (ObjectUtil.notNull(e.getValue())) {
                requiredParams.remove(e.getKey());
            }
        }

        if (requiredParams.size() > 0 && !userParams.getExpressions().isEmpty()
                && !userParams.getUserEnteredParams().isEmpty()) {
            for (Iterator<String> iterator = requiredParams.iterator(); iterator.hasNext();) {
                String parameterName = (String) iterator.next();
                if (StringUtils.isNotEmpty(userParams.getExpressions().get(parameterName))) {
                    String expression = userParams.getExpressions().get(parameterName);
                    if (!EvaluationUtil.isExpression(expression)) {
                        bindingResult.rejectValue("expressions[" + parameterName + "]",
                                "reporting.Report.run.error.invalidParamExpression");
                    }
                } else {
                    bindingResult.rejectValue("userEnteredParams[" + parameterName + "]", "error.required",
                            new Object[] { "This parameter" }, "{0} is required");
                }
            }
        }
    }

    // Try to parse the required parameters into appropriate objects if they are available
    if (!bindingResult.hasErrors()) {

        Map<String, Object> params = new LinkedHashMap<String, Object>();
        if (reportDefinition.getParameters() != null
                && (userParams.getUserEnteredParams() != null || userParams.getExpressions() != null)) {
            for (Parameter parameter : reportDefinition.getParameters()) {
                Object value = null;
                String expression = null;
                if (userParams.getExpressions() != null
                        && ObjectUtil.notNull(userParams.getExpressions().get(parameter.getName())))
                    expression = userParams.getExpressions().get(parameter.getName());
                else
                    value = userParams.getUserEnteredParams().get(parameter.getName());

                if (ObjectUtil.notNull(value) || ObjectUtil.notNull(expression)) {
                    try {
                        if (StringUtils.isNotEmpty(expression))
                            value = expression;
                        else
                            value = WidgetUtil.parseInput(value, parameter.getType(),
                                    parameter.getCollectionType());

                        params.put(parameter.getName(), value);
                    } catch (Exception ex) {
                        bindingResult.rejectValue("userEnteredParams[" + parameter.getName() + "]",
                                ex.getMessage());
                    }
                }
            }
        }

        // if no errors were found while parsing, retrieve a report design object and renderer the data
        if (!bindingResult.hasErrors()) {
            String previewResult = "";
            ReportDesign design = null;
            ReportDesignResource designResource = new ReportDesignResource();
            ReportData result = null;
            EvaluationContext ec = new EvaluationContext();
            ReportService rs = Context.getService(ReportService.class);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            if (StringUtils.isNotEmpty(uuid)) {
                design = rs.getReportDesignByUuid(uuid);
                design.setRendererType(rendererType);
                design.setReportDefinition(reportDefinition);
                design.getProperties().clear();
                design.getResources().clear();

                designResource.setReportDesign(design);
                designResource.setName("template");
                designResource.setContentType("text/html");
                designResource.setContents(script.getBytes("UTF-8"));

                design.addResource(designResource);
                design.addPropertyValue(TextTemplateRenderer.TEMPLATE_TYPE, scriptType);

                if (userParams.getBaseCohort() != null) {
                    try {
                        Cohort baseCohort = Context.getService(CohortDefinitionService.class)
                                .evaluate(userParams.getBaseCohort(), ec);
                        ec.setBaseCohort(baseCohort);

                    } catch (Exception ex) {
                        throw new EvaluationException("baseCohort", ex);
                    }
                }

                if (params != null) {
                    ec.setParameterValues(params);
                }

                Class<?> rt = Context.loadClass(design.getRendererType().getName());
                ReportTemplateRenderer reportRenderer = (ReportTemplateRenderer) rt.newInstance();
                Throwable errorDetails = null;
                result = rds.evaluate(reportDefinition, ec);
                try {
                    reportRenderer.render(result, design.getUuid(), out);
                } catch (Throwable e) {
                    errorDetails = e;
                }
                previewResult = (out.toByteArray() != null ? new String(out.toByteArray(), "UTF-8") : "");
                StringUtils.deleteWhitespace(previewResult);
                model.addAttribute("previewResult", previewResult);
                model.addAttribute("design", design);
                model.addAttribute("errorDetails", errorDetails);

            }

        }

    }

    model.addAttribute("iframe", iframe);
    model.addAttribute("script", script);
    model.addAttribute("scriptType", scriptType);
    model.addAttribute("reportDefinition", reportDefinition);
    model.addAttribute("rendererType", rendererType);
    model.addAttribute("errors", bindingResult);

}

From source file:org.openmrs.web.controller.user.UserFormController.java

/**
 * @should work for an example//from  w ww  .j a v a2  s . c  o m
 */
@RequestMapping(value = "/admin/users/user.form", method = RequestMethod.POST)
public String handleSubmission(WebRequest request, HttpSession httpSession, ModelMap model,
        @RequestParam(required = false, value = "action") String action,
        @RequestParam(required = false, value = "userFormOldPassword") String oldPassword,
        @RequestParam(required = false, value = "userFormPassword") String password,
        @RequestParam(required = false, value = "secretQuestion") String secretQuestion,
        @RequestParam(required = false, value = "secretAnswer") String secretAnswer,
        @RequestParam(required = false, value = "confirm") String confirm,
        @RequestParam(required = false, value = "forcePassword") Boolean forcePassword,
        @RequestParam(required = false, value = "roleStrings") String[] roles,
        @RequestParam(required = false, value = "createNewPerson") String createNewPerson,
        @ModelAttribute("user") User user, BindingResult errors) {

    UserService us = Context.getUserService();
    MessageSourceService mss = Context.getMessageSourceService();

    if (!Context.isAuthenticated()) {
        errors.reject("auth.invalid");
    } else if (mss.getMessage("User.assumeIdentity").equals(action)) {
        Context.becomeUser(user.getSystemId());
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success");
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName());
        return "redirect:/index.htm";

    } else if (mss.getMessage("User.delete").equals(action)) {
        try {
            Context.getUserService().purgeUser(user);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.success");
            return "redirect:users.list";
        } catch (Exception ex) {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "User.delete.failure");
            log.error("Failed to delete user", ex);
            return "redirect:/admin/users/user.form?userId=" + request.getParameter("userId");
        }

    } else if (mss.getMessage("User.retire").equals(action)) {
        String retireReason = request.getParameter("retireReason");
        if (!(StringUtils.hasText(retireReason))) {
            errors.rejectValue("retireReason", "User.disableReason.empty");
            return showForm(user.getUserId(), createNewPerson, user, model);
        } else {
            us.retireUser(user, retireReason);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.retiredMessage");
        }

    } else if (mss.getMessage("User.unRetire").equals(action)) {
        us.unretireUser(user);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.unRetiredMessage");
    } else {

        // check if username is already in the database
        if (us.hasDuplicateUsername(user)) {
            errors.rejectValue("username", "error.username.taken");
        }

        // check if password and password confirm are identical
        if (password == null || password.equals("XXXXXXXXXXXXXXX")) {
            password = "";
        }
        if (confirm == null || confirm.equals("XXXXXXXXXXXXXXX")) {
            confirm = "";
        }

        if (!password.equals(confirm)) {
            errors.reject("error.password.match");
        }

        if (password.length() == 0 && isNewUser(user)) {
            errors.reject("options.login.password.null");
        }

        //check password strength
        if (password.length() > 0) {
            try {
                OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
            } catch (PasswordException e) {
                errors.reject(e.getMessage());
            }
        }

        Set<Role> newRoles = new HashSet<Role>();
        if (roles != null) {
            for (String r : roles) {
                // Make sure that if we already have a detached instance of this role in the
                // user's roles, that we don't fetch a second copy of that same role from
                // the database, or else hibernate will throw a NonUniqueObjectException.
                Role role = null;
                if (user.getRoles() != null) {
                    for (Role test : user.getRoles()) {
                        if (test.getRole().equals(r)) {
                            role = test;
                        }
                    }
                }
                if (role == null) {
                    role = us.getRole(r);
                    user.addRole(role);
                }
                newRoles.add(role);
            }
        }

        if (user.getRoles() == null) {
            newRoles.clear();
        } else {
            user.getRoles().retainAll(newRoles);
        }

        String[] keys = request.getParameterValues("property");
        String[] values = request.getParameterValues("value");

        if (keys != null && values != null) {
            for (int x = 0; x < keys.length; x++) {
                String key = keys[x];
                String val = values[x];
                user.setUserProperty(key, val);
            }
        }

        if (StringUtils.hasLength(secretQuestion) && !StringUtils.hasLength(secretAnswer)) {
            errors.reject("error.User.secretAnswer.empty");
        } else if (!StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) {
            errors.reject("error.User.secretQuestion.empty");
        }

        new UserProperties(user.getUserProperties()).setSupposedToChangePassword(forcePassword);

        userValidator.validate(user, errors);

        if (errors.hasErrors()) {
            return showForm(user.getUserId(), createNewPerson, user, model);
        }

        if (isNewUser(user)) {
            us.createUser(user, password);
        } else {
            us.saveUser(user);

            if (!"".equals(password) && Context.hasPrivilege(PrivilegeConstants.EDIT_USER_PASSWORDS)) {
                if (log.isDebugEnabled()) {
                    log.debug("calling changePassword for user " + user + " by user "
                            + Context.getAuthenticatedUser());
                }
                us.changePassword(user, oldPassword, password);
            }
        }

        if (StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) {
            us.changeQuestionAnswer(user, secretQuestion, secretAnswer);
        }

        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
    }
    return "redirect:users.list";
}

From source file:org.orcid.frontend.web.controllers.ManageProfileController.java

@RequestMapping(value = "/save-bio-settings", method = RequestMethod.POST)
public ModelAndView saveEditedBio(HttpServletRequest request,
        @Valid @ModelAttribute("changePersonalInfoForm") ChangePersonalInfoForm changePersonalInfoForm,
        BindingResult bindingResult, RedirectAttributes redirectAttributes) {
    ModelAndView manageBioView = new ModelAndView("redirect:/account/manage-bio-settings");

    for (String keyword : changePersonalInfoForm.getKeywordsAsList()) {
        if (keyword.length() > ChangePersonalInfoForm.KEYWORD_MAX_LEN) {
            bindingResult.rejectValue("keywordsDelimited", "Length.changePersonalInfoForm.keywordsDelimited");
            break;
        }//from w  w  w .  ja  va2 s.  c  o  m
    }

    if (bindingResult.hasErrors()) {
        ModelAndView erroredView = new ModelAndView("manage_bio_settings");

        // If an error happens and the user doesnt have any website,
        // the privacy selector for websites dissapears.
        // In order to fix this, if the ChangePersonalInfoForm doesnt have
        // any researcher url, we add a new one with an empty list, which
        // is different than null ResearcherUrls
        Map<String, Object> model = bindingResult.getModel();

        if (changePersonalInfoForm.getSavedResearcherUrls() == null) {
            changePersonalInfoForm.setSavedResearcherUrls(new ResearcherUrls());
        }

        model.put("changePersonalInfoForm", changePersonalInfoForm);

        erroredView.addAllObjects(bindingResult.getModel());
        return erroredView;
    }

    OrcidProfile profile = getEffectiveProfile();
    // Update profile with values that comes from user request
    changePersonalInfoForm.mergeOrcidBioDetails(profile);

    // Update profile on database
    profileEntityManager.updateProfile(profile);

    String orcid = profile.getOrcidIdentifier().getPath();

    // Update other names on database
    OtherNames otherNames = profile.getOrcidBio().getPersonalDetails().getOtherNames();
    otherNameManager.updateOtherNames(orcid, otherNames);

    // Update keywords on database
    Keywords keywords = profile.getOrcidBio().getKeywords();
    profileKeywordManager.updateProfileKeyword(orcid, keywords);

    // Update researcher urls on database
    ResearcherUrls researcherUrls = profile.getOrcidBio().getResearcherUrls();
    boolean hasErrors = researcherUrlManager.updateResearcherUrls(orcid, researcherUrls);
    // TODO: The researcherUrlManager will not store any duplicated
    // researcher url on database,
    // however there is no way to tell the controller that some of the
    // researcher urls were not
    // saved, so, if an error occurs, we need to reload researcher ids from
    // database and update
    // cached profile. A more efficient way to fix this might be used.
    if (hasErrors) {
        ResearcherUrls upToDateResearcherUrls = getUpToDateResearcherUrls(orcid,
                researcherUrls.getVisibility());
        profile.getOrcidBio().setResearcherUrls(upToDateResearcherUrls);
    }

    redirectAttributes.addFlashAttribute("changesSaved", true);
    return manageBioView;
}

From source file:org.training.storefront.controllers.pages.AccountPageController.java

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

    String returnAction = REDIRECT_TO_UPDATE_PROFILE;
    final CustomerData currentCustomerData = customCustomerFacade.getCurrentCustomer();
    final CustomerData customerData = new CustomerData();
    customerData.setTitleCode(updateProfileForm.getTitleCode());
    customerData.setFirstName(updateProfileForm.getFirstName());
    customerData.setLastName(updateProfileForm.getLastName());
    customerData.setBirthdate(updateProfileForm.getBirthdate());
    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 {
            customCustomerFacade.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;
}

From source file:org.training.storefront.controllers.pages.LoginPageController.java

protected String processCustomRegisterUserRequest(final String referer, final CustomRegisterForm form,
        final BindingResult bindingResult, final Model model, final HttpServletRequest request,
        final HttpServletResponse response, final RedirectAttributes redirectModel)
        throws CMSItemNotFoundException {
    if (bindingResult.hasErrors()) {
        model.addAttribute(form);/*from   ww  w .  j a v a 2  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.setBirthdate(form.getBirthdate());
    try {
        getCustomCustomerFacade().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) {
        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 + getSuccessRedirect(request, response);
}

From source file:org.wise.portal.presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.java

/**
 * Maybe you want to be provided with the _page parameter (in order to map the same method for all), as you have in
 * AbstractWizardFormController./*from w  w  w.j a va  2  s .c  o m*/
 */
@RequestMapping(method = RequestMethod.POST)
public String processPage(@RequestParam("_page") final int currentPage,
        final @ModelAttribute("passwordReminderParameters") PasswordReminderParameters passwordReminderParameters,
        BindingResult result, SessionStatus status, ModelMap modelMap, final HttpServletResponse response) {

    switch (currentPage) {
    case 1:
        // handle the submit username

        try {
            String username = passwordReminderParameters.getUsername();

            if (username == null) {
                result.rejectValue("username",
                        "presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.errorNoUsername");
            } else {
                username = StringUtils.trimToNull(username);
                User user = userService.retrieveUserByUsername(username);

                /* check to see if user exists and ensure that user is a student */
                if (user == null || !(user.getUserDetails() instanceof StudentUserDetails)) {
                    result.rejectValue("username",
                            "presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.errorUsernameNotFound");
                }
            }
        } catch (EmptyResultDataAccessException e) {
            result.rejectValue("username",
                    "presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.errorUsernameNotFound");
        }
        if (result.hasErrors()) {
            return "forgotaccount/student/passwordreminder";
        }

        // passed validation, put username and account question into page
        String username = passwordReminderParameters.getUsername();

        username = StringUtils.trimToNull(username);
        User user = userService.retrieveUserByUsername(username);

        StudentUserDetails userDetails = (StudentUserDetails) user.getUserDetails();

        modelMap.put(USERNAME, userDetails.getUsername());
        modelMap.put(ACCOUNT_QUESTION, userDetails.getAccountQuestion());

        passwordReminderParameters.setAccountQuestion(userDetails.getAccountQuestion());
        passwordReminderParameters.setAccountAnswer(userDetails.getAccountAnswer());

        return "forgotaccount/student/passwordreminder2";
    case 2:
        // handle the submit with account answer

        ValidationUtils.rejectIfEmptyOrWhitespace(result, "submittedAccountAnswer",
                "presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.errorSubmittedAccountQuestion");

        String submittedAccountAnswer = passwordReminderParameters.getSubmittedAccountAnswer();

        String accountAnswer = passwordReminderParameters.getAccountAnswer();

        accountAnswer = StringUtils.lowerCase(accountAnswer);

        submittedAccountAnswer = StringUtils.lowerCase(submittedAccountAnswer);

        if (accountAnswer == null) {
            /*
             * the account answer is null perhaps because the session has
             * timed out so we will redirect them back to the first
             * password reminder page where they enter their user name
             */
            return "forgotaccount/student/passwordreminder";
        } else if (!accountAnswer.equals(submittedAccountAnswer)) {
            //they have provided an incorrect account answer
            result.reject(
                    "presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.errorSubmittedAccountQuestion");
        }

        if (result.hasErrors()) {
            modelMap.put(USERNAME, passwordReminderParameters.getUsername());
            modelMap.put(ACCOUNT_QUESTION, passwordReminderParameters.getAccountQuestion());

            return "forgotaccount/student/passwordreminder2";
        }

        // passed validation, go to next page
        return "forgotaccount/student/passwordreminder3";
    case 3:
        // handle the submit with new passwords

        ValidationUtils.rejectIfEmptyOrWhitespace(result, "verifyPassword",
                "presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.errorVerifyNewPassword");

        ValidationUtils.rejectIfEmptyOrWhitespace(result, "newPassword",
                "presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.errorVerifyNewPassword");

        if (result.hasErrors()) {
            return "forgotaccount/student/passwordreminder3";
        }

        String newPassword = passwordReminderParameters.getNewPassword();

        String verifyPassword = passwordReminderParameters.getVerifyPassword();

        if (!verifyPassword.equals(newPassword)) {
            result.reject(
                    "presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.errorVerifyNewPassword");
        }
        if (result.hasErrors()) {
            return "forgotaccount/student/passwordreminder3";
        }

        // passed validation, save new password
        String usernameSubmitted = passwordReminderParameters.getUsername();

        usernameSubmitted = StringUtils.trimToNull(usernameSubmitted);
        User userSubmitted = userService.retrieveUserByUsername(usernameSubmitted);

        if (newPassword != null) {
            userService.updateUserPassword(userSubmitted, newPassword);
        }

        //clear the command object from the session
        status.setComplete();

        modelMap.put("username", passwordReminderParameters.get(PasswordReminderParameters.USERNAME));
        return "forgotaccount/student/passwordreminder4";
    }

    return null;
}