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.citrix.cpbm.portal.fragment.controllers.AbstractTenantController.java

/**
 * Return alert preference id on successful creation of UserAlertPreference
 * //from   w  ww  .  j a v a 2  s .  c o  m
 * @param form
 * @param result
 * @return
 */
@RequestMapping(value = "/alert_prefs", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> saveAlertsDeliveryOptions(
        @Valid @ModelAttribute("userAlertEmailForm") UserAlertEmailForm form, BindingResult result) {
    logger.debug("###Entering in viewAlertsDeliveryOptions(map) method @POST");
    Map<String, String> returnMap = new HashMap<String, String>();
    if (result.hasErrors()) {
        throw new AjaxFormValidationException(result);
    }
    User user = form.getUser();
    user = userService.get(user.getUuid());
    String email = form.getEmail();
    AlertType alertType = form.getAlertType();

    long addAlertEmailLimit = config
            .getIntValue(Names.com_citrix_cpbm_accountManagement_resourceLimits_registered_emailAddresses);
    long alertsPrefsSize = userAlertPreferencesService.getCount(user);
    if (alertsPrefsSize >= addAlertEmailLimit) {
        result.rejectValue("email", "error.verifyAlertEmail.limitReached");
        throw new AjaxFormValidationException(result);
    }

    if (isEmailBlacklisted(email)) {
        result.rejectValue("email", "signup.emaildomain.blacklist.error");
        throw new AjaxFormValidationException(result);
    }

    if (email.equals(user.getEmail())) {
        result.rejectValue("email", "js.errors.addsecAlert.sameAsPrimaryEmail");
        throw new AjaxFormValidationException(result);
    }

    if (userAlertPreferencesService.checkUserAlertPrefsExists(alertType, user, email)) {
        result.rejectValue("email", "error.verifyAlertEmail.exists");
        throw new AjaxFormValidationException(result);
    }

    UserAlertPreferences alertPref = userAlertPreferencesService.createUserAlertPreference(user, email,
            alertType);
    returnMap.put("id", alertPref.getId().toString());
    logger.debug("###Exiting viewAlertsDeliveryOptions(map) method @POST - success");
    return returnMap;
}

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

protected String createUser(final B2BCustomerForm b2BCustomerForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectModel) throws CMSItemNotFoundException {

    if (bindingResult.hasErrors()) {
        GlobalMessages.addErrorMessage(model, "form.global.error");
        model.addAttribute(b2BCustomerForm);
        model.addAttribute("newUserEdit", "YES");
        return editUser(b2BCustomerForm.getUid(), model);
    }/*from  w  w  w  .j  av a 2  s  .  com*/

    final CustomerData b2bCustomerData = new CustomerData();
    b2bCustomerData.setTitleCode(b2BCustomerForm.getTitleCode());
    b2bCustomerData.setFirstName(b2BCustomerForm.getFirstName());
    b2bCustomerData.setLastName(b2BCustomerForm.getLastName());
    b2bCustomerData.setEmail(b2BCustomerForm.getEmail());
    b2bCustomerData.setDisplayUid(b2BCustomerForm.getEmail());
    b2bCustomerData.setUnit(b2bUnitFacade.getUnitForUid(b2BCustomerForm.getParentB2BUnit()));
    b2bCustomerData.setRoles(b2BCustomerForm.getRoles());
    model.addAttribute(b2BCustomerForm);
    model.addAttribute("titleData", getUserFacade().getTitles());
    model.addAttribute("roles", populateRolesCheckBoxes(b2bUserGroupFacade.getUserGroups()));

    storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.getBreadcrumbs(null);
    breadcrumbs.add(new Breadcrumb("/my-company/organization-management/", getMessageSource().getMessage(
            "text.company.organizationManagement", null, getI18nService().getCurrentLocale()), null));
    breadcrumbs.add(new Breadcrumb("/my-company/organization-management/manage-user", getMessageSource()
            .getMessage("text.company.manageUsers", null, getI18nService().getCurrentLocale()), null));
    model.addAttribute("breadcrumbs", breadcrumbs);

    try {
        b2bUserFacade.updateCustomer(b2bCustomerData);
        b2bCustomerData.setUid(b2BCustomerForm.getEmail().toLowerCase());
        b2BCustomerForm.setUid(b2bCustomerData.getUid());
        GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
                "text.confirmation.user.added");
    } catch (final ModelSavingException e) {
        if (e.getCause() instanceof InterceptorException && ((InterceptorException) e.getCause())
                .getInterceptor().getClass().equals(UniqueAttributesInterceptor.class)) {
            LOG.error("The uid of the model being stored already exists, could not save. Edit user instead.");

            bindingResult.rejectValue("email", "text.manageuser.error.email.exists.title");
            GlobalMessages.addErrorMessage(model, "form.global.error");
            model.addAttribute("b2BCustomerForm", b2BCustomerForm);
            return editUser(b2BCustomerForm.getUid(), model);
        }
    }
    return String.format(REDIRECT_TO_USER_DETAILS, urlEncode(b2bCustomerData.getUid()));
}

From source file:org.openmrs.module.personalhr.web.controller.PhrUserFormController.java

/**
 * @should work for an example//from  www  .  j  av a 2 s  .  com
 */
@RequestMapping(value = "/phr/user.form", method = RequestMethod.POST)
public String handleSubmission(final WebRequest request, final HttpSession httpSession, final ModelMap model,
        @RequestParam(required = false, value = "action") final String action,
        @RequestParam(required = false, value = "userFormPassword") String password,
        @RequestParam(required = false, value = "secretQuestion") final String secretQuestion,
        @RequestParam(required = false, value = "secretAnswer") final String secretAnswer,
        @RequestParam(required = false, value = "confirm") String confirm,
        @RequestParam(required = false, value = "forcePassword") final Boolean forcePassword,
        @RequestParam(required = false, value = "roleStrings") final String[] roles,
        @RequestParam(required = false, value = "createNewPerson") final String createNewPerson,
        @RequestParam(required = false, value = "sharingToken") String sharingToken,
        @ModelAttribute("user") final User user, final BindingResult errors) {

    if (sharingToken == null) {
        sharingToken = (String) model.get("sharingToken");
    }

    log.debug("Entering PhrUserFormController:handleSubmission..." + sharingToken);
    //add temporary privileges
    boolean isTemporary = false;
    boolean isAdministrator = false;
    if (!Context.isAuthenticated()) {
        Context.authenticate("temporary", "Temporary8");
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
        Context.addProxyPrivilege("PHR Restricted Patient Access");
        isTemporary = true;
        log.debug("Added proxy privileges!");
    } else {
        if (PhrService.PhrBasicRole.PHR_ADMINISTRATOR.getValue()
                .equals(PersonalhrUtil.getService().getPhrRole(Context.getAuthenticatedUser()))) {
            isAdministrator = true;
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_DELETE_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_PURGE_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
        }
    }

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

        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:/phr/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:/phr/user.list";
            } catch (final Exception ex) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "User.delete.failure");
                log.error("Failed to delete user", ex);
                return "redirect:/phr/user.form?userId=" + request.getParameter("userId");
            }

        } else if (mss.getMessage("User.retire").equals(action)) {
            final String retireReason = request.getParameter("retireReason");
            if (!(StringUtils.hasText(retireReason))) {
                errors.rejectValue("retireReason", "User.disableReason.empty");
                return showForm(user.getUserId(), createNewPerson, sharingToken, user, model, httpSession);
            } 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("error.password.weak");
            }

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

            final Set<Role> newRoles = new HashSet<Role>();
            if (roles != null) {
                for (final 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 (final Role test : user.getRoles()) {
                            if (test.getRole().equals(r)) {
                                role = test;
                            }
                        }
                    }
                    if (role == null) {
                        role = us.getRole(r);
                        user.addRole(role);
                    }
                    newRoles.add(role);
                }
            } else {
                final Role role = us.getRole("PHR Restricted User");
                newRoles.add(role);
                user.addRole(role);
                log.debug("Added PHR Restricted User role only: " + role);
            }

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

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

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

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

            final UserValidator uv = new UserValidator();
            uv.validate(user, errors);

            if (errors.hasErrors()) {
                log.debug("errors validating user: " + errors.getErrorCount() + errors.toString());
                return showForm(user.getUserId(), createNewPerson, sharingToken, user, model, httpSession);
            }

            String emailEntered = request.getParameter("9");

            if (isNewUser(user) && !isAdministrator) {
                log.debug("Saving new user " + user.getUsername() + ", sharingToken=" + sharingToken);
                final PhrSharingToken token = Context.getService(PhrSharingTokenService.class)
                        .getSharingToken(sharingToken);

                //check token existence and name matching
                if (token == null || token.getExpireDate().before(new Date())) {
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "Failed to register without a valid sharing token");
                    log.error("Failed to register without a valid sharing token");
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "error=Failed to register without a valid sharing token; user_name="
                                    + user.getName());

                    if (isTemporary) {
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
                        Context.removeProxyPrivilege("PHR Restricted Patient Access");
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
                        Context.logout();
                        log.debug("Removed proxy privileges!");
                    }
                    return "redirect:/phr/index.htm?noredirect=true";
                } else if ((token != null) && (token.getRelatedPerson() != null)) {
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "Failed to register with a used sharing token");
                    log.error("Failed to register with a used sharing token");
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "error=Failed to register with a used sharing token; user_name=" + user.getName()
                                    + "; sharingToken=" + token);
                    if (isTemporary) {
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
                        Context.removeProxyPrivilege("PHR Restricted Patient Access");
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
                        Context.logout();
                        log.debug("Removed proxy privileges!");
                    }

                    return "redirect:/phr/index.htm?noredirect=true";
                } else if (emailEntered != null
                        && token.getRelatedPersonEmail().equalsIgnoreCase(emailEntered)) {
                    // look for person attributes (including email entered) in the request and save to user
                    for (final PersonAttributeType type : Context.getPersonService()
                            .getPersonAttributeTypes(PERSON_TYPE.PATIENT, ATTR_VIEW_TYPE.VIEWING)) {
                        final String paramName = type.getPersonAttributeTypeId().toString();
                        final String value = request.getParameter(paramName);

                        this.log.debug("paramName=" + paramName);

                        // if there is an error displaying the attribute, the value will be null
                        if (value != null) {
                            final PersonAttribute attribute = new PersonAttribute(type, value);
                            try {
                                final Object hydratedObject = attribute.getHydratedObject();
                                if ((hydratedObject == null) || "".equals(hydratedObject.toString())) {
                                    // if null is returned, the value should be blanked out
                                    attribute.setValue("");
                                } else if (hydratedObject instanceof Attributable) {
                                    attribute.setValue(((Attributable) hydratedObject).serialize());
                                } else if (!hydratedObject.getClass().getName().equals(type.getFormat())) {
                                    // if the classes doesn't match the format, the hydration failed somehow
                                    // TODO change the PersonAttribute.getHydratedObject() to not swallow all errors?
                                    throw new APIException();
                                }
                            } catch (final APIException e) {
                                errors.rejectValue("attributeMap[" + type.getName() + "]",
                                        "Invalid value for " + type.getName() + ": '" + value + "'");
                                this.log.warn("Got an invalid value: " + value
                                        + " while setting personAttributeType id #" + paramName, e);

                                // setting the value to empty so that the user can reset the value to something else
                                attribute.setValue("");

                            }
                            user.getPerson().addAttribute(attribute);
                        }
                    }

                    //create a new user by self registration
                    us.saveUser(user, password);

                    //update sharing token
                    token.setRelatedPerson(user.getPerson());
                    token.setChangedBy(user);
                    final Date date = new Date();
                    token.setDateChanged(date);
                    token.setActivateDate(date);
                    Context.getService(PhrSharingTokenService.class).savePhrSharingToken(token);
                    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "personalhr.user.signed.up");
                    log.debug("New self-registered user created: " + user.getUsername());
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), user,
                            httpSession.getId(), null, "info=New self-registered user created; user_name="
                                    + user.getName() + "; sharingToken=" + token);

                    //save email to messaging service
                    Integer addressId = saveEmail(user.getPerson(), emailEntered);

                    //set default messaging alert address
                    boolean shouldAlert = true;
                    PersonalhrUtil.setMessagingAlertSettings(user.getPerson(), shouldAlert, addressId);

                    //send email notification

                    // TODO get the deployUrl from the request object; also bad to inject /openmrs/ ...
                    final String deployUrl = Context.getRuntimeProperties().getProperty("deployment.url");//"https://65.111.248.164:8443/"; //"172.30.201.24";

                    final String url = deployUrl + "/openmrs/phr/index.htm";
                    final String passwordOption = Context.getAdministrationService()
                            .getGlobalProperty("personalhr.show.password");

                    String notification = NOTIFICATION_TEMPLATE;
                    notification = notification.replaceAll("OPENMRS_PHR_RELATED_PERSON",
                            user.getPerson().getGivenName());
                    notification = notification.replaceAll("OPENMRS_USERNAME", user.getUsername());
                    notification = notification.replaceAll("OPENMRS_PASSWORD",
                            showPassword(password, passwordOption));
                    notification = notification.replaceAll("OPENMRS_URL", url);

                    PersonalhrUtil.sendEmail(emailEntered, notification);
                } else {
                    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                            "Failed to create new user due to email mismatch: " + emailEntered);
                    log.debug("Failed to create new user due to email mismatch: "
                            + token.getRelatedPersonEmail() + " vs " + emailEntered);
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "info=Failed to create new user due to email mismatch: "
                                    + token.getRelatedPersonEmail() + "vs " + emailEntered + "; sharingToken="
                                    + token);
                }
            } else if (isNewUser(user) && isAdministrator) {
                //create a new user by PHR Administrator
                us.saveUser(user, password);
            } else {
                //modify an exiting user
                us.saveUser(user, null);

                if (!password.equals("") && Context.hasPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS)) {
                    if (log.isDebugEnabled()) {
                        log.debug("calling changePassword for user " + user + " by user "
                                + Context.getAuthenticatedUser());
                    }
                    us.changePassword(user, password);
                }
                log.debug("Existing user " + user.getUsername() + " changed by user "
                        + Context.getAuthenticatedUser().getUsername());
                PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_UPDATE, new Date(),
                        Context.getAuthenticatedUser(), httpSession.getId(), null,
                        "info=Existing user updated; user_name=" + user.getName());
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
            }

            if (StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) {
                us.changeQuestionAnswer(user, secretQuestion, secretAnswer);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
            }
        }
    } finally {
        //remove temporary privileges
        if (isTemporary) {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
            Context.removeProxyPrivilege("PHR Restricted Patient Access");
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
            Context.logout();
            log.debug("Removed proxy privileges for self registration!");
        } else if (isAdministrator) {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_DELETE_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_PURGE_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
            log.debug("Removed proxy privileges for PHR Administrator!");
        }
    }
    return "redirect:/phr/index.htm?noredirect=true";
}

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

/**
 * Create new Alert POST method.//from   w w  w .  j a v a 2  s  .  com
 * 
 * @param tenant
 * @param tenantParam
 * @param form
 * @param result
 * @param map
 * @param request
 * @return
 */
@RequestMapping(value = "/alerts/new", method = RequestMethod.POST)
@ResponseBody
public SpendAlertSubscription createSpendAlertSubscription(@ModelAttribute("currentTenant") Tenant tenant,
        @RequestParam(value = "tenant", required = false) String tenantParam,
        @ModelAttribute("subscriptionForm") CustomAlertForm form, BindingResult result, ModelMap map,
        HttpServletRequest request) {
    logger.debug("###Entering in createSubscription(form,result,map) method @POST");
    User user = getCurrentUser();
    Tenant effectiveTenant = (Tenant) request.getAttribute(UserContextInterceptor.EFFECTIVE_TENANT_KEY);
    if ((Boolean) request.getAttribute("isSurrogatedTenant")) {
        user = effectiveTenant.getOwner();
    }
    int subscriptionType = 1; // Spend Limit money value type
    SpendAlertSubscription subscription = new SpendAlertSubscription();
    subscription.setSubscriptionType(subscriptionType);
    AccountHolder accountHolder = null;
    if (form.getType().equals("tenant")) {
        accountHolder = effectiveTenant;
    } else {
        accountHolder = user;
    }
    // Validation code.
    AlertValidator validator = new AlertValidator();
    validator.validate(form, result);
    if (result.hasErrors()) {
        throw new AjaxFormValidationException(result);
    }
    if (effectiveTenant != null) {
        List<SpendAlertSubscription> spendAlertSubscription = notificationService
                .getAllSubscriptions(effectiveTenant);
        if (CollectionUtils.isNotEmpty(spendAlertSubscription)) {
            for (SpendAlertSubscription spendAlertSubscription2 : spendAlertSubscription) {
                if (spendAlertSubscription2.getPercentage().doubleValue() == form.getTenantPercentage()
                        .doubleValue()) {
                    result.rejectValue("tenantPercentage", "js.errors.tenantPercentage.validatePercentage");
                    throw new AjaxFormValidationException(result);
                }
            }
        }
    }

    subscription.setPercentage(form.getTenantPercentage());
    subscription.setAccountHolder(accountHolder);
    subscription.setUser(user);
    // add new subscription
    subscription = notificationService.saveSubscription(subscription);
    return subscription;
}

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

protected String editUser(final String user, final B2BCustomerForm b2BCustomerForm,
        final BindingResult bindingResult, final Model model, final RedirectAttributes redirectModel)
        throws CMSItemNotFoundException {
    if (bindingResult.hasErrors()) {
        GlobalMessages.addErrorMessage(model, "form.global.error");
        model.addAttribute(b2BCustomerForm);
        return editUser(b2BCustomerForm.getUid(), model);
    }// w  w  w  .j a v  a 2 s  . c  o  m

    // A B2B Admin should not be able to downgrade their roles, they must at lest belong to B2B Administrator role
    if (customerFacade.getCurrentCustomer().getUid().equals(b2BCustomerForm.getUid())) {
        final Collection<String> roles = b2BCustomerForm.getRoles() != null ? b2BCustomerForm.getRoles()
                : new ArrayList<String>();
        if (!roles.contains(B2BConstants.B2BADMINGROUP)) {
            GlobalMessages.addErrorMessage(model, "form.b2bcustomer.adminrole.error");
            roles.add(B2BConstants.B2BADMINGROUP);
            b2BCustomerForm.setRoles(roles);
            model.addAttribute(b2BCustomerForm);
            return editUser(b2BCustomerForm.getUid(), model);
        } else {
            // A session user can't modify their own parent unit.
            final B2BUnitData parentUnit = companyB2BCommerceFacade.getParentUnit();
            if (!parentUnit.getUid().equals(b2BCustomerForm.getParentB2BUnit())) {
                GlobalMessages.addErrorMessage(model, "form.b2bcustomer.parentunit.error");
                b2BCustomerForm.setParentB2BUnit(parentUnit.getUid());
                model.addAttribute(b2BCustomerForm);
                return editUser(b2BCustomerForm.getUid(), model);
            }
        }
    }

    final CustomerData b2bCustomerData = new CustomerData();
    b2bCustomerData.setUid(b2BCustomerForm.getUid());
    b2bCustomerData.setTitleCode(b2BCustomerForm.getTitleCode());
    b2bCustomerData.setFirstName(b2BCustomerForm.getFirstName());
    b2bCustomerData.setLastName(b2BCustomerForm.getLastName());
    b2bCustomerData.setEmail(b2BCustomerForm.getEmail());
    b2bCustomerData.setDisplayUid(b2BCustomerForm.getEmail());
    b2bCustomerData.setUnit(companyB2BCommerceFacade.getUnitForUid(b2BCustomerForm.getParentB2BUnit()));
    b2bCustomerData.setRoles(
            b2BCustomerForm.getRoles() != null ? b2BCustomerForm.getRoles() : Collections.<String>emptyList());
    model.addAttribute(b2BCustomerForm);
    model.addAttribute("titleData", getUserFacade().getTitles());
    model.addAttribute("roles", populateRolesCheckBoxes(companyB2BCommerceFacade.getUserGroups()));

    storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManageUserDetailsBreadcrumb(user);
    model.addAttribute("breadcrumbs", breadcrumbs);

    try {
        b2bCommerceUserFacade.updateCustomer(b2bCustomerData);
        b2bCustomerData.setUid(b2BCustomerForm.getEmail().toLowerCase());
        GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
                "text.confirmation.user.edited");
    } catch (final DuplicateUidException e) {
        bindingResult.rejectValue("email", "text.manageuser.error.email.exists.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
        model.addAttribute("b2BCustomerForm", b2BCustomerForm);
        return editUser(b2BCustomerForm.getUid(), model);

    }
    return String.format(REDIRECT_TO_USER_DETAILS, urlEncode(b2bCustomerData.getUid()));
}

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

protected String editUser(final String user, final B2BCustomerForm b2BCustomerForm,
        final BindingResult bindingResult, final Model model, final RedirectAttributes redirectModel)
        throws CMSItemNotFoundException {
    if (bindingResult.hasErrors()) {
        GlobalMessages.addErrorMessage(model, "form.global.error");
        model.addAttribute(b2BCustomerForm);
        return editUser(b2BCustomerForm.getUid(), model);
    }/*w  w w .  j a  v a 2s .c om*/

    // A B2B Admin should not be able to downgrade their roles, they must at lest belong to B2B Administrator role
    if (customerFacade.getCurrentCustomer().getUid().equals(b2BCustomerForm.getUid())) {
        final Collection<String> roles = b2BCustomerForm.getRoles() != null ? b2BCustomerForm.getRoles()
                : new ArrayList<String>();
        if (!roles.contains(B2BConstants.B2BADMINGROUP)) {
            GlobalMessages.addErrorMessage(model, "form.b2bcustomer.adminrole.error");
            roles.add(B2BConstants.B2BADMINGROUP);
            b2BCustomerForm.setRoles(roles);
            model.addAttribute(b2BCustomerForm);
            return editUser(b2BCustomerForm.getUid(), model);
        } else {
            // A session user can't modify their own parent unit.
            final B2BUnitData parentUnit = b2bUnitFacade.getParentUnit();
            if (!parentUnit.getUid().equals(b2BCustomerForm.getParentB2BUnit())) {
                GlobalMessages.addErrorMessage(model, "form.b2bcustomer.parentunit.error");
                b2BCustomerForm.setParentB2BUnit(parentUnit.getUid());
                model.addAttribute(b2BCustomerForm);
                return editUser(b2BCustomerForm.getUid(), model);
            }
        }
    }

    final CustomerData b2bCustomerData = new CustomerData();
    b2bCustomerData.setUid(b2BCustomerForm.getUid());
    b2bCustomerData.setTitleCode(b2BCustomerForm.getTitleCode());
    b2bCustomerData.setFirstName(b2BCustomerForm.getFirstName());
    b2bCustomerData.setLastName(b2BCustomerForm.getLastName());
    b2bCustomerData.setEmail(b2BCustomerForm.getEmail());
    b2bCustomerData.setDisplayUid(b2BCustomerForm.getEmail());
    b2bCustomerData.setUnit(b2bUnitFacade.getUnitForUid(b2BCustomerForm.getParentB2BUnit()));
    b2bCustomerData.setRoles(
            b2BCustomerForm.getRoles() != null ? b2BCustomerForm.getRoles() : Collections.<String>emptyList());
    model.addAttribute(b2BCustomerForm);
    model.addAttribute("titleData", getUserFacade().getTitles());
    model.addAttribute("roles", populateRolesCheckBoxes(b2bUserGroupFacade.getUserGroups()));

    storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManageUserDetailsBreadcrumb(user);
    model.addAttribute("breadcrumbs", breadcrumbs);

    try {
        b2bUserFacade.updateCustomer(b2bCustomerData);
        b2bCustomerData.setUid(b2BCustomerForm.getEmail().toLowerCase());
        GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
                "text.confirmation.user.edited");
    } catch (final ModelSavingException e) {
        bindingResult.rejectValue("email", "text.manageuser.error.email.exists.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
        model.addAttribute("b2BCustomerForm", b2BCustomerForm);
        return editUser(b2BCustomerForm.getUid(), model);

    }
    return String.format(REDIRECT_TO_USER_DETAILS, urlEncode(b2bCustomerData.getUid()));
}

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

/**
 * This method handles add new system user.
 * //w  ww  .  j av  a2  s .  com
 * @param userLogin - UserLogin obj.
 * @param result - BindingResult.
 * @param model - {@link ModelMap}
 * @param session - {@link HttpSession}
 * @param request - {@link HttpServletRequest}
 * @throws AkuraAppException - AkuraAppException.
 * @return name of the view which is redirected to.
 */
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(@ModelAttribute(MODEL_ATT_USER_DETAIL) UserLogin userLogin, BindingResult result,
        ModelMap model, HttpSession session, HttpServletRequest request) throws AkuraAppException {

    String dispatchUrl = null;
    systemUserValidator.validate(userLogin, result);
    UserLogin existUser = null;

    try {

        if (result.hasErrors()) {
            dispatchUrl = VIEW_CREATE_SYSTEM_USER;

        } else {

            final int selectedUserLoginId = Integer.parseInt(request.getParameter(REQ_USER_LOGIN_ID));
            String confirmPassword = request.getParameter(REQ_CONFIRM_PASSWORD);
            existUser = (selectedUserLoginId > 0 ? userService.getUserByName(userLogin.getUsername()) : null);

            boolean isUserNameExist = false;
            boolean isEmailExist = false;
            boolean isConfirmedPassword = false;
            boolean isUserIdentificationNoExits = false;
            boolean isPastUser = false;
            int identificationNo = 0; // staff key or the student key.
            int userRoleId = userLogin.getUserRoleId();
            String userIdNo = userLogin.getUserIdentificationNo();

            int roleId = userLogin.getUserRoleId();
            String identification = userLogin.getUserIdentificationNo() != null
                    ? userLogin.getUserIdentificationNo().trim()
                    : "";
            int userKey = 0; // the key of the user.

            // gets the student key and the staff key as the identification number with the
            // user role key and the admission number or the registration number
            userKey = getIdentificationNo(identification, roleId);

            // Validate whether the user name is already exist.
            // User name can not be duplicate for any user role.
            if (existUser == null) {
                isUserNameExist = isUserNameExist(userLogin.getUsername().trim());
            }

            // Validate whether the email is already exist. Email can
            // not be duplicate for any user role.
            if (existUser == null || !userLogin.getEmail().equals(existUser.getEmail())) {
                isEmailExist = isEmailExist(userLogin.getEmail());
            }

            // Check whether the password and confirmPassword are equal.
            isConfirmedPassword = isConfirmPassword(userLogin.getPassword(), confirmPassword);

            // check whether the user is past or not
            if (validateIdentificationNo(userRoleId, userIdNo)) {
                userLogin.setUserIdentificationNo(userKey + "");
                isPastUser = isPastUser(userLogin);
            }
            // Check whether the user Identification no is exists.
            if (identification != null && !identification.isEmpty() && existUser == null) {

                // gets the student key and the staff key as the identification number with the
                // user role key and the admission number or the registration number if there is
                // a user login for the user.
                identificationNo = userService.getAnyUserByUserRoleIdAndIdentificationNo(roleId,
                        identification);

                // checks the identification number is already exist or not.
                isUserIdentificationNoExits = isUserIdentificationNoExist(identificationNo);
            }

            if (isUserNameExist || isEmailExist || isConfirmedPassword || isUserIdentificationNoExits
                    || isPastUser) {

                if (isConfirmedPassword) {
                    result.rejectValue(PASSWORD, ERROR_MSG_PASSWORD_ERROR);
                } else if (isEmailExist) {
                    result.rejectValue(EMAIL, ERROR_MSG_EMAIL_EXIST);
                } else if (isUserNameExist) {
                    result.rejectValue(USERNAME, ERROR_MSG_USERNAME_EXIST);
                } else if (isPastUser) {
                    result.rejectValue(USERNAME, ERROR_MSG_USERLOGIN_PAST_USER);
                } else {
                    result.rejectValue(USER_IDENTIFICATION_NO, ERROR_MSG_IDENTIFICATION_EXITS);
                }
                dispatchUrl = VIEW_CREATE_SYSTEM_USER;

            } else if (validateIdentificationNo(userRoleId, userIdNo) && existUser == null
                    || existUser != null) {
                // check valid admission no is entered
                String psWord = userLogin.getPassword();

                // set user identification NO (replace RegNo with Primary key. E.g. RegNo with
                // Student_id).
                userLogin.setUserIdentificationNo(userKey + "");

                // set system generated password to true & status to true.
                if (existUser == null
                        || !existUser.getPassword().equals(userService.encodePassword(userLogin))) {
                    userLogin.setGeneratedPassword(true);
                }
                userLogin.setStatus(true);

                if (existUser != null) {
                    userService.editUser(userLogin);
                } else {
                    userService.createUser(userLogin, userKey);
                }

                String status = this.sendConfirmationMail(userLogin, psWord, session, model);

                if (status == SUCCESS && existUser == null) {
                    String message = new ErrorMsgLoader().getErrorMessage(SUCCESS_MSG_SYS_USER);
                    model.addAttribute(MODEL_ATT_MESSAGE, message);
                    dispatchUrl = showSystemUserDetailForm(model);
                } else if (status == SUCCESS && existUser != null) {
                    String message = new ErrorMsgLoader().getErrorMessage(SUCCESS_MSG_SYS_USER_EDIT);
                    model.addAttribute(MODEL_ATT_MESSAGE, message);
                    dispatchUrl = showSystemUserDetailForm(model);
                } else {
                    dispatchUrl = status;
                }

            } else {
                result.rejectValue(USER_IDENTIFICATION_NO, ERROR_MSG_INVALID_IDENTIFICATION);
                dispatchUrl = VIEW_CREATE_SYSTEM_USER;
            }
        }
    } catch (AkuraAppException e) {
        boolean errorMessage = false;
        if (e.getCause() instanceof IllegalArgumentException) {
            errorMessage = true;
        }
        if (e.getCause() instanceof ResourceNotFoundException) {
            errorMessage = true;
        } else {
            throw e;
        }

        if (errorMessage) {

            LOG.error("Error Sending Mail ( onSubmit method )" + e);

            String message = new ErrorMsgLoader().getErrorMessage(MSG_SYSTEM_USER_MAIL);
            model.addAttribute(MODEL_ATT_MESSAGE, message);
            dispatchUrl = showSystemUserDetailForm(model);
        }
    }
    String identificationNo = getUserIdentificationNo(userLogin);
    model.addAttribute(MODEL_ATT_USER_IDENTIFICATION_NO, identificationNo);
    model.addAttribute(MODEL_ATT_USER_DETAIL, userLogin);

    return dispatchUrl;
}