Example usage for javax.naming NamingEnumeration hasMore

List of usage examples for javax.naming NamingEnumeration hasMore

Introduction

In this page you can find the example usage for javax.naming NamingEnumeration hasMore.

Prototype

public boolean hasMore() throws NamingException;

Source Link

Document

Determines whether there are any more elements in the enumeration.

Usage

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

/**
 * Optimized method to spare a LDAP request when the caller is a LDAPSession object that has already fetched the
 * LDAP Attribute instances./* w w  w .java  2  s  .  c  o m*/
 * <p>
 * This method should return the same results as the sister method: org.nuxeo
 * .ecm.directory.Reference#getTargetIdsForSource(java.lang.String)
 *
 * @return target reference ids
 * @throws DirectoryException
 */
public List<String> getLdapTargetIds(Attributes attributes) throws DirectoryException {

    Set<String> targetIds = new TreeSet<>();

    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectoryDescriptor targetDirconfig = getTargetDirectoryDescriptor();
    String emptyRefMarker = ldapTargetDirectory.getDescriptor().getEmptyRefMarker();
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) {
        String baseDn = pseudoNormalizeDn(targetDirconfig.getSearchBaseDn());

        // step #1: fetch ids referenced by static attributes
        String staticAttributeId = getStaticAttributeId();
        Attribute staticAttribute = null;
        if (staticAttributeId != null) {
            staticAttribute = attributes.get(staticAttributeId);
        }

        if (staticAttribute != null && !staticAttributeIdIsDn) {
            NamingEnumeration<?> staticContent = staticAttribute.getAll();
            try {
                while (staticContent.hasMore()) {
                    String value = staticContent.next().toString();
                    if (!emptyRefMarker.equals(value)) {
                        targetIds.add(value);
                    }
                }
            } finally {
                staticContent.close();
            }
        }

        if (staticAttribute != null && staticAttributeIdIsDn) {
            NamingEnumeration<?> targetDns = staticAttribute.getAll();
            try {
                while (targetDns.hasMore()) {
                    String targetDn = targetDns.next().toString();

                    if (!pseudoNormalizeDn(targetDn).endsWith(baseDn)) {
                        // optim: avoid network connections when obvious
                        if (log.isTraceEnabled()) {
                            log.trace(String.format("ignoring: dn='%s' (does not match '%s') for '%s'",
                                    targetDn, baseDn, this));
                        }
                        continue;
                    }
                    // find the id of the referenced entry
                    String id = null;

                    if (targetSession.rdnMatchesIdField()) {
                        // optim: do not fetch the entry to get its true id
                        // but
                        // guess it by reading the targetDn
                        LdapName name = new LdapName(targetDn);
                        String rdn = name.get(name.size() - 1);
                        int pos = rdn.indexOf("=");
                        id = rdn.substring(pos + 1);
                    } else {
                        id = getIdForDn(targetSession, targetDn);
                        if (id == null) {
                            log.warn(String.format(
                                    "ignoring target '%s' (missing attribute '%s') while resolving reference '%s'",
                                    targetDn, targetSession.idAttribute, this));
                            continue;
                        }
                    }
                    if (forceDnConsistencyCheck) {
                        // check that the referenced entry is actually part
                        // of
                        // the target directory (takes care of the filters
                        // and
                        // the scope)
                        // this check can be very expensive on large groups
                        // and thus not enabled by default
                        if (!targetSession.hasEntry(id)) {
                            if (log.isTraceEnabled()) {
                                log.trace(String.format(
                                        "ignoring target '%s' when resolving '%s' (not part of target"
                                                + " directory by forced DN consistency check)",
                                        targetDn, this));
                            }
                            continue;
                        }
                    }
                    // NXP-2461: check that id field is filled
                    if (id != null) {
                        targetIds.add(id);
                    }
                }
            } finally {
                targetDns.close();
            }
        }
        // step #2: fetched dynamically referenced ids
        String dynamicAttributeId = this.dynamicAttributeId;
        Attribute dynamicAttribute = null;
        if (dynamicAttributeId != null) {
            dynamicAttribute = attributes.get(dynamicAttributeId);
        }
        if (dynamicAttribute != null) {
            NamingEnumeration<?> rawldapUrls = dynamicAttribute.getAll();
            try {
                while (rawldapUrls.hasMore()) {
                    LdapURL ldapUrl = new LdapURL(rawldapUrls.next().toString());
                    String linkDn = pseudoNormalizeDn(ldapUrl.getDN());
                    String directoryDn = pseudoNormalizeDn(targetDirconfig.getSearchBaseDn());
                    int scope = SearchControls.ONELEVEL_SCOPE;
                    String scopePart = ldapUrl.getScope();
                    if (scopePart != null && scopePart.toLowerCase().startsWith("sub")) {
                        scope = SearchControls.SUBTREE_SCOPE;
                    }
                    if (!linkDn.endsWith(directoryDn) && !directoryDn.endsWith(linkDn)) {
                        // optim #1: if the dns do not match, abort
                        continue;
                    } else if (directoryDn.endsWith(linkDn) && linkDn.length() < directoryDn.length()
                            && scope == SearchControls.ONELEVEL_SCOPE) {
                        // optim #2: the link dn is pointing to elements
                        // that at
                        // upperlevel than directory elements
                        continue;
                    } else {

                        // Search for references elements
                        targetIds.addAll(getReferencedElements(attributes, directoryDn, linkDn,
                                ldapUrl.getFilter(), scope));

                    }
                }
            } finally {
                rawldapUrls.close();
            }
        }

        if (dynamicReferences != null && dynamicReferences.length > 0) {

            // Only the first Dynamic Reference is used
            LDAPDynamicReferenceDescriptor dynAtt = dynamicReferences[0];

            Attribute baseDnsAttribute = attributes.get(dynAtt.baseDN);
            Attribute filterAttribute = attributes.get(dynAtt.filter);

            if (baseDnsAttribute != null && filterAttribute != null) {

                NamingEnumeration<?> baseDns = null;
                NamingEnumeration<?> filters = null;

                try {
                    // Get the BaseDN value from the descriptor
                    baseDns = baseDnsAttribute.getAll();
                    String linkDnValue = baseDns.next().toString();
                    baseDns.close();
                    linkDnValue = pseudoNormalizeDn(linkDnValue);

                    // Get the filter value from the descriptor
                    filters = filterAttribute.getAll();
                    String filterValue = filters.next().toString();
                    filters.close();

                    // Get the scope value from the descriptor
                    int scope = "subtree".equalsIgnoreCase(dynAtt.type) ? SearchControls.SUBTREE_SCOPE
                            : SearchControls.ONELEVEL_SCOPE;

                    String directoryDn = pseudoNormalizeDn(targetDirconfig.getSearchBaseDn());

                    // if the dns match, and if the link dn is pointing to
                    // elements that at upperlevel than directory elements
                    if ((linkDnValue.endsWith(directoryDn) || directoryDn.endsWith(linkDnValue))
                            && !(directoryDn.endsWith(linkDnValue)
                                    && linkDnValue.length() < directoryDn.length()
                                    && scope == SearchControls.ONELEVEL_SCOPE)) {

                        // Correct the filter expression
                        filterValue = FilterExpressionCorrector.correctFilter(filterValue,
                                FilterJobs.CORRECT_NOT);

                        // Search for references elements
                        targetIds.addAll(getReferencedElements(attributes, directoryDn, linkDnValue,
                                filterValue, scope));

                    }
                } finally {
                    if (baseDns != null) {
                        baseDns.close();
                    }

                    if (filters != null) {
                        filters.close();
                    }
                }

            }

        }
        // return merged attributes
        return new ArrayList<String>(targetIds);
    } catch (NamingException e) {
        throw new DirectoryException("error computing LDAP references", e);
    }
}

From source file:org.apache.zeppelin.realm.LdapRealm.java

/**
* Returns the LDAP User Distinguished Name (DN) to use when acquiring an
* {@link javax.naming.ldap.LdapContext LdapContext} from the
* {@link LdapContextFactory}.//w w w.j ava2 s.c o m
* <p/>
* If the the {@link #getUserDnTemplate() userDnTemplate} property has been
* set, this implementation will construct the User DN by substituting the
* specified {@code principal} into the configured template. If the
* {@link #getUserDnTemplate() userDnTemplate} has not been set, the method
* argument will be returned directly (indicating that the submitted
* authentication token principal <em>is</em> the User DN).
*
* @param principal
*            the principal to substitute into the configured
*            {@link #getUserDnTemplate() userDnTemplate}.
* @return the constructed User DN to use at runtime when acquiring an
*         {@link javax.naming.ldap.LdapContext}.
* @throws IllegalArgumentException
*             if the method argument is null or empty
* @throws IllegalStateException
*             if the {@link #getUserDnTemplate userDnTemplate} has not been
*             set.
* @see LdapContextFactory#getLdapContext(Object, Object)
*/
@Override
protected String getUserDn(final String principal) throws IllegalArgumentException, IllegalStateException {
    String userDn;
    String matchedPrincipal = matchPrincipal(principal);
    String userSearchBase = getUserSearchBase();
    String userSearchAttributeName = getUserSearchAttributeName();

    // If not searching use the userDnTemplate and return.
    if ((userSearchBase == null || userSearchBase.isEmpty()) || (userSearchAttributeName == null
            && userSearchFilter == null && !"object".equalsIgnoreCase(userSearchScope))) {
        userDn = expandTemplate(userDnTemplate, matchedPrincipal);
        if (log.isDebugEnabled()) {
            log.debug("LDAP UserDN and Principal: " + userDn + "," + principal);
        }
        return userDn;
    }

    // Create the searchBase and searchFilter from config.
    String searchBase = expandTemplate(getUserSearchBase(), matchedPrincipal);
    String searchFilter = null;
    if (userSearchFilter == null) {
        if (userSearchAttributeName == null) {
            searchFilter = String.format("(objectclass=%1$s)", getUserObjectClass());
        } else {
            searchFilter = String.format("(&(objectclass=%1$s)(%2$s=%3$s))", getUserObjectClass(),
                    userSearchAttributeName,
                    expandTemplate(getUserSearchAttributeTemplate(), matchedPrincipal));
        }
    } else {
        searchFilter = expandTemplate(userSearchFilter, matchedPrincipal);
    }
    SearchControls searchControls = getUserSearchControls();

    // Search for userDn and return.
    LdapContext systemLdapCtx = null;
    NamingEnumeration<SearchResult> searchResultEnum = null;
    try {
        systemLdapCtx = getContextFactory().getSystemLdapContext();
        if (log.isDebugEnabled()) {
            log.debug("SearchBase,SearchFilter,UserSearchScope: " + searchBase + "," + searchFilter + ","
                    + userSearchScope);
        }
        searchResultEnum = systemLdapCtx.search(searchBase, searchFilter, searchControls);
        // SearchResults contains all the entries in search scope
        if (searchResultEnum.hasMore()) {
            SearchResult searchResult = searchResultEnum.next();
            userDn = searchResult.getNameInNamespace();
            if (log.isDebugEnabled()) {
                log.debug("UserDN Returned,Principal: " + userDn + "," + principal);
            }
            return userDn;
        } else {
            throw new IllegalArgumentException("Illegal principal name: " + principal);
        }
    } catch (AuthenticationException ne) {
        ne.printStackTrace();
        throw new IllegalArgumentException("Illegal principal name: " + principal);
    } catch (NamingException ne) {
        throw new IllegalArgumentException("Hit NamingException: " + ne.getMessage());
    } finally {
        try {
            if (searchResultEnum != null) {
                searchResultEnum.close();
            }
        } catch (NamingException ne) {
            // Ignore exception on close.
        } finally {
            LdapUtils.closeContext(systemLdapCtx);
        }
    }
}

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

public String[] getNamesOfModifiedAttributes() {

    List tmpList = new ArrayList();

    NamingEnumeration attributesEnumeration;
    if (isUpdateMode()) {
        attributesEnumeration = updatedAttrs.getAll();
    } else {/* w  w w  . j a  v  a2 s .c o  m*/
        attributesEnumeration = originalAttrs.getAll();
    }

    try {
        while (attributesEnumeration.hasMore()) {
            Attribute oneAttribute = (Attribute) attributesEnumeration.next();
            tmpList.add(oneAttribute.getID());
        }
    } catch (NamingException e) {
        throw LdapUtils.convertLdapException(e);
    } finally {
        closeNamingEnumeration(attributesEnumeration);
    }

    return (String[]) tmpList.toArray(new String[0]);
}

From source file:org.lsc.jndi.JndiServices.java

/**
 * Return the LDAP schema./*from w  w w .ja v a  2 s .com*/
 *
 * @param attrsToReturn
 *                list of attribute names to return (or null for all
 *                'standard' attributes)
 * @return the map of name => attribute
 * @throws NamingException
 *                 thrown if something goes wrong (bad
 */
@SuppressWarnings("unchecked")
public Map<String, List<String>> getSchema(final String[] attrsToReturn) throws NamingException {
    Map<String, List<String>> attrsResult = new HashMap<String, List<String>>();

    // connect to directory
    Hashtable<String, String> props = (Hashtable<String, String>) ctx.getEnvironment();
    String baseUrl = (String) props.get(Context.PROVIDER_URL);
    baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf('/'));
    props.put(Context.PROVIDER_URL, baseUrl);
    DirContext schemaCtx = new InitialLdapContext(props, null);

    // find schema entry
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.OBJECT_SCOPE);
    sc.setReturningAttributes(new String[] { "subschemaSubentry" });

    NamingEnumeration<SearchResult> schemaDnSR = schemaCtx.search("", "(objectclass=*)", sc);

    SearchResult sr = null;
    Attribute subschemaSubentry = null;
    String subschemaSubentryDN = null;

    if (schemaDnSR.hasMore()) {
        sr = schemaDnSR.next();
    }
    if (sr != null) {
        subschemaSubentry = sr.getAttributes().get("subschemaSubentry");
    }
    if (subschemaSubentry != null && subschemaSubentry.size() > 0) {
        subschemaSubentryDN = (String) subschemaSubentry.get();
    }

    if (subschemaSubentryDN != null) {
        // get schema attributes from subschemaSubentryDN
        Attributes schemaAttrs = schemaCtx.getAttributes(subschemaSubentryDN,
                attrsToReturn != null ? attrsToReturn : new String[] { "*", "+" });

        if (schemaAttrs != null) {
            for (String attr : attrsToReturn) {
                Attribute schemaAttr = schemaAttrs.get(attr);
                if (schemaAttr != null) {
                    attrsResult.put(schemaAttr.getID(), (List<String>) Collections.list(schemaAttr.getAll()));
                }
            }
        }
    }

    return attrsResult;
}

From source file:org.apache.zeppelin.realm.LdapRealm.java

protected Set<String> rolesFor(PrincipalCollection principals, String userNameIn, final LdapContext ldapCtx,
        final LdapContextFactory ldapContextFactory, Session session) throws NamingException {
    final Set<String> roleNames = new HashSet<>();
    final Set<String> groupNames = new HashSet<>();
    final String userName;
    if (getUserLowerCase()) {
        log.debug("userLowerCase true");
        userName = userNameIn.toLowerCase();
    } else {/*from  w  ww  . ja v  a2s. c o m*/
        userName = userNameIn;
    }

    String userDn = getUserDnForSearch(userName);

    // Activate paged results
    int pageSize = getPagingSize();
    if (log.isDebugEnabled()) {
        log.debug("Ldap PagingSize: " + pageSize);
    }
    int numResults = 0;
    byte[] cookie = null;
    try {
        ldapCtx.addToEnvironment(Context.REFERRAL, "ignore");

        ldapCtx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });

        do {
            // ldapsearch -h localhost -p 33389 -D
            // uid=guest,ou=people,dc=hadoop,dc=apache,dc=org -w guest-password
            // -b dc=hadoop,dc=apache,dc=org -s sub '(objectclass=*)'
            NamingEnumeration<SearchResult> searchResultEnum = null;
            SearchControls searchControls = getGroupSearchControls();
            try {
                if (groupSearchEnableMatchingRuleInChain) {
                    searchResultEnum = ldapCtx.search(getGroupSearchBase(), String
                            .format(MATCHING_RULE_IN_CHAIN_FORMAT, groupObjectClass, memberAttribute, userDn),
                            searchControls);
                    while (searchResultEnum != null && searchResultEnum.hasMore()) {
                        // searchResults contains all the groups in search scope
                        numResults++;
                        final SearchResult group = searchResultEnum.next();

                        Attribute attribute = group.getAttributes().get(getGroupIdAttribute());
                        String groupName = attribute.get().toString();

                        String roleName = roleNameFor(groupName);
                        if (roleName != null) {
                            roleNames.add(roleName);
                        } else {
                            roleNames.add(groupName);
                        }
                    }
                } else {
                    // Default group search filter
                    String searchFilter = String.format("(objectclass=%1$s)", groupObjectClass);

                    // If group search filter is defined in Shiro config, then use it
                    if (groupSearchFilter != null) {
                        searchFilter = expandTemplate(groupSearchFilter, userName);
                        //searchFilter = String.format("%1$s", groupSearchFilter);
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("Group SearchBase|SearchFilter|GroupSearchScope: " + getGroupSearchBase()
                                + "|" + searchFilter + "|" + groupSearchScope);
                    }
                    searchResultEnum = ldapCtx.search(getGroupSearchBase(), searchFilter, searchControls);
                    while (searchResultEnum != null && searchResultEnum.hasMore()) {
                        // searchResults contains all the groups in search scope
                        numResults++;
                        final SearchResult group = searchResultEnum.next();
                        addRoleIfMember(userDn, group, roleNames, groupNames, ldapContextFactory);
                    }
                }
            } catch (PartialResultException e) {
                log.debug("Ignoring PartitalResultException");
            } finally {
                if (searchResultEnum != null) {
                    searchResultEnum.close();
                }
            }
            // Re-activate paged results
            ldapCtx.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
        } while (cookie != null);
    } catch (SizeLimitExceededException e) {
        log.info("Only retrieved first " + numResults + " groups due to SizeLimitExceededException.");
    } catch (IOException e) {
        log.error("Unabled to setup paged results");
    }
    // save role names and group names in session so that they can be
    // easily looked up outside of this object
    session.setAttribute(SUBJECT_USER_ROLES, roleNames);
    session.setAttribute(SUBJECT_USER_GROUPS, groupNames);
    if (!groupNames.isEmpty() && (principals instanceof MutablePrincipalCollection)) {
        ((MutablePrincipalCollection) principals).addAll(groupNames, getName());
    }
    if (log.isDebugEnabled()) {
        log.debug("User RoleNames: " + userName + "::" + roleNames);
    }
    return roleNames;
}

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

private List<Member> loadMembers(NamingEnumeration<?> members) {
    List<Member> memberList = new ArrayList<Member>();
    try {/*from   w ww  .  ja  v a2s  .co  m*/
        while (members != null && members.hasMore()) {
            final String memberNaming = (String) members.next();
            // try to know if we deal with a group or a user
            Boolean isUser = userConfig.isCanGroupContainSubGroups() ? guessUserOrGroupFromDN(memberNaming)
                    : true;

            // try to retrieve the object from the cache
            LDAPAbstractCacheEntry cacheEntry;
            if (isUser != null) {
                if (isUser) {
                    cacheEntry = ldapCacheManager.getUserCacheEntryByDn(getKey(), memberNaming);
                } else {
                    cacheEntry = ldapCacheManager.getGroupCacheEntryByDn(getKey(), memberNaming);
                }
            } else {
                // look in all cache
                cacheEntry = ldapCacheManager.getUserCacheEntryByDn(getKey(), memberNaming);
                if (cacheEntry == null) {
                    cacheEntry = ldapCacheManager.getGroupCacheEntryByDn(getKey(), memberNaming);
                    isUser = cacheEntry != null ? false : null;
                } else {
                    isUser = true;
                }
            }
            if (cacheEntry != null) {
                if (isUser) {
                    memberList.add(new Member(cacheEntry.getName(), Member.MemberType.USER));
                } else {
                    memberList.add(new Member(cacheEntry.getName(), Member.MemberType.GROUP));
                }
                continue;
            }

            // try to retrieve
            if (isUser != null && userConfig.isSearchAttributeInDn()) {
                String name = getNameFromDn(memberNaming, isUser);
                if (StringUtils.isNotEmpty(name)) {
                    memberList.add(isUser ? new Member(name, Member.MemberType.USER)
                            : new Member(name, Member.MemberType.GROUP));
                    continue;
                }
            }

            // do queries
            // and cache the result
            Member member = null;
            LDAPUserCacheEntry userCacheEntry = getUserCacheEntryByDN(memberNaming, true);
            if (userCacheEntry == null) {
                // look in groups
                LDAPGroupCacheEntry groupCacheEntry = getGroupCacheEntryByDN(memberNaming, true, false);
                if (groupCacheEntry == null) {
                    if (groupConfig.isDynamicEnabled()) {
                        // look in dynamic groups
                        groupCacheEntry = getGroupCacheEntryByDN(memberNaming, true, true);
                        if (groupCacheEntry != null) {
                            member = new Member(groupCacheEntry.getName(), Member.MemberType.GROUP);
                        }
                    }
                } else {
                    member = new Member(groupCacheEntry.getName(), Member.MemberType.GROUP);
                }
            } else {
                member = new Member(userCacheEntry.getName(), Member.MemberType.USER);
            }

            if (member != null) {
                memberList.add(member);
            }
        }
    } catch (NamingException e) {
        logger.error("Error retrieving LDAP group members for group", e);
    }

    return memberList;
}

From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java

/**
 * Does a case-insensitive search for the given value in an attribute.
 *
 * @param attribute//from  ww w .  j av  a  2  s .c  om
 *            the attribute
 * @param value
 *            the value to search for
 * @return <code>true</code>, if the value was found
 * @throws javax.naming.NamingException
 *             if there is a problem accessing the attribute values
 */
private boolean hasAttributeValue(Attribute attribute, String value) throws NamingException {
    if (attribute != null) {
        NamingEnumeration<?> values = attribute.getAll();
        while (values.hasMore()) {
            try {
                if (value.equalsIgnoreCase((String) values.next())) {
                    return true;
                }
            } catch (ClassCastException e) {
                // Not a string value. ignore and continue
            }
        }
    }
    return false;
}

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)
 *//*w  w w. j a  v a  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

/**
 * Fetches the supplied user.// www.  j  ava  2  s  . c o m
 *
 * @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.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Fetches the supplied user DN./* w  w  w  . jav  a2  s.c om*/
 *
 * @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;

}