Search in sources :

Example 1 with ValidationError

use of org.olat.core.gui.components.form.ValidationError in project OpenOLAT by OpenOLAT.

the class UserBulkChangeManager method changeSelectedIdentities.

public void changeSelectedIdentities(List<Identity> selIdentities, Map<String, String> attributeChangeMap, Map<String, String> roleChangeMap, List<String> notUpdatedIdentities, boolean isAdministrativeUser, List<Long> ownGroups, List<Long> partGroups, Translator trans, Identity addingIdentity) {
    Translator transWithFallback = userManager.getPropertyHandlerTranslator(trans);
    String usageIdentifyer = UserBulkChangeStep00.class.getCanonicalName();
    notUpdatedIdentities.clear();
    List<Identity> changedIdentities = new ArrayList<>();
    List<UserPropertyHandler> userPropertyHandlers = userManager.getUserPropertyHandlersFor(usageIdentifyer, isAdministrativeUser);
    String[] securityGroups = { Constants.GROUP_USERMANAGERS, Constants.GROUP_GROUPMANAGERS, Constants.GROUP_AUTHORS, Constants.GROUP_ADMIN, Constants.GROUP_POOL_MANAGER, Constants.GROUP_INST_ORES_MANAGER };
    // loop over users to be edited:
    for (Identity identity : selIdentities) {
        // reload identity from cache, to prevent stale object
        identity = securityManager.loadIdentityByKey(identity.getKey());
        User user = identity.getUser();
        String oldEmail = user.getEmail();
        String errorDesc = "";
        boolean updateError = false;
        // change pwd
        if (attributeChangeMap.containsKey(PWD_IDENTIFYER)) {
            String newPwd = attributeChangeMap.get(PWD_IDENTIFYER);
            if (StringHelper.containsNonWhitespace(newPwd)) {
                if (!userManager.syntaxCheckOlatPassword(newPwd)) {
                    errorDesc = transWithFallback.translate("error.password");
                    updateError = true;
                }
            } else {
                newPwd = null;
            }
            olatAuthManager.changePasswordAsAdmin(identity, newPwd);
        }
        // set language
        String userLanguage = user.getPreferences().getLanguage();
        if (attributeChangeMap.containsKey(LANG_IDENTIFYER)) {
            String inputLanguage = attributeChangeMap.get(LANG_IDENTIFYER);
            if (!userLanguage.equals(inputLanguage)) {
                Preferences preferences = user.getPreferences();
                preferences.setLanguage(inputLanguage);
                user.setPreferences(preferences);
            }
        }
        Context vcContext = new VelocityContext();
        // set all properties as context
        setUserContext(identity, vcContext);
        // org.olat.admin.user.bulkChange.UserBulkChangeStep00
        for (int k = 0; k < userPropertyHandlers.size(); k++) {
            UserPropertyHandler propHandler = userPropertyHandlers.get(k);
            String propertyName = propHandler.getName();
            String userValue = identity.getUser().getProperty(propertyName, null);
            String inputFieldValue = "";
            if (attributeChangeMap.containsKey(propertyName)) {
                inputFieldValue = attributeChangeMap.get(propertyName);
                inputFieldValue = inputFieldValue.replace("$", "$!");
                String evaluatedInputFieldValue = evaluateValueWithUserContext(inputFieldValue, vcContext);
                // validate evaluated property-value
                ValidationError validationError = new ValidationError();
                // do validation checks with users current locale!
                Locale locale = transWithFallback.getLocale();
                if (!propHandler.isValidValue(identity.getUser(), evaluatedInputFieldValue, validationError, locale)) {
                    errorDesc = transWithFallback.translate(validationError.getErrorKey(), validationError.getArgs()) + " (" + evaluatedInputFieldValue + ")";
                    updateError = true;
                    break;
                }
                if (!evaluatedInputFieldValue.equals(userValue)) {
                    String stringValue = propHandler.getStringValue(evaluatedInputFieldValue, locale);
                    propHandler.setUserProperty(user, stringValue);
                }
            }
        }
        // loop over securityGroups defined above
        for (String securityGroup : securityGroups) {
            SecurityGroup secGroup = securityManager.findSecurityGroupByName(securityGroup);
            Boolean isInGroup = securityManager.isIdentityInSecurityGroup(identity, secGroup);
            String thisRoleAction = "";
            if (roleChangeMap.containsKey(securityGroup)) {
                thisRoleAction = roleChangeMap.get(securityGroup);
                // user not anymore in security group, remove him
                if (isInGroup && thisRoleAction.equals("remove")) {
                    securityManager.removeIdentityFromSecurityGroup(identity, secGroup);
                    log.audit("User::" + addingIdentity.getName() + " removed system role::" + securityGroup + " from user::" + identity.getName(), null);
                }
                // user not yet in security group, add him
                if (!isInGroup && thisRoleAction.equals("add")) {
                    securityManager.addIdentityToSecurityGroup(identity, secGroup);
                    log.audit("User::" + addingIdentity.getName() + " added system role::" + securityGroup + " to user::" + identity.getName(), null);
                }
            }
        }
        // set status
        if (roleChangeMap.containsKey("Status")) {
            Integer status = Integer.parseInt(roleChangeMap.get("Status"));
            int oldStatus = identity.getStatus();
            String oldStatusText = (oldStatus == Identity.STATUS_PERMANENT ? "permanent" : (oldStatus == Identity.STATUS_ACTIV ? "active" : (oldStatus == Identity.STATUS_LOGIN_DENIED ? "login_denied" : (oldStatus == Identity.STATUS_DELETED ? "deleted" : "unknown"))));
            String newStatusText = (status == Identity.STATUS_PERMANENT ? "permanent" : (status == Identity.STATUS_ACTIV ? "active" : (status == Identity.STATUS_LOGIN_DENIED ? "login_denied" : (status == Identity.STATUS_DELETED ? "deleted" : "unknown"))));
            if (oldStatus != status && status == Identity.STATUS_LOGIN_DENIED && Boolean.parseBoolean(roleChangeMap.get("sendLoginDeniedEmail"))) {
                sendLoginDeniedEmail(identity);
            }
            identity = securityManager.saveIdentityStatus(identity, status);
            log.audit("User::" + addingIdentity.getName() + " changed accout status for user::" + identity.getName() + " from::" + oldStatusText + " to::" + newStatusText, null);
        }
        // persist changes:
        if (updateError) {
            String errorOutput = identity.getName() + ": " + errorDesc;
            log.debug("error during bulkChange of users, following user could not be updated: " + errorOutput);
            notUpdatedIdentities.add(errorOutput);
        } else {
            userManager.updateUserFromIdentity(identity);
            securityManager.deleteInvalidAuthenticationsByEmail(oldEmail);
            changedIdentities.add(identity);
            log.audit("User::" + addingIdentity.getName() + " successfully changed account data for user::" + identity.getName() + " in bulk change", null);
        }
        // commit changes for this user
        dbInstance.commit();
    }
    // FXOLAT-101: add identity to new groups:
    if (ownGroups.size() != 0 || partGroups.size() != 0) {
        List<BusinessGroupMembershipChange> changes = new ArrayList<BusinessGroupMembershipChange>();
        for (Identity selIdentity : selIdentities) {
            if (ownGroups != null && !ownGroups.isEmpty()) {
                for (Long tutorGroupKey : ownGroups) {
                    BusinessGroupMembershipChange change = new BusinessGroupMembershipChange(selIdentity, tutorGroupKey);
                    change.setTutor(Boolean.TRUE);
                    changes.add(change);
                }
            }
            if (partGroups != null && !partGroups.isEmpty()) {
                for (Long partGroupKey : partGroups) {
                    BusinessGroupMembershipChange change = new BusinessGroupMembershipChange(selIdentity, partGroupKey);
                    change.setParticipant(Boolean.TRUE);
                    changes.add(change);
                }
            }
        }
        MailPackage mailing = new MailPackage();
        businessGroupService.updateMemberships(addingIdentity, changes, mailing);
        dbInstance.commit();
    }
}
Also used : Context(org.apache.velocity.context.Context) VelocityContext(org.apache.velocity.VelocityContext) Locale(java.util.Locale) User(org.olat.core.id.User) MailPackage(org.olat.core.util.mail.MailPackage) VelocityContext(org.apache.velocity.VelocityContext) ArrayList(java.util.ArrayList) SecurityGroup(org.olat.basesecurity.SecurityGroup) BusinessGroupMembershipChange(org.olat.group.model.BusinessGroupMembershipChange) Translator(org.olat.core.gui.translator.Translator) ValidationError(org.olat.core.gui.components.form.ValidationError) Identity(org.olat.core.id.Identity) Preferences(org.olat.core.id.Preferences) UserPropertyHandler(org.olat.user.propertyhandlers.UserPropertyHandler)

Example 2 with ValidationError

use of org.olat.core.gui.components.form.ValidationError in project OpenOLAT by OpenOLAT.

the class LinksPortletEditController method initForm.

/**
 * @see org.olat.core.gui.components.form.flexible.impl.FormBasicController#initForm(org.olat.core.gui.components.form.flexible.FormItemContainer, org.olat.core.gui.control.Controller, org.olat.core.gui.UserRequest)
 */
@Override
protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) {
    title = uifactory.addTextElement("link.title", "link.title", 200, portletLink.getTitle(), formLayout);
    title.setMandatory(true);
    title.setNotEmptyCheck("link.title.not.empty");
    desc = uifactory.addRichTextElementForStringDataMinimalistic("link.desc", "link.desc", portletLink.getDescription(), 5, -1, formLayout, getWindowControl());
    linkURL = uifactory.addTextElement("link.url", "link.url", 1024, portletLink.getUrl(), formLayout);
    linkURL.setMandatory(true);
    linkURL.setNotEmptyCheck("link.url.not.empty");
    linkURL.setItemValidatorProvider(new ItemValidatorProvider() {

        @Override
        public boolean isValidValue(String value, final ValidationError validationError, final Locale locale) {
            try {
                if (!value.contains("://")) {
                    value = "http://".concat(value);
                }
                new URL(value);
            } catch (final MalformedURLException e) {
                validationError.setErrorKey("link.url.not.empty");
                return false;
            }
            return true;
        }
    });
    openPopup = uifactory.addCheckboxesHorizontal("link.open.new.window", "link.open.new.window", formLayout, new String[] { TARGET_BLANK }, new String[] { "" });
    if (portletLink.getTarget().equals(TARGET_BLANK)) {
        openPopup.selectAll();
    }
    // language
    Map<String, String> locdescs = I18nManager.getInstance().getEnabledLanguagesTranslated();
    Set<String> lkeys = locdescs.keySet();
    String[] languageKeys = new String[lkeys.size() + 1];
    String[] languageValues = new String[lkeys.size() + 1];
    languageKeys[0] = "*";
    languageValues[0] = translate("link.lang.all");
    int p = 1;
    for (Iterator<String> iter = lkeys.iterator(); iter.hasNext(); ) {
        String key = iter.next();
        languageKeys[p] = key;
        languageValues[p] = locdescs.get(key);
        p++;
    }
    language = uifactory.addDropdownSingleselect("link.language", formLayout, languageKeys, languageValues, null);
    String langKey = portletLink.getLanguage();
    if (Arrays.asList(languageKeys).contains(langKey)) {
        language.select(langKey, true);
    }
    uifactory.addFormSubmitButton("save", formLayout);
}
Also used : Locale(java.util.Locale) MalformedURLException(java.net.MalformedURLException) ItemValidatorProvider(org.olat.core.gui.components.form.flexible.impl.elements.ItemValidatorProvider) ValidationError(org.olat.core.gui.components.form.ValidationError) URL(java.net.URL)

Example 3 with ValidationError

use of org.olat.core.gui.components.form.ValidationError in project OpenOLAT by OpenOLAT.

the class UserPropertiesTest method testPhonePropertyHandlerValidation.

@Test
public void testPhonePropertyHandlerValidation() {
    PhonePropertyHandler phoneHandler = new PhonePropertyHandler();
    ValidationError error = new ValidationError();
    // test for valid phone number formats
    assertTrue(phoneHandler.isValidValue(null, "043 544 90 00", error, null));
    assertTrue(phoneHandler.isValidValue(null, "043/544'90'00", error, null));
    assertTrue(phoneHandler.isValidValue(null, "043/544'90'00", error, null));
    assertTrue(phoneHandler.isValidValue(null, "043-544-90-00", error, null));
    assertTrue(phoneHandler.isValidValue(null, "043.544.90.00", error, null));
    assertTrue(phoneHandler.isValidValue(null, "+41 43 544 90 00", error, null));
    assertTrue(phoneHandler.isValidValue(null, "+41 (0)43 544 90 00", error, null));
    assertTrue(phoneHandler.isValidValue(null, "+41 43 544 90 00 x0", error, null));
    assertTrue(phoneHandler.isValidValue(null, "+41 43 544 90 00 ext. 0", error, null));
    assertTrue(phoneHandler.isValidValue(null, "+41 43 544 90 00 ext0", error, null));
    assertTrue(phoneHandler.isValidValue(null, "+41 43 544 90 00 ext 0", error, null));
    assertTrue(phoneHandler.isValidValue(null, "+41 43 544 90 00 extension 0", error, null));
    assertTrue(phoneHandler.isValidValue(null, "+41 43 544 90 00 Extension 0", error, null));
    // test for invalid phone number formats
    assertFalse(phoneHandler.isValidValue(null, "+41 43 frentix GmbH", error, null));
}
Also used : PhonePropertyHandler(org.olat.user.propertyhandlers.PhonePropertyHandler) ValidationError(org.olat.core.gui.components.form.ValidationError) Test(org.junit.Test)

Example 4 with ValidationError

use of org.olat.core.gui.components.form.ValidationError in project OpenOLAT by OpenOLAT.

the class UserPropertiesTest method testURLPropertyHandlerValidation.

@Test
public void testURLPropertyHandlerValidation() {
    URLPropertyHandler urlHandler = new URLPropertyHandler();
    ValidationError error = new ValidationError();
    // test for valid URL's
    assertTrue(urlHandler.isValidValue(null, "http://www.openolat.org", error, null));
    assertTrue(urlHandler.isValidValue(null, "https://www.openolat.org", error, null));
    assertTrue(urlHandler.isValidValue(null, "http://test.ch", error, null));
    assertTrue(urlHandler.isValidValue(null, "http://localhost", error, null));
    // test for invalid URL's
    assertFalse(urlHandler.isValidValue(null, "http:www.openolat.org", error, null));
    assertFalse(urlHandler.isValidValue(null, "www.openolat.org", error, null));
}
Also used : URLPropertyHandler(org.olat.user.propertyhandlers.URLPropertyHandler) ValidationError(org.olat.core.gui.components.form.ValidationError) Test(org.junit.Test)

Example 5 with ValidationError

use of org.olat.core.gui.components.form.ValidationError in project OpenOLAT by OpenOLAT.

the class EmailProperty method addFormItem.

/**
 * @see org.olat.user.propertyhandlers.UserPropertyHandler#addFormItem(java.util.Locale, org.olat.core.id.User, java.lang.String, boolean, org.olat.core.gui.components.form.flexible.FormItemContainer)
 */
@Override
public FormItem addFormItem(Locale locale, final User user, String usageIdentifyer, final boolean isAdministrativeUser, FormItemContainer formItemContainer) {
    org.olat.core.gui.components.form.flexible.elements.TextElement tElem = null;
    tElem = (org.olat.core.gui.components.form.flexible.elements.TextElement) super.addFormItem(locale, user, usageIdentifyer, isAdministrativeUser, formItemContainer);
    // to validate the input a special isValidValue is used.
    if (usageIdentifyer.equals(UserBulkChangeStep00.class.getCanonicalName())) {
        tElem.setItemValidatorProvider(new ItemValidatorProvider() {

            @Override
            public boolean isValidValue(String value, ValidationError validationError, Locale locale2) {
                UserBulkChangeManager ubcMan = CoreSpringFactory.getImpl(UserBulkChangeManager.class);
                Context vcContext = new VelocityContext();
                if (user == null) {
                    vcContext = ubcMan.getDemoContext(locale2);
                } else // should be used if user-argument !=null --> move to right place
                {
                    Long userKey = user.getKey();
                    Identity identity = BaseSecurityManager.getInstance().loadIdentityByKey(userKey);
                    ubcMan.setUserContext(identity, vcContext);
                }
                value = value.replace("$", "$!");
                String evaluatedValue = ubcMan.evaluateValueWithUserContext(value, vcContext);
                return EmailProperty.this.isValidValue(user, evaluatedValue, validationError, locale2);
            }
        });
    }
    return tElem;
}
Also used : Locale(java.util.Locale) VelocityContext(org.apache.velocity.VelocityContext) Context(org.apache.velocity.context.Context) ItemValidatorProvider(org.olat.core.gui.components.form.flexible.impl.elements.ItemValidatorProvider) VelocityContext(org.apache.velocity.VelocityContext) UserBulkChangeStep00(org.olat.admin.user.bulkChange.UserBulkChangeStep00) UserBulkChangeManager(org.olat.admin.user.bulkChange.UserBulkChangeManager) ValidationError(org.olat.core.gui.components.form.ValidationError) Identity(org.olat.core.id.Identity)

Aggregations

ValidationError (org.olat.core.gui.components.form.ValidationError)24 Locale (java.util.Locale)14 ItemValidatorProvider (org.olat.core.gui.components.form.flexible.impl.elements.ItemValidatorProvider)10 MalformedURLException (java.net.MalformedURLException)4 URL (java.net.URL)4 VelocityContext (org.apache.velocity.VelocityContext)4 Context (org.apache.velocity.context.Context)4 Test (org.junit.Test)4 TextElement (org.olat.core.gui.components.form.flexible.elements.TextElement)4 Translator (org.olat.core.gui.translator.Translator)4 Identity (org.olat.core.id.Identity)4 UserManager (org.olat.user.UserManager)4 UserPropertyHandler (org.olat.user.propertyhandlers.UserPropertyHandler)4 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 UserBulkChangeManager (org.olat.admin.user.bulkChange.UserBulkChangeManager)2 UserBulkChangeStep00 (org.olat.admin.user.bulkChange.UserBulkChangeStep00)2 SecurityGroup (org.olat.basesecurity.SecurityGroup)2 DateChooser (org.olat.core.gui.components.form.flexible.elements.DateChooser)2 FormLink (org.olat.core.gui.components.form.flexible.elements.FormLink)2