Example usage for javax.naming NamingEnumeration next

List of usage examples for javax.naming NamingEnumeration next

Introduction

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

Prototype

public T next() throws NamingException;

Source Link

Document

Retrieves the next element in the enumeration.

Usage

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

/**
 * Creates User in OLAT and ads user to LDAP securityGroup Required Attributes
 * have to be checked before this method.
 * /*from w  ww.ja  v a 2 s. c  o m*/
 * @param userAttributes Set of LDAP Attribute of User to be created
 */
@Override
public Identity createAndPersistUser(Attributes userAttributes) {
    // Get and Check Config
    String[] reqAttrs = syncConfiguration.checkRequestAttributes(userAttributes);
    if (reqAttrs != null) {
        log.warn("Can not create and persist user, the following attributes are missing::"
                + ArrayUtils.toString(reqAttrs), null);
        return null;
    }

    String uid = getAttributeValue(userAttributes
            .get(syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER)));
    String email = getAttributeValue(
            userAttributes.get(syncConfiguration.getOlatPropertyToLdapAttribute(UserConstants.EMAIL)));
    // Lookup user
    if (securityManager.findIdentityByName(uid) != null) {
        log.error("Can't create user with username='" + uid
                + "', this username does already exist in OLAT database", null);
        return null;
    }
    if (!MailHelper.isValidEmailAddress(email)) {
        // needed to prevent possibly an AssertException in findIdentityByEmail breaking the sync!
        log.error("Cannot try to lookup user " + uid + " by email with an invalid email::" + email, null);
        return null;
    }
    if (userManager.userExist(email)) {
        log.error("Can't create user with email='" + email
                + "', a user with that email does already exist in OLAT database", null);
        return null;
    }

    // Create User (first and lastname is added in next step)
    User user = userManager.createUser(null, null, email);
    // Set User Property's (Iterates over Attributes and gets OLAT Property out
    // of olatexconfig.xml)
    NamingEnumeration<? extends Attribute> neAttr = userAttributes.getAll();
    try {
        while (neAttr.hasMore()) {
            Attribute attr = neAttr.next();
            String olatProperty = mapLdapAttributeToOlatProperty(attr.getID());
            if (!attr.getID().equalsIgnoreCase(
                    syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER))) {
                String ldapValue = getAttributeValue(attr);
                if (olatProperty == null || ldapValue == null)
                    continue;
                user.setProperty(olatProperty, ldapValue);
            }
        }
        // Add static user properties from the configuration
        Map<String, String> staticProperties = syncConfiguration.getStaticUserProperties();
        if (staticProperties != null && staticProperties.size() > 0) {
            for (Entry<String, String> staticProperty : staticProperties.entrySet()) {
                user.setProperty(staticProperty.getKey(), staticProperty.getValue());
            }
        }
    } catch (NamingException e) {
        log.error("NamingException when trying to create and persist LDAP user with username::" + uid, e);
        return null;
    } catch (Exception e) {
        // catch any exception here to properly log error
        log.error("Unknown exception when trying to create and persist LDAP user with username::" + uid, e);
        return null;
    }

    // Create Identity
    Identity identity = securityManager.createAndPersistIdentityAndUser(uid, null, user,
            LDAPAuthenticationController.PROVIDER_LDAP, uid);
    // Add to SecurityGroup LDAP
    SecurityGroup secGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP);
    securityManager.addIdentityToSecurityGroup(identity, secGroup);
    // Add to SecurityGroup OLATUSERS
    secGroup = securityManager.findSecurityGroupByName(Constants.GROUP_OLATUSERS);
    securityManager.addIdentityToSecurityGroup(identity, secGroup);
    log.info("Created LDAP user username::" + uid);
    return identity;
}

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

public void update() {
    NamingEnumeration attributesEnumeration = null;

    try {//  w ww.  j  ava  2 s .c  om
        attributesEnumeration = updatedAttrs.getAll();

        // find what to update
        while (attributesEnumeration.hasMore()) {
            Attribute a = (Attribute) attributesEnumeration.next();

            // if it does not exist it should be added
            if (isEmptyAttribute(a)) {
                originalAttrs.remove(a.getID());
            } else {
                // Otherwise it should be set.
                originalAttrs.put(a);
            }
        }
    } catch (NamingException e) {
        throw LdapUtils.convertLdapException(e);
    } finally {
        closeNamingEnumeration(attributesEnumeration);
    }

    // Reset the attributes to be updated
    updatedAttrs = new BasicAttributes(true);
}

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

private void writeSearchResults(final XMLBuffer xmlb, final NamingEnumeration<SearchResult> srch)
        throws NamingException {

    final ArrayList<SearchResult> sortedResults = new ArrayList<>(MAX_SORTED_RESULTS);
    final String searchBase = getPropertyAsString(SEARCHBASE);
    final String rootDn = getRootdn();

    // read all sortedResults into memory so we can guarantee ordering
    try {//from w w  w  .j  a va2  s . c o  m
        while (srch.hasMore() && (sortedResults.size() < MAX_SORTED_RESULTS)) {
            final SearchResult sr = srch.next();

            // must be done prior to sorting
            normaliseSearchDN(sr, searchBase, rootDn);
            sortedResults.add(sr);
        }
    } finally { // show what we did manage to retrieve

        sortResults(sortedResults);

        for (final SearchResult sr : sortedResults) {
            writeSearchResult(sr, xmlb);
        }
    }

    while (srch.hasMore()) { // If there's anything left ...
        final SearchResult sr = srch.next();

        normaliseSearchDN(sr, searchBase, rootDn);
        writeSearchResult(sr, xmlb);
    }
}

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

/**
 * Gets the values of a repeating attribute that may have range restriction options. If an attribute is range
 * restricted, it will appear in the attribute set with a ";range=i-j" option, where i and j indicate the start and
 * end index, and j is '*' if it is at the end.
 *
 * @param attributes//from  w  w  w .j  a v a 2s .  c om
 *            the attributes
 * @param attributeName
 *            the attribute name
 * @return the range restricted attribute
 * @throws NamingException
 *             the naming exception
 */
protected Attribute getRangeRestrictedAttribute(final Attributes attributes, final String attributeName)
        throws NamingException {
    final Attribute unrestricted = attributes.get(attributeName);
    if (unrestricted != null) {
        return unrestricted;
    }
    final NamingEnumeration<? extends Attribute> i = attributes.getAll();
    final String searchString = attributeName.toLowerCase(Locale.ENGLISH) + ';';
    while (i.hasMore()) {
        final Attribute attribute = i.next();
        if (attribute.getID().toLowerCase(Locale.ENGLISH).startsWith(searchString)) {
            return attribute;
        }
    }
    return null;
}

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)
 *///  w  w  w  .  j a  v  a 2 s  .com
@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.jasig.portal.security.provider.SimpleLdapSecurityContext.java

/**
 * Authenticates the user.//from ww  w  .j a  v a  2  s. c  o  m
 */
public synchronized void authenticate() throws PortalSecurityException {
    this.isauth = false;
    ILdapServer ldapConn;

    String propFile = ctxProperties.getProperty(LDAP_PROPERTIES_CONNECTION_NAME);
    if (propFile != null && propFile.length() > 0)
        ldapConn = LdapServices.getLdapServer(propFile);
    else
        ldapConn = LdapServices.getDefaultLdapServer();

    String creds = new String(this.myOpaqueCredentials.credentialstring);
    if (this.myPrincipal.UID != null && !this.myPrincipal.UID.trim().equals("")
            && this.myOpaqueCredentials.credentialstring != null && !creds.trim().equals("")) {
        DirContext conn = null;
        NamingEnumeration results = null;
        StringBuffer user = new StringBuffer("(");
        String first_name = null;
        String last_name = null;

        user.append(ldapConn.getUidAttribute()).append("=");
        user.append(this.myPrincipal.UID).append(")");
        if (log.isDebugEnabled())
            log.debug("SimpleLdapSecurityContext: Looking for " + user.toString());

        try {
            conn = ldapConn.getConnection();

            // set up search controls
            SearchControls searchCtls = new SearchControls();
            searchCtls.setReturningAttributes(attributes);
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            // do lookup
            if (conn != null) {
                try {
                    results = conn.search(ldapConn.getBaseDN(), user.toString(), searchCtls);
                    if (results != null) {
                        if (!results.hasMore())
                            log.error("SimpleLdapSecurityContext: user not found , " + this.myPrincipal.UID);
                        while (results != null && results.hasMore()) {
                            SearchResult entry = (SearchResult) results.next();
                            StringBuffer dnBuffer = new StringBuffer();
                            dnBuffer.append(entry.getName()).append(", ");
                            dnBuffer.append(ldapConn.getBaseDN());
                            Attributes attrs = entry.getAttributes();
                            first_name = getAttributeValue(attrs, ATTR_FIRSTNAME);
                            last_name = getAttributeValue(attrs, ATTR_LASTNAME);
                            // re-bind as user
                            conn.removeFromEnvironment(javax.naming.Context.SECURITY_PRINCIPAL);
                            conn.removeFromEnvironment(javax.naming.Context.SECURITY_CREDENTIALS);
                            conn.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, dnBuffer.toString());
                            conn.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS,
                                    this.myOpaqueCredentials.credentialstring);
                            searchCtls = new SearchControls();
                            searchCtls.setReturningAttributes(new String[0]);
                            searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);

                            String attrSearch = "(" + ldapConn.getUidAttribute() + "=*)";
                            log.debug("SimpleLdapSecurityContext: Looking in " + dnBuffer.toString() + " for "
                                    + attrSearch);
                            conn.search(dnBuffer.toString(), attrSearch, searchCtls);

                            this.isauth = true;
                            this.myPrincipal.FullName = first_name + " " + last_name;
                            log.debug("SimpleLdapSecurityContext: User " + this.myPrincipal.UID + " ("
                                    + this.myPrincipal.FullName + ") is authenticated");

                            // Since LDAP is case-insensitive with respect to uid, force
                            // user name to lower case for use by the portal
                            this.myPrincipal.UID = this.myPrincipal.UID.toLowerCase();
                        } // while (results != null && results.hasMore())
                    } else {
                        log.error("SimpleLdapSecurityContext: No such user: " + this.myPrincipal.UID);
                    }
                } catch (AuthenticationException ae) {
                    log.info("SimpleLdapSecurityContext: Password invalid for user: " + this.myPrincipal.UID);
                } catch (Exception e) {
                    log.error("SimpleLdapSecurityContext: LDAP Error with user: " + this.myPrincipal.UID + "; ",
                            e);
                    throw new PortalSecurityException("SimpleLdapSecurityContext: LDAP Error" + e
                            + " with user: " + this.myPrincipal.UID);
                } finally {
                    ldapConn.releaseConnection(conn);
                }
            } else {
                log.error("LDAP Server Connection unavalable");
            }
        } catch (final NamingException ne) {
            log.error("Error geting connection to LDAP server.", ne);
        }
    } else {
        log.error("Principal or OpaqueCredentials not initialized prior to authenticate");
    }
    // Ok...we are now ready to authenticate all of our subcontexts.
    super.authenticate();
    return;
}

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  ww.j  a v  a 2 s . co  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.nifi.ldap.tenants.LdapUserGroupProvider.java

/**
 * Reloads the tenants./*w ww . j  a  v  a 2  s  . c  om*/
 */
private void load(final ContextSource contextSource) {
    // create the ldapTemplate based on the context source. use a single source context to use the same connection
    // to support paging when configured
    final SingleContextSource singleContextSource = new SingleContextSource(contextSource.getReadOnlyContext());
    final LdapTemplate ldapTemplate = new LdapTemplate(singleContextSource);

    try {
        final List<User> userList = new ArrayList<>();
        final List<Group> groupList = new ArrayList<>();

        // group dn -> user identifiers lookup
        final Map<String, Set<String>> groupToUserIdentifierMappings = new HashMap<>();

        // user dn -> user lookup
        final Map<String, User> userLookup = new HashMap<>();

        if (performUserSearch) {
            // search controls
            final SearchControls userControls = new SearchControls();
            userControls.setSearchScope(userSearchScope.ordinal());

            // consider paging support for users
            final DirContextProcessor userProcessor;
            if (pageSize == null) {
                userProcessor = new NullDirContextProcessor();
            } else {
                userProcessor = new PagedResultsDirContextProcessor(pageSize);
            }

            // looking for objects matching the user object class
            final AndFilter userFilter = new AndFilter();
            userFilter.and(new EqualsFilter("objectClass", userObjectClass));

            // if a filter has been provided by the user, we add it to the filter
            if (StringUtils.isNotBlank(userSearchFilter)) {
                userFilter.and(new HardcodedFilter(userSearchFilter));
            }

            do {
                userList.addAll(ldapTemplate.search(userSearchBase, userFilter.encode(), userControls,
                        new AbstractContextMapper<User>() {
                            @Override
                            protected User doMapFromContext(DirContextOperations ctx) {
                                // get the user identity
                                final String identity = getUserIdentity(ctx);

                                // build the user
                                final User user = new User.Builder().identifierGenerateFromSeed(identity)
                                        .identity(identity).build();

                                // store the user for group member later
                                userLookup.put(getReferencedUserValue(ctx), user);

                                if (StringUtils.isNotBlank(userGroupNameAttribute)) {
                                    final Attribute attributeGroups = ctx.getAttributes()
                                            .get(userGroupNameAttribute);

                                    if (attributeGroups == null) {
                                        logger.warn("User group name attribute [" + userGroupNameAttribute
                                                + "] does not exist. Ignoring group membership.");
                                    } else {
                                        try {
                                            final NamingEnumeration<String> groupValues = (NamingEnumeration<String>) attributeGroups
                                                    .getAll();
                                            while (groupValues.hasMoreElements()) {
                                                // store the group -> user identifier mapping
                                                groupToUserIdentifierMappings
                                                        .computeIfAbsent(groupValues.next(),
                                                                g -> new HashSet<>())
                                                        .add(user.getIdentifier());
                                            }
                                        } catch (NamingException e) {
                                            throw new AuthorizationAccessException(
                                                    "Error while retrieving user group name attribute ["
                                                            + userIdentityAttribute + "].");
                                        }
                                    }
                                }

                                return user;
                            }
                        }, userProcessor));
            } while (hasMorePages(userProcessor));
        }

        if (performGroupSearch) {
            final SearchControls groupControls = new SearchControls();
            groupControls.setSearchScope(groupSearchScope.ordinal());

            // consider paging support for groups
            final DirContextProcessor groupProcessor;
            if (pageSize == null) {
                groupProcessor = new NullDirContextProcessor();
            } else {
                groupProcessor = new PagedResultsDirContextProcessor(pageSize);
            }

            // looking for objects matching the group object class
            AndFilter groupFilter = new AndFilter();
            groupFilter.and(new EqualsFilter("objectClass", groupObjectClass));

            // if a filter has been provided by the user, we add it to the filter
            if (StringUtils.isNotBlank(groupSearchFilter)) {
                groupFilter.and(new HardcodedFilter(groupSearchFilter));
            }

            do {
                groupList.addAll(ldapTemplate.search(groupSearchBase, groupFilter.encode(), groupControls,
                        new AbstractContextMapper<Group>() {
                            @Override
                            protected Group doMapFromContext(DirContextOperations ctx) {
                                final String dn = ctx.getDn().toString();

                                // get the group identity
                                final String name = getGroupName(ctx);

                                // get the value of this group that may associate it to users
                                final String referencedGroupValue = getReferencedGroupValue(ctx);

                                if (!StringUtils.isBlank(groupMemberAttribute)) {
                                    Attribute attributeUsers = ctx.getAttributes().get(groupMemberAttribute);
                                    if (attributeUsers == null) {
                                        logger.warn("Group member attribute [" + groupMemberAttribute
                                                + "] does not exist. Ignoring group membership.");
                                    } else {
                                        try {
                                            final NamingEnumeration<String> userValues = (NamingEnumeration<String>) attributeUsers
                                                    .getAll();
                                            while (userValues.hasMoreElements()) {
                                                final String userValue = userValues.next();

                                                if (performUserSearch) {
                                                    // find the user by it's referenced attribute and add the identifier to this group
                                                    final User user = userLookup.get(userValue);

                                                    // ensure the user is known
                                                    if (user != null) {
                                                        groupToUserIdentifierMappings
                                                                .computeIfAbsent(referencedGroupValue,
                                                                        g -> new HashSet<>())
                                                                .add(user.getIdentifier());
                                                    } else {
                                                        logger.warn(String.format(
                                                                "%s contains member %s but that user was not found while searching users. Ignoring group membership.",
                                                                name, userValue));
                                                    }
                                                } else {
                                                    // since performUserSearch is false, then the referenced group attribute must be blank... the user value must be the dn
                                                    final String userDn = userValue;

                                                    final String userIdentity;
                                                    if (useDnForUserIdentity) {
                                                        // use the user value to avoid the unnecessary look up
                                                        userIdentity = userDn;
                                                    } else {
                                                        // lookup the user to extract the user identity
                                                        userIdentity = getUserIdentity(
                                                                (DirContextAdapter) ldapTemplate
                                                                        .lookup(userDn));
                                                    }

                                                    // build the user
                                                    final User user = new User.Builder()
                                                            .identifierGenerateFromSeed(userIdentity)
                                                            .identity(userIdentity).build();

                                                    // add this user
                                                    userList.add(user);
                                                    groupToUserIdentifierMappings
                                                            .computeIfAbsent(referencedGroupValue,
                                                                    g -> new HashSet<>())
                                                            .add(user.getIdentifier());
                                                }
                                            }
                                        } catch (NamingException e) {
                                            throw new AuthorizationAccessException(
                                                    "Error while retrieving group name attribute ["
                                                            + groupNameAttribute + "].");
                                        }
                                    }
                                }

                                // build this group
                                final Group.Builder groupBuilder = new Group.Builder()
                                        .identifierGenerateFromSeed(name).name(name);

                                // add all users that were associated with this referenced group attribute
                                if (groupToUserIdentifierMappings.containsKey(referencedGroupValue)) {
                                    groupToUserIdentifierMappings.remove(referencedGroupValue)
                                            .forEach(userIdentifier -> groupBuilder.addUser(userIdentifier));
                                }

                                return groupBuilder.build();
                            }
                        }, groupProcessor));
            } while (hasMorePages(groupProcessor));

            // any remaining groupDn's were referenced by a user but not found while searching groups
            groupToUserIdentifierMappings.forEach((referencedGroupValue, userIdentifiers) -> {
                logger.warn(String.format(
                        "[%s] are members of %s but that group was not found while searching users. Ignoring group membership.",
                        StringUtils.join(userIdentifiers, ", "), referencedGroupValue));
            });
        } else {
            // since performGroupSearch is false, then the referenced user attribute must be blank... the group value must be the dn

            // groups are not being searched so lookup any groups identified while searching users
            groupToUserIdentifierMappings.forEach((groupDn, userIdentifiers) -> {
                final String groupName;
                if (useDnForGroupName) {
                    // use the dn to avoid the unnecessary look up
                    groupName = groupDn;
                } else {
                    groupName = getGroupName((DirContextAdapter) ldapTemplate.lookup(groupDn));
                }

                // define the group
                final Group.Builder groupBuilder = new Group.Builder().identifierGenerateFromSeed(groupName)
                        .name(groupName);

                // add each user
                userIdentifiers.forEach(userIdentifier -> groupBuilder.addUser(userIdentifier));

                // build the group
                groupList.add(groupBuilder.build());
            });
        }

        // record the updated tenants
        tenants.set(new TenantHolder(new HashSet<>(userList), new HashSet<>(groupList)));
    } finally {
        singleContextSource.destroy();
    }
}

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

public ModificationItem[] getModificationItems() {
    if (!updateMode) {
        return new ModificationItem[0];
    }//w  ww  .java  2 s . c  om

    List tmpList = new LinkedList();
    NamingEnumeration attributesEnumeration = null;
    try {
        attributesEnumeration = updatedAttrs.getAll();

        // find attributes that have been changed, removed or added
        while (attributesEnumeration.hasMore()) {
            Attribute oneAttr = (Attribute) attributesEnumeration.next();

            collectModifications(oneAttr, tmpList);
        }
    } catch (NamingException e) {
        throw LdapUtils.convertLdapException(e);
    } finally {
        closeNamingEnumeration(attributesEnumeration);
    }

    if (log.isDebugEnabled()) {
        log.debug("Number of modifications:" + tmpList.size());
    }

    return (ModificationItem[]) tmpList.toArray(new ModificationItem[tmpList.size()]);
}

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

/**
 * Return the LDAP schema.//from w ww . j  a v a  2 s.co  m
 *
 * @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;
}