Example usage for javax.naming.directory Attribute add

List of usage examples for javax.naming.directory Attribute add

Introduction

In this page you can find the example usage for javax.naming.directory Attribute add.

Prototype

boolean add(Object attrVal);

Source Link

Document

Adds a new value to the attribute.

Usage

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * Either delete or add user from/to group.
 *
 * @param userNameDN : distinguish name of user entry.
 * @param groupRDN   : relative distinguish name of group entry
 * @param modifyType : modify attribute type in DirCOntext.
 * @throws UserStoreException If an error occurs while updating.
 *///  w  ww.j  a va2 s  .  co m
protected void modifyUserInRole(String userNameDN, String groupRDN, int modifyType, String searchBase)
        throws UserStoreException {

    if (log.isDebugEnabled()) {
        log.debug("Modifying role: " + groupRDN + " with type: " + modifyType + " user: " + userNameDN
                + " in search base: " + searchBase);
    }

    DirContext mainDirContext = null;
    DirContext groupContext = null;
    try {
        mainDirContext = this.connectionSource.getContext();
        groupContext = (DirContext) mainDirContext.lookup(searchBase);
        String memberAttributeName = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
        Attributes modifyingAttributes = new BasicAttributes(true);
        Attribute memberAttribute = new BasicAttribute(memberAttributeName);
        memberAttribute.add(userNameDN);
        modifyingAttributes.put(memberAttribute);

        groupContext.modifyAttributes(groupRDN, modifyType, modifyingAttributes);
        if (log.isDebugEnabled()) {
            log.debug("User: " + userNameDN + " was successfully " + "modified in LDAP group: " + groupRDN);
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while modifying user entry: " + userNameDN + " in LDAP role: "
                + groupRDN;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage);
    } finally {
        JNDIUtil.closeContext(groupContext);
        JNDIUtil.closeContext(mainDirContext);
    }
}

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

/**
 * This method overwrites the method in LDAPUserStoreManager. This implements the functionality
 * of updating user's profile information in LDAP user store.
 *
 * @param userName/*from   w w  w  .jav a2 s. c  o m*/
 * @param claims
 * @param profileName
 * @throws org.wso2.carbon.user.core.UserStoreException
 */
@Override
public void doSetUserClaimValues(String userName, Map<String, String> claims, String profileName)
        throws UserStoreException {
    // get the LDAP Directory context
    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // search the relevant user entry by user name
    String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    // if user name contains domain name, remove domain name
    String[] userNames = userName.split(CarbonConstants.DOMAIN_SEPARATOR);
    if (userNames.length > 1) {
        userName = userNames[1];
    }
    userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(null);

    NamingEnumeration<SearchResult> returnedResultList = null;
    String returnedUserEntry = null;

    boolean cnModified = false;
    String cnValue = null;

    try {

        returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter,
                searchControls);
        // assume only one user is returned from the search
        // TODO:what if more than one user is returned
        returnedUserEntry = returnedResultList.next().getName();

    } catch (NamingException e) {
        String errorMessage = "Results could not be retrieved from the directory context for user : "
                + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(returnedResultList);
    }

    if (profileName == null) {
        profileName = UserCoreConstants.DEFAULT_PROFILE;
    }

    if (claims.get(UserCoreConstants.PROFILE_CONFIGURATION) == null) {
        claims.put(UserCoreConstants.PROFILE_CONFIGURATION, UserCoreConstants.DEFAULT_PROFILE_CONFIGURATION);
    }

    try {
        Attributes updatedAttributes = new BasicAttributes(true);

        String domainName = userName.indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > -1
                ? userName.split(UserCoreConstants.DOMAIN_SEPARATOR)[0]
                : realmConfig.getUserStoreProperty(UserStoreConfigConstants.DOMAIN_NAME);
        for (Map.Entry<String, String> claimEntry : claims.entrySet()) {
            String claimURI = claimEntry.getKey();
            // if there is no attribute for profile configuration in LDAP,
            // skip updating it.
            if (claimURI.equals(UserCoreConstants.PROFILE_CONFIGURATION)) {
                continue;
            }
            // get the claimMapping related to this claimURI
            String attributeName = getClaimAtrribute(claimURI, userName, null);
            //remove user DN from cache if changing username attribute
            if (realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE).equals(attributeName)) {
                userCache.remove(userName);
            }
            // if mapped attribute is CN, then skip treating as a modified
            // attribute -
            // it should be an object rename
            if ("CN".toLowerCase().equals(attributeName.toLowerCase())) {
                cnModified = true;
                cnValue = claimEntry.getValue();
                continue;
            }
            Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);
            /* if updated attribute value is null, remove its values. */
            if (EMPTY_ATTRIBUTE_STRING.equals(claimEntry.getValue())) {
                currentUpdatedAttribute.clear();
            } else {
                if (claimEntry.getValue() != null) {
                    String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR);
                    if (claimSeparator != null && !claimSeparator.trim().isEmpty()) {
                        userAttributeSeparator = claimSeparator;
                    }
                    if (claimEntry.getValue().contains(userAttributeSeparator)) {
                        StringTokenizer st = new StringTokenizer(claimEntry.getValue(), userAttributeSeparator);
                        while (st.hasMoreElements()) {
                            String newVal = st.nextElement().toString();
                            if (newVal != null && newVal.trim().length() > 0) {
                                currentUpdatedAttribute.add(newVal.trim());
                            }
                        }
                    } else {
                        currentUpdatedAttribute.add(claimEntry.getValue());
                    }
                } else {
                    currentUpdatedAttribute.add(claimEntry.getValue());
                }
            }
            updatedAttributes.put(currentUpdatedAttribute);
        }
        // update the attributes in the relevant entry of the directory
        // store

        subDirContext = (DirContext) dirContext.lookup(userSearchBase);
        subDirContext.modifyAttributes(returnedUserEntry, DirContext.REPLACE_ATTRIBUTE, updatedAttributes);

        if (cnModified && cnValue != null) {
            subDirContext.rename(returnedUserEntry, "CN=" + escapeSpecialCharactersForDN(cnValue));
        }

    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        String errorMessage = "Error in obtaining claim mapping for user : " + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } catch (NamingException e) {
        handleException(e, userName);
    } finally {
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }

}

From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java

/**
 * Remove existing statically defined links for the given source id (dynamic references remain unaltered)
 *
 * @see org.nuxeo.ecm.directory.Reference#removeLinksForSource(String)
 *///from w ww .  j a va2  s  .co  m
@Override
public void removeLinksForSource(String sourceId) throws DirectoryException {
    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();
    String attributeId = getStaticAttributeId();
    try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession();
            LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) {
        if (sourceSession.isReadOnly() || attributeId == null) {
            // do not try to do anything on a read only server or to a
            // purely dynamic reference
            return;
        }
        // get the dn of the entry that matches sourceId
        SearchResult sourceLdapEntry = sourceSession.getLdapEntry(sourceId);
        if (sourceLdapEntry == null) {
            throw new DirectoryException(
                    String.format("cannot edit the links hold by missing entry '%s' in directory '%s'",
                            sourceId, ldapSourceDirectory.getName()));
        }
        String sourceDn = pseudoNormalizeDn(sourceLdapEntry.getNameInNamespace());

        Attribute oldAttr = sourceLdapEntry.getAttributes().get(attributeId);
        if (oldAttr == null) {
            // consider it as an empty attribute to simplify the following
            // code
            oldAttr = new BasicAttribute(attributeId);
        }
        Attribute attrToRemove = new BasicAttribute(attributeId);

        NamingEnumeration<?> oldAttrs = oldAttr.getAll();
        String targetBaseDn = pseudoNormalizeDn(ldapTargetDirectory.getDescriptor().getSearchBaseDn());
        try {
            while (oldAttrs.hasMore()) {
                String targetKeyAttr = oldAttrs.next().toString();

                if (staticAttributeIdIsDn) {
                    String dn = pseudoNormalizeDn(targetKeyAttr);
                    if (forceDnConsistencyCheck) {
                        String id = getIdForDn(targetSession, dn);
                        if (id != null && targetSession.hasEntry(id)) {
                            // this is an entry managed by the current
                            // reference
                            attrToRemove.add(dn);
                        }
                    } else if (dn.endsWith(targetBaseDn)) {
                        // this is an entry managed by the current
                        // reference
                        attrToRemove.add(dn);
                    }
                } else {
                    attrToRemove.add(targetKeyAttr);
                }
            }
        } finally {
            oldAttrs.close();
        }
        try {
            if (attrToRemove.size() == oldAttr.size()) {
                // use the empty ref marker to avoid empty attr
                String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
                Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker);
                if (log.isDebugEnabled()) {
                    log.debug(String.format(
                            "LDAPReference.removeLinksForSource(%s): LDAP modifyAttributes key='%s' "
                                    + " mod_op='REPLACE_ATTRIBUTE' attrs='%s' [%s]",
                            sourceId, sourceDn, emptyAttribute, this));
                }
                sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REPLACE_ATTRIBUTE,
                        emptyAttribute);
            } else if (attrToRemove.size() > 0) {
                // remove the attribute managed by the current reference
                Attributes attrsToRemove = new BasicAttributes();
                attrsToRemove.put(attrToRemove);
                if (log.isDebugEnabled()) {
                    log.debug(String.format(
                            "LDAPReference.removeLinksForSource(%s): LDAP modifyAttributes dn='%s' "
                                    + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                            sourceId, sourceDn, attrsToRemove, this));
                }
                sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE, attrsToRemove);
            }
        } catch (SchemaViolationException e) {
            if (isDynamic()) {
                // we are editing an entry that has no static part
                log.warn(String.format("cannot remove dynamic reference in field %s for source %s",
                        getFieldName(), sourceId));
            } else {
                // this is a real schma configuration problem, wrapup the
                // exception
                throw new DirectoryException(e);
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("removeLinksForSource failed: " + e.getMessage(), e);
    }
}

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

/**
 * Either delete or add user from/to group.
 *
 * @param userNameDN : distinguish name of user entry.
 * @param groupRDN   : relative distinguish name of group entry
 * @param modifyType : modify attribute type in DirCOntext.
 * @throws UserStoreException//from w ww .j a v  a  2 s . co m
 */
protected void modifyUserInRole(String userNameDN, String groupRDN, int modifyType, String searchBase)
        throws UserStoreException {

    if (log.isDebugEnabled()) {
        logger.debug("Modifying role: " + groupRDN + " with type: " + modifyType + " user: " + userNameDN
                + " in search base: " + searchBase);
    }

    DirContext mainDirContext = null;
    DirContext groupContext = null;
    try {
        mainDirContext = this.connectionSource.getContext();
        groupContext = (DirContext) mainDirContext.lookup(searchBase);
        String memberAttributeName = realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
        Attributes modifyingAttributes = new BasicAttributes(true);
        Attribute memberAttribute = new BasicAttribute(memberAttributeName);
        memberAttribute.add(userNameDN);
        modifyingAttributes.put(memberAttribute);

        groupContext.modifyAttributes(groupRDN, modifyType, modifyingAttributes);
        if (log.isDebugEnabled()) {
            logger.debug("User: " + userNameDN + " was successfully " + "modified in LDAP group: " + groupRDN);
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while modifying user entry: " + userNameDN + " in LDAP role: "
                + groupRDN;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage);
    } finally {
        JNDIUtil.closeContext(groupContext);
        JNDIUtil.closeContext(mainDirContext);
    }
}

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

@SuppressWarnings("rawtypes")
@Override//  ww  w.  j a  va 2 s  . c  om
public void doUpdateCredential(String userName, Object newCredential, Object oldCredential)
        throws UserStoreException {

    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // first search the existing user entry.
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { "userPassword" });

    NamingEnumeration<SearchResult> namingEnumeration = null;
    NamingEnumeration passwords = null;

    try {
        namingEnumeration = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControls);
        // here we assume only one user
        // TODO: what to do if there are more than one user
        SearchResult searchResult = null;
        String passwordHashMethod = realmConfig.getUserStoreProperty(PASSWORD_HASH_METHOD);
        while (namingEnumeration.hasMore()) {
            searchResult = namingEnumeration.next();

            String dnName = searchResult.getName();
            subDirContext = (DirContext) dirContext.lookup(searchBase);

            Attribute passwordAttribute = new BasicAttribute("userPassword");
            passwordAttribute.add(
                    UserCoreUtil.getPasswordToStore((String) newCredential, passwordHashMethod, kdcEnabled));
            BasicAttributes basicAttributes = new BasicAttributes(true);
            basicAttributes.put(passwordAttribute);
            subDirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes);
        }
        // we check whether both carbon admin entry and ldap connection
        // entry are the same
        if (searchResult.getNameInNamespace()
                .equals(realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME))) {
            this.connectionSource.updateCredential((String) newCredential);
        }

    } catch (NamingException e) {
        String errorMessage = "Can not access the directory service for user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(passwords);
        JNDIUtil.closeNamingEnumeration(namingEnumeration);

        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}

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

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

    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // first search the existing user entry.
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { "userPassword" });

    NamingEnumeration<SearchResult> namingEnumeration = null;
    NamingEnumeration passwords = null;

    try {/*from w  w w . j a  v  a 2s.  c o  m*/
        namingEnumeration = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControls);
        // here we assume only one user
        // TODO: what to do if there are more than one user
        // there can be only only on user

        SearchResult searchResult = null;
        while (namingEnumeration.hasMore()) {
            searchResult = namingEnumeration.next();
            String passwordHashMethod = realmConfig.getUserStoreProperty(PASSWORD_HASH_METHOD);
            if (!UserCoreConstants.RealmConfig.PASSWORD_HASH_METHOD_PLAIN_TEXT
                    .equalsIgnoreCase(passwordHashMethod)) {
                Attributes attributes = searchResult.getAttributes();
                Attribute userPassword = attributes.get("userPassword");
                // When admin changes other user passwords he do not have to
                // provide the old password. Here it is only possible to have one password, if there
                // are more every one should match with the given old password
                passwords = userPassword.getAll();
                if (passwords.hasMore()) {
                    byte[] byteArray = (byte[]) passwords.next();
                    String password = new String(byteArray);

                    if (password.startsWith("{")) {
                        passwordHashMethod = password.substring(password.indexOf('{') + 1,
                                password.indexOf('}'));
                    }
                }
            }

            String dnName = searchResult.getName();
            subDirContext = (DirContext) dirContext.lookup(searchBase);

            Attribute passwordAttribute = new BasicAttribute("userPassword");
            passwordAttribute.add(
                    UserCoreUtil.getPasswordToStore((String) newCredential, passwordHashMethod, kdcEnabled));
            BasicAttributes basicAttributes = new BasicAttributes(true);
            basicAttributes.put(passwordAttribute);
            subDirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes);
        }
        // we check whether both carbon admin entry and ldap connection
        // entry are the same
        if (searchResult.getNameInNamespace()
                .equals(realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME))) {
            this.connectionSource.updateCredential((String) newCredential);
        }

    } catch (NamingException e) {
        String errorMessage = "Can not access the directory service for user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(passwords);
        JNDIUtil.closeNamingEnumeration(namingEnumeration);

        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}

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

protected void addLDAPRole(RoleContext context) throws UserStoreException {

    String roleName = context.getRoleName();
    String[] userList = context.getMembers();
    String groupEntryObjectClass = ((LDAPRoleContext) context).getGroupEntryObjectClass();
    String groupNameAttribute = ((LDAPRoleContext) context).getRoleNameProperty();
    String searchBase = ((LDAPRoleContext) context).getSearchBase();

    if ((userList == null || userList.length == 0) && !emptyRolesAllowed) {
        String errorMessage = "Can not create empty role. There should be at least " + "one user for the role.";
        throw new UserStoreException(errorMessage);
    } else if (userList == null && emptyRolesAllowed
            || userList != null && userList.length > 0 && !emptyRolesAllowed || emptyRolesAllowed) {

        // if (userList.length > 0) {
        DirContext mainDirContext = this.connectionSource.getContext();
        DirContext groupContext = null;
        NamingEnumeration<SearchResult> results = null;

        try {//  w w  w  .  j a  v  a  2 s.  c  om
            // create the attribute set for group entry
            Attributes groupAttributes = new BasicAttributes(true);

            // create group entry's object class attribute
            Attribute objectClassAttribute = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
            objectClassAttribute.add(groupEntryObjectClass);
            groupAttributes.put(objectClassAttribute);

            // create cn attribute
            Attribute cnAttribute = new BasicAttribute(groupNameAttribute);
            cnAttribute.add(roleName);
            groupAttributes.put(cnAttribute);
            // following check is for if emptyRolesAllowed made this
            // code executed.
            if (userList != null && userList.length > 0) {

                String memberAttributeName = realmConfig
                        .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
                Attribute memberAttribute = new BasicAttribute(memberAttributeName);
                for (String userName : userList) {

                    if (userName == null || userName.trim().length() == 0) {
                        continue;
                    }
                    // search the user in user search base
                    String searchFilter = realmConfig
                            .getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
                    searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName));
                    results = searchInUserBase(searchFilter, new String[] {}, SearchControls.SUBTREE_SCOPE,
                            mainDirContext);
                    // we assume only one user with the given user
                    // name under user search base.
                    SearchResult userResult = null;
                    if (results.hasMore()) {
                        userResult = results.next();
                    } else {
                        String errorMsg = "There is no user with the user name: " + userName
                                + " to be added to this role.";
                        logger.error(errorMsg);
                        throw new UserStoreException(errorMsg);
                    }
                    // get his DN
                    String userEntryDN = userResult.getNameInNamespace();
                    // put it as member-attribute value
                    memberAttribute.add(userEntryDN);
                }
                groupAttributes.put(memberAttribute);
            }

            groupContext = (DirContext) mainDirContext.lookup(searchBase);
            NameParser ldapParser = groupContext.getNameParser("");
            /*
             * Name compoundGroupName = ldapParser.parse(groupNameAttributeName + "=" +
             * roleName);
             */
            Name compoundGroupName = ldapParser.parse("cn=" + roleName);
            groupContext.bind(compoundGroupName, null, groupAttributes);

        } catch (NamingException e) {
            String errorMsg = "Role: " + roleName + " could not be added.";
            if (log.isDebugEnabled()) {
                log.debug(errorMsg, e);
            }
            throw new UserStoreException(errorMsg, e);
        } catch (Exception e) {
            String errorMsg = "Role: " + roleName + " could not be added.";
            if (log.isDebugEnabled()) {
                log.debug(errorMsg, e);
            }
            throw new UserStoreException(errorMsg, e);
        } finally {
            JNDIUtil.closeNamingEnumeration(results);
            JNDIUtil.closeContext(groupContext);
            JNDIUtil.closeContext(mainDirContext);
        }

    }

}

From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java

/**
 * Store new links using the LDAP staticAttributeId strategy.
 *
 * @see org.nuxeo.ecm.directory.Reference#addLinks(String, List)
 *//*from   ww  w  .ja v  a2s .c  om*/
@Override
public void addLinks(String sourceId, List<String> targetIds) throws DirectoryException {

    if (targetIds.isEmpty()) {
        // optim: nothing to do, return silently without further creating
        // session instances
        return;
    }

    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();
    String attributeId = getStaticAttributeId();
    if (attributeId == null) {
        if (log.isTraceEnabled()) {
            log.trace(String.format("trying to edit a non-static reference from %s in directory %s: ignoring",
                    sourceId, ldapSourceDirectory.getName()));
        }
        return;
    }
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();
            LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
        // fetch the entry to be able to run the security policy
        // implemented in an entry adaptor
        DocumentModel sourceEntry = sourceSession.getEntry(sourceId, false);
        if (sourceEntry == null) {
            throw new DirectoryException(String.format("could not add links from unexisting %s in directory %s",
                    sourceId, ldapSourceDirectory.getName()));
        }
        if (!BaseSession.isReadOnlyEntry(sourceEntry)) {
            SearchResult ldapEntry = sourceSession.getLdapEntry(sourceId);

            String sourceDn = ldapEntry.getNameInNamespace();
            Attribute storedAttr = ldapEntry.getAttributes().get(attributeId);
            String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
            Attribute attrToAdd = new BasicAttribute(attributeId);
            for (String targetId : targetIds) {
                if (staticAttributeIdIsDn) {
                    // TODO optim: avoid LDAP search request when targetDn
                    // can be forged client side (rdnAttribute = idAttribute and scope is onelevel)
                    ldapEntry = targetSession.getLdapEntry(targetId);
                    if (ldapEntry == null) {
                        log.warn(String.format(
                                "entry '%s' in directory '%s' not found: could not add link from '%s' in directory '%s' for '%s'",
                                targetId, ldapTargetDirectory.getName(), sourceId,
                                ldapSourceDirectory.getName(), this));
                        continue;
                    }
                    String dn = ldapEntry.getNameInNamespace();
                    if (storedAttr == null || !storedAttr.contains(dn)) {
                        attrToAdd.add(dn);
                    }
                } else {
                    if (storedAttr == null || !storedAttr.contains(targetId)) {
                        attrToAdd.add(targetId);
                    }
                }
            }
            if (attrToAdd.size() > 0) {
                try {
                    // do the LDAP request to store missing dns
                    Attributes attrsToAdd = new BasicAttributes();
                    attrsToAdd.put(attrToAdd);

                    if (log.isDebugEnabled()) {
                        log.debug(String.format(
                                "LDAPReference.addLinks(%s, [%s]): LDAP modifyAttributes dn='%s' "
                                        + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]",
                                sourceId, StringUtils.join(targetIds, ", "), sourceDn, attrsToAdd, this));
                    }
                    sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.ADD_ATTRIBUTE, attrsToAdd);

                    // robustly clean any existing empty marker now that we are sure that the list in not empty
                    if (storedAttr.contains(emptyRefMarker)) {
                        Attributes cleanAttrs = new BasicAttributes(attributeId, emptyRefMarker);

                        if (log.isDebugEnabled()) {
                            log.debug(String.format(
                                    "LDAPReference.addLinks(%s, [%s]): LDAP modifyAttributes dn='%s'"
                                            + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                                    sourceId, StringUtils.join(targetIds, ", "), sourceDn, cleanAttrs, this));
                        }
                        sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE,
                                cleanAttrs);
                    }
                } catch (SchemaViolationException e) {
                    if (isDynamic()) {
                        // we are editing an entry that has no static part
                        log.warn(String.format("cannot update dynamic reference in field %s for source %s",
                                getFieldName(), sourceId));
                    } else {
                        // this is a real schema configuration problem,
                        // wrap up the exception
                        throw new DirectoryException(e);
                    }
                }
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("addLinks failed: " + e.getMessage(), e);
    }
}

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

@Override
public void doSetUserClaimValue(String userName, String claimURI, String value, String profileName)
        throws UserStoreException {

    // get the LDAP Directory context
    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // search the relevant user entry by user name
    String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    // if user name contains domain name, remove domain name
    String[] userNames = userName.split(CarbonConstants.DOMAIN_SEPARATOR);
    if (userNames.length > 1) {
        userName = userNames[1];//ww w .j  av a 2 s  .  c o m
    }
    userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(null);

    NamingEnumeration<SearchResult> returnedResultList = null;
    String returnedUserEntry = null;

    try {

        returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter,
                searchControls);
        // assume only one user is returned from the search
        // TODO:what if more than one user is returned
        if (returnedResultList.hasMore()) {
            returnedUserEntry = returnedResultList.next().getName();
        }

    } catch (NamingException e) {
        String errorMessage = "Results could not be retrieved from the directory context for user : "
                + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(returnedResultList);
    }

    try {
        Attributes updatedAttributes = new BasicAttributes(true);
        // if there is no attribute for profile configuration in LDAP, skip
        // updating it.
        // get the claimMapping related to this claimURI
        String attributeName = null;
        attributeName = getClaimAtrribute(claimURI, userName, null);

        Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);
        /* if updated attribute value is null, remove its values. */
        if (EMPTY_ATTRIBUTE_STRING.equals(value)) {
            currentUpdatedAttribute.clear();
        } else {
            if (attributeName.equals("uid") || attributeName.equals("sn")) {
                currentUpdatedAttribute.add(value);
            } else {
                String userAttributeSeparator = ",";
                String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR);
                if (claimSeparator != null && !claimSeparator.trim().isEmpty()) {
                    userAttributeSeparator = claimSeparator;
                }

                if (value.contains(userAttributeSeparator)) {
                    StringTokenizer st = new StringTokenizer(value, userAttributeSeparator);
                    while (st.hasMoreElements()) {
                        String newVal = st.nextElement().toString();
                        if (newVal != null && newVal.trim().length() > 0) {
                            currentUpdatedAttribute.add(newVal.trim());
                        }
                    }
                } else {
                    currentUpdatedAttribute.add(value);
                }

            }
        }
        updatedAttributes.put(currentUpdatedAttribute);

        // update the attributes in the relevant entry of the directory
        // store

        subDirContext = (DirContext) dirContext.lookup(userSearchBase);
        subDirContext.modifyAttributes(returnedUserEntry, DirContext.REPLACE_ATTRIBUTE, updatedAttributes);

    } catch (Exception e) {
        handleException(e, userName);
    } finally {
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }

}

From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java

/**
 * Remove existing statically defined links for the given target id (dynamic references remain unaltered)
 *
 * @see org.nuxeo.ecm.directory.Reference#removeLinksForTarget(String)
 *//*from  w w  w.ja va2  s .  c o  m*/
@Override
public void removeLinksForTarget(String targetId) throws DirectoryException {
    if (!isStatic()) {
        // nothing to do: dynamic references cannot be updated
        return;
    }
    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();
    String attributeId = getStaticAttributeId();
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();
            LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
        if (!sourceSession.isReadOnly()) {
            // get the dn of the target that matches targetId
            String targetAttributeValue;

            if (staticAttributeIdIsDn) {
                SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId);
                if (targetLdapEntry == null) {
                    String rdnAttribute = ldapTargetDirectory.getDescriptor().getRdnAttribute();
                    if (!rdnAttribute.equals(targetSession.idAttribute)) {
                        log.warn(String.format(
                                "cannot remove links to missing entry %s in directory %s for reference %s",
                                targetId, ldapTargetDirectory.getName(), this));
                        return;
                    }
                    // the entry might have already been deleted, try to
                    // re-forge it if possible (might not work if scope is
                    // subtree)
                    targetAttributeValue = String.format("%s=%s,%s", rdnAttribute, targetId,
                            ldapTargetDirectory.getDescriptor().getSearchBaseDn());
                } else {
                    targetAttributeValue = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace());
                }
            } else {
                targetAttributeValue = targetId;
            }

            // build a LDAP query to find entries that point to the target
            String searchFilter = String.format("(%s=%s)", attributeId, targetAttributeValue);
            String sourceFilter = ldapSourceDirectory.getBaseFilter();

            if (sourceFilter != null && !"".equals(sourceFilter)) {
                searchFilter = String.format("(&(%s)(%s))", searchFilter, sourceFilter);
            }

            SearchControls scts = new SearchControls();
            scts.setSearchScope(ldapSourceDirectory.getDescriptor().getSearchScope());
            scts.setReturningAttributes(new String[] { attributeId });

            // find all source entries that point to the target key and
            // clean
            // those references
            if (log.isDebugEnabled()) {
                log.debug(String.format(
                        "LDAPReference.removeLinksForTarget(%s): LDAP search baseDn='%s' "
                                + " filter='%s' scope='%s' [%s]",
                        targetId, sourceSession.searchBaseDn, searchFilter, scts.getSearchScope(), this));
            }
            NamingEnumeration<SearchResult> results = sourceSession.dirContext
                    .search(sourceSession.searchBaseDn, searchFilter, scts);
            String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
            Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker);

            try {
                while (results.hasMore()) {
                    SearchResult result = results.next();
                    Attributes attrs = result.getAttributes();
                    Attribute attr = attrs.get(attributeId);
                    try {
                        if (attr.size() == 1) {
                            // the attribute holds the last reference, put
                            // the
                            // empty ref. marker before removing the
                            // attribute
                            // since empty attribute are often not allowed
                            // by
                            // the server schema
                            if (log.isDebugEnabled()) {
                                log.debug(String.format(
                                        "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' "
                                                + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]",
                                        targetId, result.getNameInNamespace(), attrs, this));
                            }
                            sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(),
                                    DirContext.ADD_ATTRIBUTE, emptyAttribute);
                        }
                        // remove the reference to the target key
                        attrs = new BasicAttributes();
                        attr = new BasicAttribute(attributeId);
                        attr.add(targetAttributeValue);
                        attrs.put(attr);
                        if (log.isDebugEnabled()) {
                            log.debug(String.format(
                                    "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' "
                                            + "mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                                    targetId, result.getNameInNamespace(), attrs, this));
                        }
                        sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(),
                                DirContext.REMOVE_ATTRIBUTE, attrs);
                    } catch (SchemaViolationException e) {
                        if (isDynamic()) {
                            // we are editing an entry that has no static
                            // part
                            log.warn(String.format("cannot remove dynamic reference in field %s for target %s",
                                    getFieldName(), targetId));
                        } else {
                            // this is a real schema configuration problem,
                            // wrapup the exception
                            throw new DirectoryException(e);
                        }
                    }
                }
            } finally {
                results.close();
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("removeLinksForTarget failed: " + e.getMessage(), e);
    }
}