List of usage examples for org.springframework.web.bind.support SessionStatus setComplete
void setComplete();
From source file:org.anyframe.iam.admin.viewresources.web.AnnotationViewResourcesController.java
/** * delete view resources data/*from w w w.j av a 2 s . c o m*/ * * @param viewResourceIds * array of view resource IDs * @param status * SessionStatus object to prevent double submit * @return move to "/viewresources/listData.do" * @throws Exception * fail to delete data */ @JsonError @RequestMapping("/viewresources/delete.do") public String delete(@RequestParam("viewResourceIds") String[] viewResourceIds, @RequestParam(value = "parentViewResourceId", required = false) String parentViewResourceId, SessionStatus status) throws Exception { parentViewResourceId = StringUtil.null2str(parentViewResourceId); viewResourcesService.delete(viewResourceIds); status.setComplete(); return "forward:/viewresources/listData.do?"; }
From source file:org.cloudfoundry.identity.uaa.oauth.AccessController.java
@RequestMapping("/oauth/confirm_access") public String confirm(Map<String, Object> model, final HttpServletRequest request, Principal principal, SessionStatus sessionStatus) throws Exception { if (!(principal instanceof Authentication)) { sessionStatus.setComplete(); throw new InsufficientAuthenticationException( "User must be authenticated with before authorizing access."); }//from w ww . ja v a 2 s. co m AuthorizationRequest clientAuthRequest = (AuthorizationRequest) model.remove("authorizationRequest"); if (clientAuthRequest == null) { model.put("error", "No authorization request is present, so we cannot confirm access (we don't know what you are asking for)."); // response.sendError(HttpServletResponse.SC_BAD_REQUEST); } else { String clientId = clientAuthRequest.getClientId(); BaseClientDetails client = (BaseClientDetails) clientDetailsService.loadClientByClientId(clientId); // TODO: Need to fix the copy constructor to copy additionalInfo BaseClientDetails modifiableClient = new BaseClientDetails(client); modifiableClient.setClientSecret(null); model.put("auth_request", clientAuthRequest); model.put("redirect_uri", getRedirectUri(modifiableClient, clientAuthRequest)); Map<String, Object> additionalInfo = client.getAdditionalInformation(); String clientDisplayName = (String) additionalInfo.get(ClientConstants.CLIENT_NAME); model.put("client_display_name", (clientDisplayName != null) ? clientDisplayName : clientId); // Find the auto approved scopes for this clients Set<String> autoApproved = client.getAutoApproveScopes(); Set<String> autoApprovedScopes = new HashSet<>(); if (autoApproved != null) { if (autoApproved.contains("true")) { autoApprovedScopes.addAll(client.getScope()); } else { autoApprovedScopes.addAll(autoApproved); } } List<Approval> filteredApprovals = new ArrayList<Approval>(); // Remove auto approved scopes List<Approval> approvals = approvalStore.getApprovals(Origin.getUserId((Authentication) principal), clientId); for (Approval approval : approvals) { if (!(autoApprovedScopes.contains(approval.getScope()))) { filteredApprovals.add(approval); } } ArrayList<String> approvedScopes = new ArrayList<String>(); ArrayList<String> deniedScopes = new ArrayList<String>(); for (Approval approval : filteredApprovals) { switch (approval.getStatus()) { case APPROVED: approvedScopes.add(approval.getScope()); break; case DENIED: deniedScopes.add(approval.getScope()); break; default: logger.error("Encountered an unknown scope. This is not supposed to happen"); break; } } ArrayList<String> undecidedScopes = new ArrayList<String>(); // Filter the scopes approved/denied from the ones requested for (String scope : clientAuthRequest.getScope()) { if (!approvedScopes.contains(scope) && !deniedScopes.contains(scope) && !autoApprovedScopes.contains(scope)) { undecidedScopes.add(scope); } } List<Map<String, String>> approvedScopeDetails = getScopes(approvedScopes); model.put("approved_scopes", approvedScopeDetails); List<Map<String, String>> undecidedScopeDetails = getScopes(undecidedScopes); model.put("undecided_scopes", undecidedScopeDetails); List<Map<String, String>> deniedScopeDetails = getScopes(deniedScopes); model.put("denied_scopes", deniedScopeDetails); List<Map<String, String>> allScopes = new ArrayList<>(); allScopes.addAll(approvedScopeDetails); allScopes.addAll(undecidedScopeDetails); allScopes.addAll(deniedScopeDetails); model.put("scopes", allScopes); model.put("message", "To confirm or deny access POST to the following locations with the parameters requested."); Map<String, Object> options = new HashMap<String, Object>() { { put("confirm", new HashMap<String, String>() { { put("location", getLocation(request, "oauth/authorize")); put("path", getPath(request, "oauth/authorize")); put("key", OAuth2Utils.USER_OAUTH_APPROVAL); put("value", "true"); } }); put("deny", new HashMap<String, String>() { { put("location", getLocation(request, "oauth/authorize")); put("path", getPath(request, "oauth/authorize")); put("key", OAuth2Utils.USER_OAUTH_APPROVAL); put("value", "false"); } }); } }; model.put("options", options); } return "access_confirmation"; }
From source file:org.encuestame.mvc.page.ForgetPasswordController.java
/** * Process Submit./* w ww . j ava 2 s.co 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.georchestra.console.ws.newaccount.NewAccountFormController.java
/** * Creates a new account in ldap. If the application was configured with "moderated signup" the new account is added with the PENDING role, * in other case, it will be inserted with the USER role * * * @param formBean/*w w w. j av a 2s .c o m*/ * @param result * @param sessionStatus * * @return the next view * * @throws IOException */ @RequestMapping(value = "/account/new", method = RequestMethod.POST) public String create(HttpServletRequest request, @ModelAttribute AccountFormBean formBean, @RequestParam("orgCities") String orgCities, BindingResult result, SessionStatus sessionStatus, Model model) throws IOException, SQLException { // Populate orgs droplist model.addAttribute("orgs", this.getOrgs()); // Populate org type droplist model.addAttribute("orgTypes", this.getOrgTypes()); // uid validation if (!this.validation.validateUserField("uid", formBean.getUid())) { result.rejectValue("uid", "uid.error.required", "required"); } else { // A valid user identifier (uid) can only contain characters, numbers, hyphens or dot. // It must begin with a character. Pattern regexp = Pattern.compile("[a-zA-Z][a-zA-Z0-9.-]*"); Matcher m = regexp.matcher(formBean.getUid()); if (!m.matches()) result.rejectValue("uid", "uid.error.invalid", "required"); } // first name and surname validation if (!this.validation.validateUserField("firstName", formBean.getFirstName())) result.rejectValue("firstName", "firstName.error.required", "required"); if (!this.validation.validateUserField("surname", formBean.getSurname())) result.rejectValue("surname", "surname.error.required", "required"); // email validation if (!this.validation.validateUserField("email", formBean.getEmail())) result.rejectValue("email", "email.error.required", "required"); else if (!EmailValidator.getInstance().isValid(formBean.getEmail())) result.rejectValue("email", "email.error.invalidFormat", "Invalid Format"); // password validation PasswordUtils.validate(formBean.getPassword(), formBean.getConfirmPassword(), result); // Check captcha RecaptchaUtils.validate(reCaptchaParameters, formBean.getRecaptcha_response_field(), result); // Validate remaining fields this.validation.validateUserField("phone", formBean.getPhone(), result); this.validation.validateUserField("title", formBean.getTitle(), result); this.validation.validateUserField("description", formBean.getDescription(), result); // Create org if needed if (formBean.getCreateOrg() && !result.hasErrors()) { try { // Check required fields this.validation.validateOrgField("name", formBean.getOrgName(), result); this.validation.validateOrgField("shortName", formBean.getOrgShortName(), result); this.validation.validateOrgField("address", formBean.getOrgAddress(), result); this.validation.validateOrgField("type", formBean.getOrgType(), result); Org org = new Org(); OrgExt orgExt = new OrgExt(); // Generate textual identifier based on name String orgId = this.orgDao.generateId(formBean.getOrgName()); org.setId(orgId); orgExt.setId(orgId); // Generate numeric identifier orgExt.setNumericId(this.orgDao.generateNumericId()); // Store name, short name, orgType and address org.setName(formBean.getOrgName()); org.setShortName(formBean.getOrgShortName()); orgExt.setAddress(formBean.getOrgAddress()); orgExt.setOrgType(formBean.getOrgType()); // Parse and store cities orgCities = orgCities.trim(); if (orgCities.length() > 0) org.setCities(Arrays.asList(orgCities.split("\\s*,\\s*"))); // Set default value org.setStatus(Org.STATUS_PENDING); // Persist changes to LDAP server if (!result.hasErrors()) { this.orgDao.insert(org); this.orgDao.insert(orgExt); // Set real org identifier in form formBean.setOrg(orgId); } } catch (Exception e) { LOG.error(e.getMessage()); throw new IOException(e); } } else { this.validation.validateUserField("org", formBean.getOrg(), result); } if (result.hasErrors()) return "createAccountForm"; // inserts the new account try { Account account = AccountFactory.createBrief(formBean.getUid().toLowerCase(), formBean.getPassword(), formBean.getFirstName(), formBean.getSurname(), formBean.getEmail(), formBean.getPhone(), formBean.getTitle(), formBean.getDescription()); if (!formBean.getOrg().equals("-")) account.setOrg(formBean.getOrg()); String roleID = this.moderator.moderatedSignup() ? Role.PENDING : Role.USER; this.accountDao.insert(account, roleID, request.getHeader("sec-username")); final ServletContext servletContext = request.getSession().getServletContext(); // email to the moderator this.mailService.sendNewAccountRequiresModeration(servletContext, account.getUid(), account.getCommonName(), account.getEmail(), this.moderator.getModeratorEmail()); // email to delegated admin if org is specified if (!formBean.getOrg().equals("-")) { // and a delegation is defined List<DelegationEntry> delegations = this.advancedDelegationDao.findByOrg(formBean.getOrg()); for (DelegationEntry delegation : delegations) { Account delegatedAdmin = this.accountDao.findByUID(delegation.getUid()); this.mailService.sendNewAccountRequiresModeration(servletContext, account.getUid(), account.getCommonName(), account.getEmail(), delegatedAdmin.getEmail()); } } // email to the user if (this.moderator.moderatedSignup()) { this.mailService.sendAccountCreationInProcess(servletContext, account.getUid(), account.getCommonName(), account.getEmail()); } else { this.mailService.sendAccountWasCreated(servletContext, account.getUid(), account.getCommonName(), account.getEmail()); } sessionStatus.setComplete(); return "welcomeNewUser"; } catch (DuplicatedEmailException e) { result.rejectValue("email", "email.error.exist", "there is a user with this e-mail"); return "createAccountForm"; } catch (DuplicatedUidException e) { try { String proposedUid = this.accountDao.generateUid(formBean.getUid()); formBean.setUid(proposedUid); result.rejectValue("uid", "uid.error.exist", "the uid exist"); return "createAccountForm"; } catch (DataServiceException e1) { throw new IOException(e); } } catch (DataServiceException e) { throw new IOException(e); } }
From source file:org.georchestra.console.ws.passwordrecovery.NewPasswordFormController.java
/** * Registers the new password, if it is valid. * /*from w w w . j a va2 s. c o m*/ * @param formBean * @param result * @param sessionStatus * * @return the next view * * @throws IOException */ @RequestMapping(value = "/account/newPassword", method = RequestMethod.POST) public String newPassword(@ModelAttribute NewPasswordFormBean formBean, BindingResult result, SessionStatus sessionStatus) throws IOException { PasswordUtils.validate(formBean.getPassword(), formBean.getConfirmPassword(), result); if (result.hasErrors()) { return "newPasswordForm"; } // changes the user's password and removes the token try { String uid = formBean.getUid(); String password = formBean.getPassword(); this.accountDao.changePassword(uid, password); this.userTokenDao.delete(uid); sessionStatus.setComplete(); return "passwordUpdated"; } catch (DataServiceException e) { LOG.error("cannot set the the new password. " + e.getMessage()); throw new IOException(e); } }
From source file:org.georchestra.console.ws.passwordrecovery.PasswordRecoveryFormController.java
/** * Generates a new unique http URL based on a token, then an e-mail is sent to the user with instruction to change his password. * * * @param formBean Contains the user's email * @param resultErrors will be updated with the list of found errors. * @param sessionStatus/*from w ww .j a v a2s .c om*/ * * @return the next view * * @throws IOException */ @RequestMapping(value = "/account/passwordRecovery", method = RequestMethod.POST) public String generateToken(HttpServletRequest request, @ModelAttribute PasswordRecoveryFormBean formBean, BindingResult resultErrors, SessionStatus sessionStatus) throws IOException { RecaptchaUtils.validate(reCaptchaParameters, formBean.getRecaptcha_response_field(), resultErrors); if (resultErrors.hasErrors()) { return "passwordRecoveryForm"; } try { Account account = this.accountDao.findByEmail(formBean.getEmail()); List<Role> role = this.roleDao.findAllForUser(account.getUid()); // Finds the user using the email as key, if it exists a new token is generated to include in the unique http URL. for (Role g : role) { if (g.getName().equals(Role.PENDING)) { throw new NameNotFoundException("User in PENDING role"); } } String token = UUID.randomUUID().toString(); // if there is a previous token it is removed if (this.userTokenDao.exist(account.getUid())) { this.userTokenDao.delete(account.getUid()); } this.userTokenDao.insertToken(account.getUid(), token); String contextPath = this.config.getPublicContextPath(); String url = makeChangePasswordURL(this.georConfig.getProperty("publicUrl"), contextPath, token); ServletContext servletContext = request.getSession().getServletContext(); this.mailService.sendChangePasswordURL(servletContext, account.getUid(), account.getCommonName(), url, account.getEmail()); sessionStatus.setComplete(); return "emailWasSent"; } catch (DataServiceException e) { throw new IOException(e); } catch (NameNotFoundException e) { resultErrors.rejectValue("email", "email.error.notFound", "No user found for this email."); return "passwordRecoveryForm"; } }
From source file:org.jasig.portlet.announcements.mvc.portlet.admin.AdminAnnouncementController.java
/** * Saves the announcement/*from w w w . j a v a2s . com*/ * * @param req * @param res * @throws PortletException */ @RequestMapping(params = "action=addAnnouncement") public void actionAddAnnouncementForm(@ModelAttribute("announcement") Announcement announcement, BindingResult result, SessionStatus status, ActionRequest req, ActionResponse res) throws PortletException { // First verify the user has AUTHOR permission for this topic UserPermissionChecker upChecker = userPermissionCheckerFactory.createUserPermissionChecker(req, announcement.getParent()); if (!(upChecker.isAdmin() || upChecker.isModerator() || upChecker.isAuthor())) { throw new UnauthorizedException("You do not have permission to create an announcement in this topic"); } // Next validate the announcement new AnnouncementValidator(getAllowOpenEndDate(req), getAllowEmptyMessage(req)).validate(announcement, result); if (result.hasErrors()) { res.setRenderParameter("action", "addAnnouncement"); return; } // Before we save, be sure the user isn't sneaking in a disallowed attachment through clever request hacking... PortletPreferences prefs = req.getPreferences(); final boolean useAttachments = Boolean .valueOf(prefs.getValue(PREFERENCE_USE_ATTACHMENTS, DEFAULT_USE_ATTACHMENTS)); if (!useAttachments) { announcement.setAttachments(Collections.emptySet()); } if (!result.hasErrors()) { if (!announcement.hasId()) { // add the automatic data announcement.setAuthor(req.getRemoteUser()); announcement.setCreated(new Date()); announcementService.addOrSaveAnnouncement(announcement); } else { announcementService.mergeAnnouncement(announcement); } status.setComplete(); res.setRenderParameter("topicId", announcement.getParent().getId().toString()); res.setRenderParameter("action", "showTopic"); } }
From source file:org.jasig.portlet.announcements.mvc.portlet.admin.AdminTopicController.java
/** * Saves the Topic that was submitted/*from w w w . java2 s .c o m*/ * * @param topic * @param result * @param status * @param request * @param response * @throws PortletException */ @RequestMapping(params = "action=addTopic") public void actionAddTopicForm(@ModelAttribute("topic") Topic topic, BindingResult result, SessionStatus status, ActionRequest request, ActionResponse response) throws PortletException { if (!UserPermissionChecker.isPortalAdmin(request)) { throw new UnauthorizedException("You do not have access to create a topic"); } new TopicValidator().validate(topic, result); if (result.hasErrors()) { if (log.isDebugEnabled()) log.debug("Error in form: " + result.toString()); response.setRenderParameter("action", "addTopic"); return; } if (!result.hasErrors() && topic != null) { if (log.isDebugEnabled()) log.debug("No errors in form"); // no id has been assigned by hibernate, so this must be a new topic if (!topic.hasId()) { topic.setCreator(request.getRemoteUser()); announcementService.addOrSaveTopic(topic); } else { Long id = topic.getId(); Topic oldTopic = announcementService.getTopic(id); oldTopic.setTitle(topic.getTitle()); oldTopic.setDescription(topic.getDescription()); oldTopic.setAllowRss(topic.isAllowRss()); oldTopic.setSubscriptionMethod(topic.getSubscriptionMethod()); announcementService.addOrSaveTopic(oldTopic); } status.setComplete(); response.setRenderParameter("action", "baseAdmin"); } }
From source file:org.jasig.portlet.calendar.mvc.controller.EditUserHttpICalController.java
/** * Update the calendar in the data store. * //from w w w .ja v a2 s . c o m * @param request * @param response * @param form * @param result * @param status * @throws Exception */ @ActionMapping(params = "action=editUrl") public void updateHttpCalendar(ActionRequest request, ActionResponse response, @ModelAttribute(FORM_NAME) UserHttpIcalCalendarForm form, BindingResult result, SessionStatus status) throws Exception { // construct a calendar definition from the form data UserDefinedCalendarConfiguration config = null; UserDefinedCalendarDefinition definition = null; if (form.getId() > -1) { config = (UserDefinedCalendarConfiguration) calendarStore.getCalendarConfiguration(form.getId()); definition = config.getCalendarDefinition(); definition.addParameter("url", form.getUrl()); definition.setName(form.getName()); } else { definition = new UserDefinedCalendarDefinition(); definition.setClassName("httpIcalAdapter"); definition.addParameter("url", form.getUrl()); definition.setName(form.getName()); calendarStore.storeCalendarDefinition(definition); config = new UserDefinedCalendarConfiguration(); config.setCalendarDefinition(definition); config.setSubscribeId(form.getSubscribeId()); config.setDisplayed(form.isDisplayed()); } // save the calendar calendarStore.storeCalendarConfiguration(config); // send the user back to the main edit page response.setRenderParameter("action", "editSubscriptions"); status.setComplete(); }
From source file:org.mifos.ui.core.controller.AcceptedPaymentTypesController.java
@RequestMapping(method = RequestMethod.POST) public String processFormSubmit(@RequestParam(value = CANCEL_PARAM, required = false) String cancel, @ModelAttribute("acceptedPaymentTypesBean") AcceptedPaymentTypesBean formBean, BindingResult result, SessionStatus status) { String viewName = REDIRECT_TO_ADMIN_SCREEN; if (StringUtils.isNotBlank(cancel)) { viewName = REDIRECT_TO_ADMIN_SCREEN; status.setComplete(); } else if (result.hasErrors()) { viewName = "defineAcceptedPaymentTypes"; } else {//from w w w. j a v a 2 s . c o m this.adminServiceFacade.updateAcceptedPaymentTypes(formBean.getChosenAcceptedFees(), formBean.getChosenAcceptedLoanDisbursements(), formBean.getChosenAcceptedLoanRepayments(), formBean.getChosenAcceptedSavingDeposits(), formBean.getChosenAcceptedSavingWithdrawals()); status.setComplete(); } return viewName; }