Example usage for javax.naming.directory DirContext modifyAttributes

List of usage examples for javax.naming.directory DirContext modifyAttributes

Introduction

In this page you can find the example usage for javax.naming.directory DirContext modifyAttributes.

Prototype

public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException;

Source Link

Document

Modifies the attributes associated with a named object using an ordered list of modifications.

Usage

From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java

/**
 * Change the password on the LDAP server.
 * @see org.olat.ldap.LDAPLoginManager#changePassword(org.olat.core.id.Identity, java.lang.String, org.olat.ldap.LDAPError)
 *///  w  ww.j a  v  a2 s  .  com
@Override
public boolean changePassword(Identity identity, String pwd, LDAPError errors) {
    String uid = identity.getName();
    String ldapUserPasswordAttribute = syncConfiguration.getLdapUserPasswordAttribute();
    try {
        DirContext ctx = bindSystem();
        String dn = ldapDao.searchUserDN(uid, ctx);

        ModificationItem[] modificationItems = new ModificationItem[1];

        Attribute userPasswordAttribute;
        if (ldapLoginModule.isActiveDirectory()) {
            //active directory need the password enquoted and unicoded (but little-endian)
            String quotedPassword = "\"" + pwd + "\"";
            char unicodePwd[] = quotedPassword.toCharArray();
            byte pwdArray[] = new byte[unicodePwd.length * 2];
            for (int i = 0; i < unicodePwd.length; i++) {
                pwdArray[i * 2 + 1] = (byte) (unicodePwd[i] >>> 8);
                pwdArray[i * 2 + 0] = (byte) (unicodePwd[i] & 0xff);
            }
            userPasswordAttribute = new BasicAttribute(ldapUserPasswordAttribute, pwdArray);
        } else {
            userPasswordAttribute = new BasicAttribute(ldapUserPasswordAttribute, pwd);
        }

        modificationItems[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPasswordAttribute);
        ctx.modifyAttributes(dn, modificationItems);
        ctx.close();
        return true;
    } catch (NamingException e) {
        log.error("NamingException when trying to change password with username::" + uid, e);
        errors.insert("Cannot change the password");
        return false;
    } catch (Exception e) {
        log.error("Unexpected exception when trying to change password with username::" + uid, e);
        errors.insert("Cannot change the password");
        return false;
    }
}

From source file:org.projectforge.business.ldap.LdapDao.java

public void modify(final DirContext ctx, final T obj, final List<ModificationItem> modificationItems)
        throws NamingException {
    final Object id = getId(obj);
    // The dn is may-be changed, so find the original dn by id:
    final T origObject = findById(ctx, id, obj.getOrganizationalUnit());
    if (origObject == null) {
        throw new RuntimeException("Object with id " + id + " not found in search base '"
                + StringHelper.listToString(",", obj.getOrganizationalUnit()) + "'. Can't modify the object: "
                + obj);/*from  w  w w . j  ava2 s  .c o m*/
    }
    final String dn = origObject.getDn();
    log.info("Modify attributes of " + getObjectClass() + ": " + dn + ": " + getLogInfo(obj));
    final ModificationItem[] items = modificationItems.toArray(new ModificationItem[modificationItems.size()]);
    ctx.modifyAttributes(dn, items);
    // Don't move object.
    // if (obj.getDn() != null && StringUtils.equals(dn, obj.getDn()) == false) {
    // log.info("DN of object is changed from '" + dn + "' to '" + obj.getDn());
    // ctx.rename(dn, obj.getDn());
    // }
}

From source file:org.sonar.plugins.activedirectory.server.ApacheDS.java

/**
 * This seems to be required for objectClass posixGroup.
 *//*  www  .j a v a2  s  .c o m*/
private ApacheDS activateNis() throws Exception {
    Preconditions.checkState(ldapServer.isStarted());

    Attribute disabled = new BasicAttribute("m-disabled", "TRUE");
    Attribute disabled2 = new BasicAttribute("m-disabled", "FALSE");
    ModificationItem[] mods = new ModificationItem[] {
            new ModificationItem(DirContext.REMOVE_ATTRIBUTE, disabled),
            new ModificationItem(DirContext.ADD_ATTRIBUTE, disabled2) };

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, getUrl());

    DirContext ctx = new InitialDirContext(env);
    ctx.modifyAttributes("cn=nis,ou=schema", mods);

    return this;
}

From source file:org.springframework.ldap.core.LdapTemplate.java

public void modifyAttributes(final Name dn, final ModificationItem[] mods) {
    executeReadWrite(new ContextExecutor() {
        public Object executeWithContext(DirContext ctx) throws javax.naming.NamingException {
            ctx.modifyAttributes(dn, mods);
            return null;
        }//  ww  w .j  ava2s.c  o  m
    });
}

From source file:org.springframework.ldap.core.LdapTemplate.java

public void modifyAttributes(final String dn, final ModificationItem[] mods) {

    executeReadWrite(new ContextExecutor() {
        public Object executeWithContext(DirContext ctx) throws javax.naming.NamingException {
            ctx.modifyAttributes(dn, mods);
            return null;
        }/*  w w w.  ja v a  2 s  . c  om*/
    });
}

From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java

/**
 *
 *///from  w ww .ja  v a  2  s  .  c o  m
public void doAddUser(String userName, Object credential, String[] roleList, Map<String, String> claims,
        String profileName, boolean requirePasswordChange) throws UserStoreException {

    boolean isUserBinded = false;

    /* getting search base directory context */
    DirContext dirContext = getSearchBaseDirectoryContext();

    /* getting add user basic attributes */
    BasicAttributes basicAttributes = getAddUserBasicAttributes(userName);

    if (!isADLDSRole) {
        // creating a disabled user account in AD DS
        BasicAttribute userAccountControl = new BasicAttribute(
                LDAPConstants.ACTIVE_DIRECTORY_USER_ACCOUNT_CONTROL);
        userAccountControl.add(LDAPConstants.ACTIVE_DIRECTORY_DISABLED_NORMAL_ACCOUNT);
        basicAttributes.put(userAccountControl);
    }

    /* setting claims */
    setUserClaims(claims, basicAttributes, userName);

    Name compoundName = null;
    try {
        NameParser ldapParser = dirContext.getNameParser("");
        compoundName = ldapParser.parse("cn=" + escapeSpecialCharactersForDN(userName));

        /* bind the user. A disabled user account with no password */
        dirContext.bind(compoundName, null, basicAttributes);
        isUserBinded = true;

        /* update the user roles */
        doUpdateRoleListOfUser(userName, null, roleList);

        /* reset the password and enable the account */
        if (!isSSLConnection) {
            logger.warn("Unsecured connection is being used. Enabling user account operation will fail");
        }

        ModificationItem[] mods = new ModificationItem[2];
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE,
                        createUnicodePassword((String) credential)));
        if (isADLDSRole) {
            mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_MSDS_USER_ACCOUNT_DISSABLED, "FALSE"));
        } else {
            mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(
                    LDAPConstants.ACTIVE_DIRECTORY_USER_ACCOUNT_CONTROL, userAccountControl));
        }
        dirContext.modifyAttributes(compoundName, mods);

    } catch (NamingException e) {
        String errorMessage = "Error while adding the user to the Active Directory for user : " + userName;
        if (isUserBinded) {
            try {
                dirContext.unbind(compoundName);
            } catch (NamingException e1) {
                errorMessage = "Error while accessing the Active Directory for user : " + userName;
                throw new UserStoreException(errorMessage, e);
            }
            errorMessage = "Error while enabling the user account. Please check password policy at DC for user : "
                    + userName;
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeContext(dirContext);
    }
}

From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java

/**
 *
 *///from   w  w w  . jav a 2 s .c  om
public void doUpdateCredential(String userName, Object newCredential, Object oldCredential)
        throws UserStoreException {

    if (!isSSLConnection) {
        logger.warn("Unsecured connection is being used. Password operations will fail");
    }

    DirContext dirContext = this.connectionSource.getContext();
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userListFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER);
    String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
    // String searchFilter =
    // realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    String searchFilter = "(&" + userListFilter + "(" + userNameAttribute + "="
            + escapeSpecialCharactersForFilter(userName) + "))";

    SearchControls searchControl = new SearchControls();
    String[] returningAttributes = { "CN" };
    searchControl.setReturningAttributes(returningAttributes);
    searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    DirContext subDirContext = null;
    NamingEnumeration<SearchResult> searchResults = null;
    try {
        // search the user with UserNameAttribute and obtain its CN attribute
        searchResults = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControl);
        SearchResult user = null;
        int count = 0;
        while (searchResults.hasMore()) {
            if (count > 0) {
                throw new UserStoreException(
                        "There are more than one result in the user store " + "for user: " + userName);
            }
            user = searchResults.next();
            count++;
        }
        String userCNValue = null;
        if (user.getAttributes() != null) {
            Attribute cnAttribute = user.getAttributes().get("CN");
            if (cnAttribute != null) {
                userCNValue = (String) cnAttribute.get();
            } else {
                throw new UserStoreException("Can not update credential: CN attribute is null");
            }
        }

        ModificationItem[] mods = null;

        // The user tries to change his own password
        if (oldCredential != null && newCredential != null) {
            mods = new ModificationItem[1];
            /*
            * byte[] oldUnicodePassword = createUnicodePassword((String) oldCredential); byte[]
            * newUnicodePassword = createUnicodePassword((String) newCredential);
            */
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE,
                            createUnicodePassword((String) newCredential)));
            /*
             * mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute(
             * LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE, newUnicodePassword));
             */
        }
        subDirContext = (DirContext) dirContext.lookup(searchBase);
        subDirContext.modifyAttributes("CN" + "=" + escapeSpecialCharactersForDN(userCNValue), mods);

    } catch (NamingException e) {
        String error = "Can not access the directory service for user : " + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(error, e);
        }
        throw new UserStoreException(error, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(searchResults);
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }

}

From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java

@Override
public void doUpdateCredentialByAdmin(String userName, Object newCredential) throws UserStoreException {

    if (!isSSLConnection) {
        logger.warn("Unsecured connection is being used. Password operations will fail");
    }/* w  w w .ja v  a  2s.com*/

    DirContext dirContext = this.connectionSource.getContext();
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userListFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER);
    String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
    String searchFilter = "(&" + userListFilter + "(" + userNameAttribute + "="
            + escapeSpecialCharactersForFilter(userName) + "))";
    SearchControls searchControl = new SearchControls();
    String[] returningAttributes = { "CN" };
    searchControl.setReturningAttributes(returningAttributes);
    searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE);

    DirContext subDirContext = null;
    NamingEnumeration<SearchResult> searchResults = null;
    try {
        // search the user with UserNameAttribute and obtain its CN attribute
        searchResults = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControl);
        SearchResult user = null;
        int count = 0;
        while (searchResults.hasMore()) {
            if (count > 0) {
                throw new UserStoreException(
                        "There are more than one result in the user store " + "for user: " + userName);
            }
            user = searchResults.next();
            count++;
        }
        String userCNValue = null;
        if (user.getAttributes() != null) {
            Attribute cnAttribute = user.getAttributes().get("CN");
            if (cnAttribute != null) {
                userCNValue = (String) cnAttribute.get();
            } else {
                throw new UserStoreException("Can not update credential: CN attribute is null");
            }
        }

        ModificationItem[] mods = null;

        if (newCredential != null) {
            mods = new ModificationItem[1];
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE,
                            createUnicodePassword((String) newCredential)));

            subDirContext = (DirContext) dirContext.lookup(searchBase);
            subDirContext.modifyAttributes("CN" + "=" + escapeSpecialCharactersForDN(userCNValue), mods);
        }

    } catch (NamingException e) {
        String error = "Can not access the directory service for user : " + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(error, e);
        }
        throw new UserStoreException(error, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(searchResults);
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}