List of usage examples for org.springframework.validation BindingResult rejectValue
void rejectValue(@Nullable String field, String errorCode, @Nullable Object[] errorArgs,
@Nullable String defaultMessage);
From source file:org.anyframe.iam.admin.securedresources.web.AnnotationResourcesController.java
/** * update Resources data/*from www . j av a 2s . com*/ * @param sr SecuredResources domain object * @param bindingResult an object to check input data with validation rules * @param status SessionStatus object to block double submit * @return move to "/resources/list.do" * @throws Exception fail to update data */ @RequestMapping("/resources/update.do") public String update(@RequestParam(value = "skipvalidation", required = false) String skipValidation, @ModelAttribute("resources") SecuredResources sr, BindingResult bindingResult, HttpSession session, SessionStatus status) throws Exception { if (!("Y").equals(skipValidation)) { beanValidator.validate(sr, bindingResult); boolean isMatched = candidateSecuredResourcesService.checkMatched(sr.getResourcePattern(), sr.getResourceType()); if (!isMatched) { bindingResult.rejectValue("resourcePattern", "errors.resourcepattern", new Object[] { sr.getResourcePattern() }, "check resource pattern."); } if (bindingResult.hasErrors()) { return "/resources/resourcedetail"; } } String[] systemName = new String[1]; systemName[0] = (String) session.getAttribute("systemName"); sr.setSystemName(systemName[0]); String currentTime = DateUtil.getCurrentTime("yyyyMMdd"); sr.setModifyDate(currentTime); SecuredResources gettedsr = securedResourcesService.get(sr.getResourceId()); sr.setCreateDate(gettedsr.getCreateDate()); securedResourcesService.update(sr); status.setComplete(); return "forward:/resources/list.do"; }
From source file:org.encuestame.mvc.page.ForgetPasswordController.java
/** * Process Submit.//from w w w . j a va 2 s . c o m * * @param req * @param challenge * @param response * @param user * @param result * @param status * @return * @throws EnMeNoResultsFoundException */ @RequestMapping(value = "/user/forgot", method = RequestMethod.POST) public String forgotSubmitForm(HttpServletRequest req, ModelMap model, @RequestParam(value = "recaptcha_challenge_field", required = false) String challenge, @RequestParam(value = "recaptcha_response_field", required = false) String response, @ModelAttribute ForgotPasswordBean user, BindingResult result, SessionStatus status) throws EnMeNoResultsFoundException { log.info("recaptcha_challenge_field " + challenge); log.info("recaptcha_response_field " + response); log.info("result erros " + result.getAllErrors().size()); log.info("result erros " + result.getErrorCount()); final String email = user.getEmail() == null ? "" : user.getEmail(); setCss(model, "user"); if (!email.isEmpty()) { log.debug("email " + email); final ReCaptchaResponse reCaptchaResponse = getReCaptcha().checkAnswer(req.getRemoteAddr(), challenge, response); final ValidateOperations validation = new ValidateOperations(getSecurityService()); boolean _isValidEmailFormat = validation.validateEmail(email); log.info("EMAIL FORMAT NOT VALID --> " + _isValidEmailFormat); if (_isValidEmailFormat) { final UserAccount userValidate = validation.checkifEmailExist(email); if (userValidate == null) { result.rejectValue("email", "secure.email.notvalid", new Object[] { user.getEmail() }, ""); } log.info("reCaptchaResponse " + reCaptchaResponse.isValid()); //validate reCaptcha validation.validateCaptcha(reCaptchaResponse, result); if (reCaptchaResponse.getErrorMessage() != null) { RequestSessionMap.getCurrent(req).put("resetError", Boolean.TRUE); RequestSessionMap.getCurrent(req).put("resetErrorMessage", reCaptchaResponse.getErrorMessage()); log.fatal("reCaptcha Fatal Error: " + reCaptchaResponse.getErrorMessage()); } log.info("result.hasErrors() " + result.hasErrors()); if (result.hasErrors()) { return "forgot"; } else { final String password = PasswordGenerator.getPassword(6); try { /* * Stuffs to change; * 1. user should be to change own password, not auto generate * 2. instead redirect to sign in page, should be to success page. */ getSecurityService().renewPassword( ConvertDomainBean.convertBasicSecondaryUserToUserBean(userValidate), password); } catch (EnMeException e) { log.error("Error Renewd password " + e.getMessage()); return "forgot"; } status.setComplete(); log.info("password generated: " + password); final ForgotPasswordBean forgot = new ForgotPasswordBean(); model.addAttribute("forgotPasswordBean", forgot); return "/user/checkyouremail"; } } else { log.info("EMAIL FORMAT NOT VALID"); result.rejectValue("email", "secure.email.notvalid", new Object[] { user.getEmail() }, ""); return "forgot"; } } else { result.rejectValue("email", "secure.email.emtpy", null, ""); return "forgot"; } }
From source file:org.hoteia.qalingo.core.web.mvc.controller.user.UserPersonalController.java
@RequestMapping(value = BoUrls.PERSONAL_EDIT_URL, method = RequestMethod.POST) public ModelAndView submitPersonalEdit(final HttpServletRequest request, @Valid @ModelAttribute(ModelConstants.USER_FORM) UserForm userForm, BindingResult result, final Model model) throws Exception { if (result.hasErrors()) { return displayPersonalEdit(request, model, userForm); }/*from www . j a v a 2s. c om*/ final String newEmail = userForm.getEmail(); final User currentUser = requestUtil.getCurrentUser(request); final User checkUser = userService.getUserActivedByLoginOrEmail(newEmail); if (checkUser != null && !currentUser.getEmail().equalsIgnoreCase(newEmail)) { final String forgottenPasswordUrl = backofficeUrlService.generateUrl(BoUrls.FORGOTTEN_PASSWORD, requestUtil.getRequestData(request)); final Object[] objects = { forgottenPasswordUrl }; result.rejectValue("email", "fo.user.error_form_create_account_account_already_exist", objects, "This email user account already exist! Go on this <a href=\"${0}\" alt=\"\">page</a> to get a new password."); } // Update the user webBackofficeService.createOrUpdatePersonalUser(checkUser, userForm); requestUtil.updateCurrentUser(request, userService.getUserActivedByLoginOrEmail(newEmail)); final String urlRedirect = backofficeUrlService.generateRedirectUrl(BoUrls.PERSONAL_DETAILS, requestUtil.getRequestData(request)); return new ModelAndView(new RedirectView(urlRedirect)); }
From source file:org.training.storefront.controllers.pages.AccountPageController.java
@RequestMapping(value = "/update-email", method = RequestMethod.POST) @RequireHardLogIn/* w w w . ja v a2 s . co m*/ public String updateEmail(final UpdateEmailForm updateEmailForm, final BindingResult bindingResult, final Model model, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException { getEmailValidator().validate(updateEmailForm, bindingResult); String returnAction = REDIRECT_TO_UPDATE_EMAIL_PAGE; if (!bindingResult.hasErrors() && !updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) { bindingResult.rejectValue("chkEmail", "validation.checkEmail.equals", new Object[] {}, "validation.checkEmail.equals"); } if (bindingResult.hasErrors()) { returnAction = setErrorMessagesAndCMSPage(model, UPDATE_EMAIL_CMS_PAGE); } else { try { customCustomerFacade.changeUid(updateEmailForm.getEmail(), updateEmailForm.getPassword()); GlobalMessages.addFlashMessage(redirectAttributes, GlobalMessages.CONF_MESSAGES_HOLDER, "text.account.profile.confirmationUpdated", null); // Replace the spring security authentication with the new UID final String newUid = customCustomerFacade.getCurrentCustomer().getUid().toLowerCase(); final Authentication oldAuthentication = SecurityContextHolder.getContext().getAuthentication(); final UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken( newUid, null, oldAuthentication.getAuthorities()); newAuthentication.setDetails(oldAuthentication.getDetails()); SecurityContextHolder.getContext().setAuthentication(newAuthentication); } catch (final DuplicateUidException e) { bindingResult.rejectValue("email", "profile.email.unique"); returnAction = setErrorMessagesAndCMSPage(model, UPDATE_EMAIL_CMS_PAGE); } catch (final PasswordMismatchException passwordMismatchException) { bindingResult.rejectValue("password", PROFILE_CURRENT_PASSWORD_INVALID); returnAction = setErrorMessagesAndCMSPage(model, UPDATE_EMAIL_CMS_PAGE); } } return returnAction; }
From source file:org.training.storefront.controllers.pages.AccountPageController.java
@RequestMapping(value = "/update-password", method = RequestMethod.POST) @RequireHardLogIn//from ww w. j a v a 2 s .c o m public String updatePassword(final UpdatePasswordForm updatePasswordForm, final BindingResult bindingResult, final Model model, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException { getPasswordValidator().validate(updatePasswordForm, bindingResult); if (!bindingResult.hasErrors()) { if (updatePasswordForm.getNewPassword().equals(updatePasswordForm.getCheckNewPassword())) { try { customCustomerFacade.changePassword(updatePasswordForm.getCurrentPassword(), updatePasswordForm.getNewPassword()); } catch (final PasswordMismatchException localException) { bindingResult.rejectValue("currentPassword", PROFILE_CURRENT_PASSWORD_INVALID, new Object[] {}, PROFILE_CURRENT_PASSWORD_INVALID); } } else { bindingResult.rejectValue("checkNewPassword", "validation.checkPwd.equals", new Object[] {}, "validation.checkPwd.equals"); } } if (bindingResult.hasErrors()) { GlobalMessages.addErrorMessage(model, FORM_GLOBAL_ERROR); storeCmsPageInModel(model, getContentPageForLabelOrId(UPDATE_PASSWORD_CMS_PAGE)); setUpMetaDataForContentPage(model, getContentPageForLabelOrId(UPDATE_PASSWORD_CMS_PAGE)); model.addAttribute(BREADCRUMBS_ATTR, accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile.updatePasswordForm")); return getViewForPage(model); } else { GlobalMessages.addFlashMessage(redirectAttributes, GlobalMessages.CONF_MESSAGES_HOLDER, "text.account.confirmation.password.updated", null); return REDIRECT_TO_PASSWORD_UPDATE_PAGE; } }
From source file:org.wise.portal.presentation.web.controllers.teacher.RegisterTeacherController.java
/** * On submission of the signup form, a user is created and saved to the data * store.//from ww w . j a va 2s . c o m * @param accountForm the model object that contains values for the page to use when rendering the view * @param bindingResult the object used for validation in which errors will be stored * @param request the http request object * @param model the object that contains values to be displayed on the page * @return the path of the view to display */ @RequestMapping(method = RequestMethod.POST) protected String onSubmit(@ModelAttribute("teacherAccountForm") TeacherAccountForm accountForm, BindingResult bindingResult, HttpServletRequest request, Model model) { String view = formView; String domain = ControllerUtil.getBaseUrlString(request); String domainWithPort = domain + ":" + request.getLocalPort(); String referrer = request.getHeader("referer"); //get the context path e.g. /wise String contextPath = request.getContextPath(); String registerUrl = contextPath + "/teacher/registerteacher.html"; String updateAccountInfoUrl = contextPath + "/teacher/management/updatemyaccountinfo.html"; if (referrer.contains(domain + registerUrl) || referrer.contains(domainWithPort + registerUrl) || referrer.contains(domain + updateAccountInfoUrl) || referrer.contains(domainWithPort + updateAccountInfoUrl)) { TeacherUserDetails userDetails = (TeacherUserDetails) accountForm.getUserDetails(); //set the sign up date userDetails.setSignupdate(Calendar.getInstance().getTime()); //validate the form teacherAccountFormValidator.validate(accountForm, bindingResult); if (bindingResult.hasErrors()) { //there were errors populateModel(model); view = formView; } else { //there were no errors if (accountForm.isNewAccount()) { try { userDetails.setDisplayname(userDetails.getFirstname() + " " + userDetails.getLastname()); userDetails.setEmailValid(true); User createdUser = this.userService.createUser(userDetails); // send email to new teacher if email server is configured properly NewAccountEmailService newAccountEmailService = new NewAccountEmailService(createdUser, request.getLocale()); Thread thread = new Thread(newAccountEmailService); thread.start(); } catch (DuplicateUsernameException e) { bindingResult.rejectValue("username", "error.duplicate-username", new Object[] { userDetails.getUsername() }, "Duplicate Username."); populateModel(model); view = formView; } } else { // we're updating an existing teacher's account User user = userService.retrieveUserByUsername(userDetails.getUsername()); TeacherUserDetails teacherUserDetails = (TeacherUserDetails) user.getUserDetails(); teacherUserDetails.setCity(userDetails.getCity()); teacherUserDetails.setCountry(userDetails.getCountry()); teacherUserDetails.setCurriculumsubjects(userDetails.getCurriculumsubjects()); teacherUserDetails.setEmailAddress(userDetails.getEmailAddress()); teacherUserDetails.setSchoollevel(userDetails.getSchoollevel()); teacherUserDetails.setSchoolname(userDetails.getSchoolname()); teacherUserDetails.setState(userDetails.getState()); teacherUserDetails.setDisplayname(userDetails.getDisplayname()); teacherUserDetails.setEmailValid(true); teacherUserDetails.setLanguage(userDetails.getLanguage()); String userLanguage = userDetails.getLanguage(); Locale locale = null; if (userLanguage.contains("_")) { String language = userLanguage.substring(0, userLanguage.indexOf("_")); String country = userLanguage.substring(userLanguage.indexOf("_") + 1); locale = new Locale(language, country); } else { locale = new Locale(userLanguage); } request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale); userService.updateUser(user); // update user in session request.getSession().setAttribute(User.CURRENT_USER_SESSION_KEY, user); } model.addAttribute(USERNAME_KEY, userDetails.getUsername()); model.addAttribute(DISPLAYNAME_KEY, userDetails.getDisplayname()); view = successView; } } else { //the request is not coming from a valid domain address so we will not allow it bindingResult.reject("Forbidden"); populateModel(model); view = formView; } return view; }
From source file:org.wise.portal.presentation.web.controllers.teacher.run.CreateRunController.java
/** * Creates a run.// www . j a va2s .c om * * This method is called if there is a submit that validates and contains the "_finish" * request parameter. */ @RequestMapping(params = "_finish") protected ModelAndView processFinish(final @ModelAttribute("runParameters") RunParameters runParameters, final BindingResult result, final HttpServletRequest request, final HttpServletResponse response, final SessionStatus status) throws Exception { Project project = runParameters.getProject(); Project newProject; // copied project that will be used for new run. Integer projectWiseVersion = project.getWiseVersion(); if (projectWiseVersion != null && projectWiseVersion == 5) { User user = ControllerUtil.getSignedInUser(); CredentialManager.setRequestCredentials(request, user); String pathAllowedToAccess = CredentialManager.getAllowedPathAccess(request); /* * get the project folder path * e.g. * /Users/geoffreykwan/dev/apache-tomcat-5.5.27/webapps/curriculum/667 */ String projectFolderPath = FileManager.getProjectFolderPath(project); /* * get the curriculum base * e.g. * /Users/geoffreykwan/dev/apache-tomcat-5.5.27/webapps/curriculum */ String curriculumBaseDir = wiseProperties.getProperty("curriculum_base_dir"); if (SecurityUtils.isAllowedAccess(pathAllowedToAccess, projectFolderPath)) { String newProjectDirname = FileManager.copyProject(curriculumBaseDir, projectFolderPath); String newProjectPath = "/" + newProjectDirname + "/project.json"; String newProjectName = project.getName(); Long parentProjectId = (Long) project.getId(); ModuleParameters mParams = new ModuleParameters(); mParams.setUrl(newProjectPath); Curnit curnit = curnitService.createCurnit(mParams); ProjectParameters pParams = new ProjectParameters(); pParams.setCurnitId(curnit.getId()); pParams.setOwner(user); pParams.setProjectname(newProjectName); pParams.setProjectType(ProjectType.LD); pParams.setWiseVersion(5); pParams.setParentProjectId(parentProjectId); // get the project's metadata from the parent ProjectMetadata parentProjectMetadata = project.getMetadata(); if (parentProjectMetadata != null) { // copy into new metadata object ProjectMetadata newProjectMetadata = new ProjectMetadataImpl( parentProjectMetadata.toJSONString()); pParams.setMetadata(newProjectMetadata); } newProject = projectService.createProject(pParams); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return new ModelAndView("errors/accessdenied"); } } else { // this will be a new run using a WISE4 project. The new project has already been created. // get newProjectId from request and use that to set up the run String newProjectId = request.getParameter("newProjectId"); newProject = projectService.getById(new Long(newProjectId)); } Run run; try { runParameters.setProject(newProject); Locale userLocale = request.getLocale(); runParameters.setLocale(userLocale); runParameters.setPostLevel(5); // always use the highest post-level (starting WISE5) run = this.runService.createRun(runParameters); User owner = runParameters.getOwner(); HashSet<User> members = new HashSet<>(); members.add(owner); // create a workgroup for the owners of the run (teacher) workgroupService.createWISEWorkgroup("teacher", members, run, null); } catch (ObjectNotFoundException e) { result.rejectValue("curnitId", "error.curnit-not_found", new Object[] { runParameters.getCurnitId() }, "Project Not Found."); return null; } ModelAndView modelAndView = new ModelAndView(COMPLETE_VIEW_NAME); modelAndView.addObject(RUN_KEY, run); Set<String> runIdsToArchive = runParameters.getRunIdsToArchive(); if (runIdsToArchive != null) { for (String runIdStr : runIdsToArchive) { Long runId = Long.valueOf(runIdStr); Run runToArchive = runService.retrieveById(runId); runService.endRun(runToArchive); } } // send email to the recipients in new thread //tries to retrieve the user from the session User user = ControllerUtil.getSignedInUser(); Locale locale = request.getLocale(); String fullWiseContextPath = ControllerUtil.getPortalUrlString(request); // e.g. http://localhost:8080/wise CreateRunEmailService emailService = new CreateRunEmailService(runParameters, run, user, locale, fullWiseContextPath); Thread thread = new Thread(emailService); thread.start(); status.setComplete(); return modelAndView; }
From source file:org.wise.portal.presentation.web.controllers.teacher.TeacherAccountController.java
/** * On submission of the signup form, a user is created and saved to the data * store./* ww w. j a v a 2 s . c o m*/ * @param accountForm the model object that contains values for the page to use when rendering the view * @param bindingResult the object used for validation in which errors will be stored * @param request the http request object * @param modelMap the object that contains values to be displayed on the page * @return the path of the view to display */ @RequestMapping(value = { "/teacher/join", "/teacher/management/updatemyaccountinfo.html" }, method = RequestMethod.POST) protected String onSubmit(@ModelAttribute("teacherAccountForm") TeacherAccountForm accountForm, BindingResult bindingResult, HttpServletRequest request, ModelMap modelMap) { String referrer = request.getHeader("referer"); //get the context path e.g. /wise String contextPath = request.getContextPath(); String registerUrl = contextPath + "/teacher/join"; String updateAccountInfoUrl = contextPath + "/teacher/management/updatemyaccountinfo.html"; if (referrer != null && (referrer.contains(registerUrl) || referrer.contains(updateAccountInfoUrl))) { TeacherUserDetails userDetails = (TeacherUserDetails) accountForm.getUserDetails(); //there were no errors if (accountForm.isNewAccount()) { //set the sign up date userDetails.setSignupdate(Calendar.getInstance().getTime()); //validate the form teacherAccountFormValidator.validate(accountForm, bindingResult); if (bindingResult.hasErrors()) { //there were errors populateModelMap(modelMap); return "teacher/join"; } try { userDetails.setDisplayname(userDetails.getFirstname() + " " + userDetails.getLastname()); userDetails.setEmailValid(true); User createdUser = this.userService.createUser(userDetails); // send email to new teacher if email server is configured properly NewAccountEmailService newAccountEmailService = new NewAccountEmailService(createdUser, request.getLocale()); Thread thread = new Thread(newAccountEmailService); thread.start(); modelMap.addAttribute(USERNAME_KEY, userDetails.getUsername()); modelMap.addAttribute(DISPLAYNAME_KEY, userDetails.getDisplayname()); return "teacher/joinsuccess"; } catch (DuplicateUsernameException e) { bindingResult.rejectValue("username", "error.duplicate-username", new Object[] { userDetails.getUsername() }, "Duplicate Username."); populateModelMap(modelMap); return "teacher/join"; } } else { // we're updating an existing teacher's account //validate the form teacherAccountFormValidator.validate(accountForm, bindingResult); if (bindingResult.hasErrors()) { //there were errors populateModelMap(modelMap); return "teacher/management/updatemyaccountinfo"; } User user = userService.retrieveUserByUsername(userDetails.getUsername()); TeacherUserDetails teacherUserDetails = (TeacherUserDetails) user.getUserDetails(); teacherUserDetails.setCity(userDetails.getCity()); teacherUserDetails.setCountry(userDetails.getCountry()); teacherUserDetails.setCurriculumsubjects(userDetails.getCurriculumsubjects()); teacherUserDetails.setEmailAddress(userDetails.getEmailAddress()); teacherUserDetails.setSchoollevel(userDetails.getSchoollevel()); teacherUserDetails.setSchoolname(userDetails.getSchoolname()); teacherUserDetails.setState(userDetails.getState()); teacherUserDetails.setDisplayname(userDetails.getDisplayname()); teacherUserDetails.setEmailValid(true); if ("default".equals(userDetails.getLanguage())) { teacherUserDetails.setLanguage(null); } else { teacherUserDetails.setLanguage(userDetails.getLanguage()); } // set user's language (if specified) Locale locale = null; String userLanguage = teacherUserDetails.getLanguage(); if (userLanguage != null) { if (userLanguage.contains("_")) { String language = userLanguage.substring(0, userLanguage.indexOf("_")); String country = userLanguage.substring(userLanguage.indexOf("_") + 1); locale = new Locale(language, country); } else { locale = new Locale(userLanguage); } } else { // user default browser locale setting if user hasn't specified locale locale = request.getLocale(); } request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale); userService.updateUser(user); // update user in session request.getSession().setAttribute(User.CURRENT_USER_SESSION_KEY, user); return "teacher/management/updatemyaccount"; } } else { //the request is not coming from a valid domain address so we will not allow it bindingResult.reject("Forbidden"); populateModelMap(modelMap); return "teacher/join"; } }