Example usage for javax.naming.directory Attributes get

List of usage examples for javax.naming.directory Attributes get

Introduction

In this page you can find the example usage for javax.naming.directory Attributes get.

Prototype

Attribute get(String attrID);

Source Link

Document

Retrieves the attribute with the given attribute id from the attribute set.

Usage

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

/**
 *
 * {@inheritDoc}//from   ww w  .j  av a  2  s . c o  m
 */
@Override
public String resolveDistinguishedName(final String userId, final AuthenticationDiagnostic diagnostic)
        throws AuthenticationException {
    LOGGER.debug("resolveDistinguishedName userId: {}", userId);

    final SearchControls userSearchCtls = new SearchControls();
    userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868
    userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName });

    final String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName
            + "= userId))";

    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;

    InitialDirContext ctx = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic);

        // Execute the user query with an additional condition that ensures only the user with the required ID is
        // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation

        searchResults = ctx.search(this.userSearchBase,
                "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId },
                userSearchCtls);

        if (searchResults.hasMore()) {
            result = searchResults.next();
            final Attributes attributes = result.getAttributes();
            final Attribute uidAttribute = attributes.get(this.userIdAttributeName);
            if (uidAttribute == null) {
                if (this.errorOnMissingUID) {
                    throw new AlfrescoRuntimeException(
                            "User returned by user search does not have mandatory user id attribute "
                                    + attributes);
                } else {
                    LOGGER.warn("User returned by user search does not have mandatory user id attribute {}",
                            attributes);
                }
            }
            // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will
            // only resolve this user if the user ID matches
            else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) {
                final String name = result.getNameInNamespace();

                this.commonCloseSearchResult(result);
                result = null;
                return name;
            }

            this.commonCloseSearchResult(result);
            result = null;
        }

        final Object[] args = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args);

        throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic);
    } catch (final NamingException e) {
        // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory
        final Object[] args1 = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1);

        // failed to search
        final Object[] args = { e.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e);
    } finally {
        this.commonAfterQueryCleanup(searchResults, result, ctx);
    }
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

protected UidNodeDescription mapToNode(final SearchResult searchResult, final String idAttributeName,
        final Map<String, String> attributeMapping, final Map<String, String> attributeDefaults)
        throws NamingException {
    final Attributes attributes = searchResult.getAttributes();
    final Collection<String> uidValues = this.mapAttribute(attributes.get(idAttributeName), String.class);
    final String uid = uidValues.iterator().next();

    final UidNodeDescription nodeDescription = new UidNodeDescription(searchResult.getNameInNamespace(), uid);

    final Attribute modifyTimestamp = attributes.get(this.modifyTimestampAttributeName);
    if (modifyTimestamp != null) {
        try {/*from  w  w w  . j a  v a2  s  . c o m*/
            nodeDescription.setLastModified(this.timestampFormat.parse(modifyTimestamp.get().toString()));
            LOGGER.debug("Setting last modified of node {} to {}", uid, nodeDescription.getLastModified());
        } catch (final ParseException e) {
            throw new AlfrescoRuntimeException("Failed to parse timestamp.", e);
        }
    }

    final PropertyMap properties = nodeDescription.getProperties();
    for (final String key : attributeMapping.keySet()) {
        final QName keyQName = QName.createQName(key, this.namespaceService);

        final String attributeName = attributeMapping.get(key);
        if (attributeName != null) {
            final Attribute attribute = attributes.get(attributeName);
            final String defaultAttribute = attributeDefaults.get(key);

            if (attribute != null) {
                final Collection<Object> mappedAttributeValue = this.mapAttribute(attribute);
                if (mappedAttributeValue.size() == 1) {
                    final Object singleValue = mappedAttributeValue.iterator().next();
                    if (singleValue instanceof Serializable) {
                        properties.put(keyQName, (Serializable) singleValue);
                    } else {
                        properties.put(keyQName,
                                DefaultTypeConverter.INSTANCE.convert(String.class, singleValue));
                    }
                } else if (!mappedAttributeValue.isEmpty()) {
                    final ArrayList<Serializable> values = new ArrayList<>();
                    mappedAttributeValue.forEach((x) -> {
                        if (x instanceof Serializable) {
                            values.add((Serializable) x);
                        } else {
                            values.add(DefaultTypeConverter.INSTANCE.convert(String.class, x));
                        }
                    });
                    properties.put(keyQName, values);
                } else if (defaultAttribute != null) {
                    properties.put(keyQName, defaultAttribute);
                } else {
                    // Make sure that a 2nd sync, updates deleted ldap attributes (MNT-14026)
                    properties.put(keyQName, null);
                }
            } else if (defaultAttribute != null) {
                LOGGER.debug("Node {} does not provide attriute {} - using default value", uid, attributeName);
                properties.put(keyQName, defaultAttribute);
            } else {
                LOGGER.debug("Node {} does not provide attriute {} - setting to null", uid, attributeName);
                // Make sure that a 2nd sync, updates deleted ldap attributes (MNT-14026)
                properties.put(keyQName, null);
            }
        } else {
            LOGGER.debug("No attribute name has been configured for property {}", keyQName);
            final String defaultValue = attributeDefaults.get(key);
            if (defaultValue != null) {
                LOGGER.debug("Using default value for {} on node {}", keyQName, uid);
                properties.put(keyQName, defaultValue);
            }
        }
    }

    return nodeDescription;
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Fetches the supplied user DN.//w  w w  .  ja v  a  2  s  . co  m
 *
 * @param uid the user id
 * @return the user DN for the supplied uid
 * @throws NamingException LDAP error obtaining user information.
 * @throws IOException 
 */
protected String selectUserDN(String uid) throws NamingException, IOException {

    String dn = null;

    InitialLdapContext ctx = createLdapInitialContext(false);

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    String principalUidAttrName = this.getPrincipalUidAttributeID();
    String usersCtxDN = this.getUsersCtxDN();

    try {
        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr);
        // This gives more control over search behavior :

        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute uidAttr = attrs.get(principalUidAttrName);

            if (uidAttr == null) {
                logger.warn("Invalid user uid attribute '" + principalUidAttrName + "'");
                continue;
            }

            String uidValue = uidAttr.get().toString();

            if (uidValue != null) {
                dn = sr.getName() + "," + usersCtxDN;
                if (logger.isDebugEnabled())
                    logger.debug("Found user '" + principalUidAttrName + "=" + uidValue + "' for user '" + uid
                            + "' DN=" + dn);
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("User not found for user '" + uid + "'");
            }
        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        if (tls != null) {
            tls.close();
        }
        ctx.close();
    }

    return dn;

}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Fetches the supplied user.//from   w w  w.  j  a  va2 s. c om
 *
 * @param attrValue the user id
 * @return the user id for the supplied uid
 * @throws NamingException LDAP error obtaining user information.
 * @throws IOException 
 */
protected String selectUser(String attrId, String attrValue) throws NamingException, IOException {
    String uidValue = null;

    InitialLdapContext ctx = createLdapInitialContext(false);

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    BasicAttributes matchAttrs = new BasicAttributes(true);

    String uidAttrName = this.getPrincipalUidAttributeID();
    String usersCtxDN = this.getUsersCtxDN();

    matchAttrs.put(attrId, attrValue);

    // String[] principalAttr = {attrId};

    try {
        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr);
        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + attrId + "=" + attrValue + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute uidAttr = attrs.get(uidAttrName);

            if (uidAttr == null) {
                logger.warn("Invalid user attrValue attribute '" + uidAttrName + "'");
                continue;
            }

            uidValue = uidAttr.get().toString();

            if (uidValue != null) {
                if (logger.isDebugEnabled())
                    logger.debug(
                            "Found user '" + uidAttrName + "=" + uidValue + "' for user '" + attrValue + "'");
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("User not found for user '" + attrValue + "'");
            }
        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        if (tls != null) {
            tls.close();
        }
        ctx.close();
    }

    return uidValue;
}

From source file:org.jahia.services.usermanager.ldap.LDAPUserGroupProvider.java

/**
 * get the members from a group DN//w  ww.ja v  a2s  . c  om
 *
 * @param groupDN
 * @return
 */
private List<Member> loadMembersFromDN(final String groupDN) {
    long l = System.currentTimeMillis();

    NamingEnumeration<?> members = ldapTemplateWrapper
            .execute(new BaseLdapActionCallback<NamingEnumeration<?>>(externalUserGroupService, key) {
                @Override
                public NamingEnumeration<?> doInLdap(LdapTemplate ldapTemplate) {
                    // use AD range search if a range is specify in the conf
                    if (groupConfig.getAdRangeStep() > 0) {
                        DefaultIncrementalAttributesMapper incrementalAttributesMapper = new DefaultIncrementalAttributesMapper(
                                groupConfig.getAdRangeStep(), groupConfig.getMembersAttribute());

                        while (incrementalAttributesMapper.hasMore()) {
                            ldapTemplate.lookup(groupDN, incrementalAttributesMapper.getAttributesForLookup(),
                                    incrementalAttributesMapper);
                        }

                        Attributes attributes = incrementalAttributesMapper.getCollectedAttributes();
                        try {
                            return attributes.get(groupConfig.getMembersAttribute()).getAll();
                        } catch (NamingException e) {
                            logger.error("Error retrieving the LDAP members using range on group: " + groupDN,
                                    e);
                        }
                    } else {
                        return ldapTemplate.lookup(groupDN, new String[] { groupConfig.getMembersAttribute() },
                                new AttributesMapper<NamingEnumeration<?>>() {
                                    @Override
                                    public NamingEnumeration<?> mapFromAttributes(Attributes attributes)
                                            throws NamingException {
                                        return attributes.get(groupConfig.getMembersAttribute()) != null
                                                ? attributes.get(groupConfig.getMembersAttribute()).getAll()
                                                : null;
                                    }
                                });
                    }
                    return null;
                }
            });
    logger.debug("Load group members {} in {} ms", groupDN, System.currentTimeMillis() - l);

    return loadMembers(members);
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Get user UID attribute for the given certificate.
 *
 * @param lookupValue value used for credentials lookup
 * @param certificate user certificate//from  w  ww .  j a v a 2 s  .c  om
 * @param cp credential provider
 * @return user UID
 * @throws NamingException LDAP error obtaining user UID.
 * @throws IOException 
 */
protected String loadUID(String lookupValue, X509Certificate certificate, CredentialProvider cp)
        throws NamingException, IOException {
    String uidValue = null;

    InitialLdapContext ctx = createLdapInitialContext(false);

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    String schemeName = null;
    if (cp instanceof AuthenticationScheme) {
        schemeName = ((AuthenticationScheme) cp).getName();
    }

    String principalLookupAttrName = this.getPrincipalLookupAttributeID();
    if (principalLookupAttrName == null || principalLookupAttrName.trim().equals("")
            || !"strong-authentication".equals(schemeName)) {
        principalLookupAttrName = this.getPrincipalUidAttributeID();
    }

    String principalUidAttrName = this.getPrincipalUidAttributeID();
    String certificateAttrName = this.getUserCertificateAtrributeID();
    String usersCtxDN = this.getUsersCtxDN();

    try {
        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr);
        // This gives more control over search behavior :

        NamingEnumeration answer = ctx.search(usersCtxDN,
                "(&(" + principalLookupAttrName + "={0})(" + certificateAttrName + "={1}))",
                new Object[] { lookupValue, certificate.getEncoded() }, getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute uidAttr = attrs.get(principalUidAttrName);

            if (uidAttr == null) {
                logger.warn("Invalid user uid attribute '" + principalUidAttrName + "'");
                continue;
            }

            uidValue = uidAttr.get().toString();

            if (uidValue != null) {
                if (logger.isDebugEnabled())
                    logger.debug("Found user " + principalUidAttrName + "=" + uidValue);
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("User not found for certificate '"
                            + certificate.getSubjectX500Principal().getName() + "'");
            }
        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } catch (CertificateEncodingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Certificate encoding exception", e);
    } finally {
        // Close the context to release the connection
        if (tls != null) {
            tls.close();
        }
        ctx.close();
    }

    return uidValue;
}

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

/**
 * Fetch both statically and dynamically defined references and merge the results.
 *
 * @see org.nuxeo.ecm.directory.Reference#getSourceIdsForTarget(String)
 *//*from   w w  w.  j  a  va  2  s.co  m*/
@Override
public List<String> getSourceIdsForTarget(String targetId) throws DirectoryException {

    // container to hold merged references
    Set<String> sourceIds = new TreeSet<>();
    SearchResult targetLdapEntry = null;
    String targetDn = null;

    // step #1: resolve static references
    String staticAttributeId = getStaticAttributeId();
    if (staticAttributeId != null) {
        // step #1.1: fetch the dn of the targetId entry in the target
        // directory by the static dn valued strategy
        LDAPDirectory targetDir = getTargetLDAPDirectory();

        if (staticAttributeIdIsDn) {
            try (LDAPSession targetSession = (LDAPSession) targetDir.getSession()) {
                targetLdapEntry = targetSession.getLdapEntry(targetId, false);
                if (targetLdapEntry == null) {
                    String msg = String.format(
                            "Failed to perform inverse lookup on LDAPReference"
                                    + " resolving field '%s' of '%s' to entries of '%s'"
                                    + " using the static content of attribute '%s':"
                                    + " entry '%s' cannot be found in '%s'",
                            fieldName, sourceDirectory, targetDirectoryName, staticAttributeId, targetId,
                            targetDirectoryName);
                    throw new DirectoryEntryNotFoundException(msg);
                }
                targetDn = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace());

            } catch (NamingException e) {
                throw new DirectoryException(
                        "error fetching " + targetId + " from " + targetDirectoryName + ": " + e.getMessage(),
                        e);
            }
        }

        // step #1.2: search for entries that reference that dn in the
        // source directory and collect their ids
        LDAPDirectory ldapSourceDirectory = getSourceLDAPDirectory();

        String filterExpr = String.format("(&(%s={0})%s)", staticAttributeId,
                ldapSourceDirectory.getBaseFilter());
        String[] filterArgs = new String[1];

        if (staticAttributeIdIsDn) {
            filterArgs[0] = targetDn;
        } else {
            filterArgs[0] = targetId;
        }

        String searchBaseDn = ldapSourceDirectory.getDescriptor().getSearchBaseDn();
        SearchControls sctls = ldapSourceDirectory.getSearchControls();
        try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
            if (log.isDebugEnabled()) {
                log.debug(String.format(
                        "LDAPReference.getSourceIdsForTarget(%s): LDAP search search base='%s'"
                                + " filter='%s' args='%s' scope='%s' [%s]",
                        targetId, searchBaseDn, filterExpr, StringUtils.join(filterArgs, ", "),
                        sctls.getSearchScope(), this));
            }
            NamingEnumeration<SearchResult> results = sourceSession.dirContext.search(searchBaseDn, filterExpr,
                    filterArgs, sctls);

            try {
                while (results.hasMore()) {
                    Attributes attributes = results.next().getAttributes();
                    // NXP-2461: check that id field is filled
                    Attribute attr = attributes.get(sourceSession.idAttribute);
                    if (attr != null) {
                        Object value = attr.get();
                        if (value != null) {
                            sourceIds.add(value.toString());
                        }
                    }
                }
            } finally {
                results.close();
            }
        } catch (NamingException e) {
            throw new DirectoryException("error during reference search for " + filterArgs[0], e);
        }
    }
    // step #2: resolve dynamic references
    String dynamicAttributeId = this.dynamicAttributeId;
    if (dynamicAttributeId != null) {

        LDAPDirectory ldapSourceDirectory = getSourceLDAPDirectory();
        LDAPDirectory ldapTargetDirectory = getTargetLDAPDirectory();
        String searchBaseDn = ldapSourceDirectory.getDescriptor().getSearchBaseDn();

        try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession();
                LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) {
            // step #2.1: fetch the target entry to apply the ldap url
            // filters of the candidate sources on it
            if (targetLdapEntry == null) {
                // only fetch the entry if not already fetched by the
                // static
                // attributes references resolution
                targetLdapEntry = targetSession.getLdapEntry(targetId, false);
            }
            if (targetLdapEntry == null) {
                String msg = String.format(
                        "Failed to perform inverse lookup on LDAPReference"
                                + " resolving field '%s' of '%s' to entries of '%s'"
                                + " using the dynamic content of attribute '%s':"
                                + " entry '%s' cannot be found in '%s'",
                        fieldName, ldapSourceDirectory, targetDirectoryName, dynamicAttributeId, targetId,
                        targetDirectoryName);
                throw new DirectoryException(msg);
            }
            targetDn = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace());
            Attributes targetAttributes = targetLdapEntry.getAttributes();

            // step #2.2: find the list of entries that hold candidate
            // dynamic links in the source directory
            SearchControls sctls = ldapSourceDirectory.getSearchControls();
            sctls.setReturningAttributes(new String[] { sourceSession.idAttribute, dynamicAttributeId });
            String filterExpr = String.format("%s=*", dynamicAttributeId);

            if (log.isDebugEnabled()) {
                log.debug(String.format(
                        "LDAPReference.getSourceIdsForTarget(%s): LDAP search search base='%s'"
                                + " filter='%s' scope='%s' [%s]",
                        targetId, searchBaseDn, filterExpr, sctls.getSearchScope(), this));
            }
            NamingEnumeration<SearchResult> results = sourceSession.dirContext.search(searchBaseDn, filterExpr,
                    sctls);
            try {
                while (results.hasMore()) {
                    // step #2.3: for each sourceId and each ldapUrl test
                    // whether the current target entry matches the
                    // collected
                    // URL
                    Attributes sourceAttributes = results.next().getAttributes();

                    NamingEnumeration<?> ldapUrls = sourceAttributes.get(dynamicAttributeId).getAll();
                    try {
                        while (ldapUrls.hasMore()) {
                            LdapURL ldapUrl = new LdapURL(ldapUrls.next().toString());
                            String candidateDN = pseudoNormalizeDn(ldapUrl.getDN());
                            // check base URL
                            if (!targetDn.endsWith(candidateDN)) {
                                continue;
                            }

                            // check onelevel scope constraints
                            if ("onelevel".equals(ldapUrl.getScope())) {
                                int targetDnSize = new LdapName(targetDn).size();
                                int urlDnSize = new LdapName(candidateDN).size();
                                if (targetDnSize - urlDnSize > 1) {
                                    // target is not a direct child of the
                                    // DN of the
                                    // LDAP URL
                                    continue;
                                }
                            }

                            // check that the target entry matches the
                            // filter
                            if (getFilterMatcher().match(targetAttributes, ldapUrl.getFilter())) {
                                // the target match the source url, add it
                                // to the
                                // collected ids
                                sourceIds.add(sourceAttributes.get(sourceSession.idAttribute).get().toString());
                            }
                        }
                    } finally {
                        ldapUrls.close();
                    }
                }
            } finally {
                results.close();
            }
        } catch (NamingException e) {
            throw new DirectoryException("error during reference search for " + targetId, e);
        }
    }

    /*
     * This kind of reference is not supported because Active Directory use filter expression not yet supported by
     * LDAPFilterMatcher. See NXP-4562
     */
    if (dynamicReferences != null && dynamicReferences.length > 0) {
        log.error("This kind of reference is not supported.");
    }

    return new ArrayList<>(sourceIds);
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Obtains the roles for the given user.
 *
 * @param username the user name to fetch user data.
 * @return the list of roles to which the user is associated to.
 * @throws NamingException LDAP error obtaining roles fro the given user
 * @throws IOException //  ww w . j a  v a  2 s  .co  m
 */
protected String[] selectRolesByUsername(String username) throws NamingException, IOException {
    List userRoles = new ArrayList();

    InitialLdapContext ctx = null;
    try {
        ctx = createLdapInitialContext(getUseBindCredentials());
    } catch (NamingException e) {
        if (getUseBindCredentials()) {
            // in case we are using virtual identity store
            return (String[]) userRoles.toArray(new String[userRoles.size()]);
        } else {
            throw e;
        }
    }

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    String rolesCtxDN = getRolesCtxDN();

    // Search for any roles associated with the user
    if (rolesCtxDN != null) {

        // The attribute where user DN is stored in roles :
        String uidAttributeID = getUidAttributeID();
        if (uidAttributeID == null)
            uidAttributeID = "uniquemember";

        // The attribute that identifies the role name 
        String roleAttrName = getRoleAttributeID();
        if (roleAttrName == null)
            roleAttrName = "roles";

        String userDN;
        if ("UID".equals(getRoleMatchingMode())) {
            // Use User ID to match the role
            userDN = username;
        } else {
            // Default behaviour: Match the role using the User DN, not just the username :
            userDN = selectUserDN(username);
        }

        if (userDN != null) {
            if (logger.isDebugEnabled())
                logger.debug("Searching Roles for user '" + userDN + "' in Uid attribute name '"
                        + uidAttributeID + "'");

            try {
                if (userDN.contains("\\")) {
                    logger.debug("Escaping '\\' character");
                    userDN = userDN.replace("\\", "\\\\\\");
                }

                NamingEnumeration answer = ctx.search(rolesCtxDN, "(&(" + uidAttributeID + "=" + userDN + "))",
                        getSearchControls());

                if (logger.isDebugEnabled())
                    logger.debug("Search Name:  " + rolesCtxDN);

                if (logger.isDebugEnabled())
                    logger.debug("Search Filter:  (&(" + uidAttributeID + "=" + userDN + "))");

                if (!answer.hasMore())
                    logger.info("No role where found for user " + username);

                while (answer.hasMore()) {
                    SearchResult sr = (SearchResult) answer.next();
                    Attributes attrs = sr.getAttributes();
                    Attribute roles = attrs.get(roleAttrName);
                    for (int r = 0; r < roles.size(); r++) {
                        Object value = roles.get(r);
                        String roleName = null;
                        // The role attribute value is the role name
                        roleName = value.toString();

                        if (roleName != null) {
                            if (logger.isDebugEnabled())
                                logger.debug("Saving role '" + roleName + "' for user '" + username + "'");
                            userRoles.add(roleName);
                        }
                    }
                }
            } catch (NamingException e) {
                if (logger.isDebugEnabled())
                    logger.debug("Failed to locate roles", e);
            }
        }
    }
    // Close the context to release the connection
    if (tls != null) {
        tls.close();
    }
    ctx.close();
    return (String[]) userRoles.toArray(new String[userRoles.size()]);
}

From source file:com.funambol.LDAP.dao.impl.ContactDAO.java

/**
 * Compares two attribute sets//from ww  w . j  a  v a 2 s  .  co  m
 * 
 * @param authoritativeSet
 *            reference set
 * @param compareSet
 *            comparative set
 * @return list of modifications to commit
 * @throws NamingException
 */
public Map<String, Attributes> compareAttributeSets(Attributes authoritativeSet, Attributes compareSet)
        throws NamingException {

    Map<String, Attributes> modifications = new HashMap<String, Attributes>();
    Attributes delAttributes = new BasicAttributes();
    Attributes addAttributes = new BasicAttributes();
    Attributes replaceAttributes = new BasicAttributes();
    // List<LDAPModification> modifications = new
    // ArrayList<LDAPModification>();
    List<String> supportedAttrs = Arrays.asList(getSupportedAttributes());

    Iterator<String> it = supportedAttrs.iterator();

    // loop over supported attributes
    while (it.hasNext()) {
        String attribute = it.next();

        // skip unmodifiable attrs
        if (attribute.equals("modifyTimestamp"))
            continue;

        Attribute authoritaveAttribute = authoritativeSet.get(attribute);
        Attribute compareAttribute = compareSet.get(attribute);

        if (authoritaveAttribute == null || compareAttribute == null) {
            // remove an old attribute
            if (authoritaveAttribute == null && compareAttribute != null) {
                delAttributes.put(compareAttribute);
            }

            // add a new attribute
            if (authoritaveAttribute != null && compareAttribute == null) {
                addAttributes.put(authoritaveAttribute);
            }
        } else {
            // replace an attribute
            String authValue = (String) authoritaveAttribute.get();
            String compareValue = (String) compareAttribute.get();
            if (!authValue.equals(compareValue)) {
                replaceAttributes.put(authoritaveAttribute);
            }
        }
    }
    modifications.put(DEL_ATTRIBUTE, delAttributes);
    modifications.put(REPLACE_ATTRIBUTE, replaceAttributes);
    modifications.put(ADD_ATTRIBUTE, addAttributes);

    return modifications;
}