Example usage for javax.naming NamingEnumeration close

List of usage examples for javax.naming NamingEnumeration close

Introduction

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

Prototype

public void close() throws NamingException;

Source Link

Document

Closes this enumeration.

Usage

From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java

private void getGroups(UserGroupSink sink) throws Throwable {
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
    long highestdeltaSyncGroupTime = deltaSyncGroupTime;
    try {//ww w. j  a v a 2  s .c om
        createLdapContext();
        int total;
        // Activate paged results
        if (pagedResultsEnabled) {
            ldapContext.setRequestControls(
                    new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) });
        }
        extendedGroupSearchFilter = "(objectclass=" + groupObjectClass + ")";
        if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) {
            String customFilter = groupSearchFilter.trim();
            if (!customFilter.startsWith("(")) {
                customFilter = "(" + customFilter + ")";
            }
            extendedGroupSearchFilter = extendedGroupSearchFilter + customFilter;
        }

        extendedAllGroupsSearchFilter = "(&" + extendedGroupSearchFilter + "(|(uSNChanged>="
                + deltaSyncGroupTime + ")(modifyTimestamp>=" + deltaSyncGroupTimeStamp + "Z)))";

        LOG.info("extendedAllGroupsSearchFilter = " + extendedAllGroupsSearchFilter);
        for (int ou = 0; ou < groupSearchBase.length; ou++) {
            byte[] cookie = null;
            int counter = 0;
            try {
                int paged = 0;
                do {
                    groupSearchResultEnum = ldapContext.search(groupSearchBase[ou],
                            extendedAllGroupsSearchFilter, groupSearchControls);
                    while (groupSearchResultEnum.hasMore()) {
                        final SearchResult groupEntry = groupSearchResultEnum.next();
                        if (groupEntry == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info("groupEntry null, skipping sync for the entry");
                            }
                            continue;
                        }
                        counter++;
                        Attribute groupNameAttr = groupEntry.getAttributes().get(groupNameAttribute);
                        if (groupNameAttr == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info(groupNameAttribute + " empty for entry "
                                        + groupEntry.getNameInNamespace() + ", skipping sync");
                            }
                            continue;
                        }
                        String gName = (String) groupNameAttr.get();
                        String transformGroupName = groupNameTransform(gName);
                        // If group based search is enabled, then
                        // update the group name to ranger admin
                        // check for group members and populate userInfo object with user's full name and group mapping
                        if (groupSearchFirstEnabled) {
                            LOG.debug("Update Ranger admin with " + transformGroupName);
                            sink.addOrUpdateGroup(transformGroupName);
                        }
                        Attribute timeStampAttr = groupEntry.getAttributes().get("uSNChanged");
                        if (timeStampAttr != null) {
                            String uSNChangedVal = (String) timeStampAttr.get();
                            long currentDeltaSyncTime = Long.parseLong(uSNChangedVal);
                            if (currentDeltaSyncTime > highestdeltaSyncGroupTime) {
                                highestdeltaSyncGroupTime = currentDeltaSyncTime;
                            }
                        } else {
                            timeStampAttr = groupEntry.getAttributes().get("modifytimestamp");
                            if (timeStampAttr != null) {
                                String timeStampVal = (String) timeStampAttr.get();
                                Date parseDate = dateFormat.parse(timeStampVal);
                                long currentDeltaSyncTime = parseDate.getTime();
                                LOG.info("timeStampVal = " + timeStampVal + "and currentDeltaSyncTime = "
                                        + currentDeltaSyncTime);
                                if (currentDeltaSyncTime > highestdeltaSyncGroupTime) {
                                    highestdeltaSyncGroupTime = currentDeltaSyncTime;
                                    deltaSyncGroupTimeStamp = timeStampVal;
                                }
                            }
                        }
                        Attribute groupMemberAttr = groupEntry.getAttributes().get(groupMemberAttributeName);
                        int userCount = 0;
                        if (groupMemberAttr == null || groupMemberAttr.size() <= 0) {
                            LOG.info("No members available for " + gName);
                            continue;
                        }

                        NamingEnumeration<?> userEnum = groupMemberAttr.getAll();
                        while (userEnum.hasMore()) {
                            String originalUserFullName = (String) userEnum.next();
                            if (originalUserFullName == null || originalUserFullName.trim().isEmpty()) {
                                continue;
                            }
                            userCount++;
                            String userName = getShortUserName(originalUserFullName);
                            originalUserFullName = originalUserFullName.toLowerCase();
                            if (groupSearchFirstEnabled && !userSearchEnabled) {
                                String transformUserName = userNameTransform(userName);
                                try {
                                    sink.addOrUpdateUser(transformUserName);
                                } catch (Throwable t) {
                                    LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage()
                                            + ", for user: " + transformUserName);
                                }
                                userNameMap.put(originalUserFullName, transformUserName);
                            }
                            //System.out.println("Adding " + userNameMap.get(originalUserFullName) + " and fullname = " + originalUserFullName + " to " + gName);
                            if (userNameMap.get(originalUserFullName) != null) {
                                groupUserTable.put(gName, originalUserFullName,
                                        userNameMap.get(originalUserFullName));
                            } else {
                                groupUserTable.put(gName, originalUserFullName, originalUserFullName);
                            }
                            groupNameMap.put(groupEntry.getNameInNamespace().toLowerCase(), gName);
                        }
                        LOG.info("No. of members in the group " + gName + " = " + userCount);
                    }
                    // Examine the paged results control response
                    Control[] controls = ldapContext.getResponseControls();
                    if (controls != null) {
                        for (int i = 0; i < controls.length; i++) {
                            if (controls[i] instanceof PagedResultsResponseControl) {
                                PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                                total = prrc.getResultSize();
                                if (total != 0) {
                                    LOG.debug("END-OF-PAGE total : " + total);
                                } else {
                                    LOG.debug("END-OF-PAGE total : unknown");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOG.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    if (pagedResultsEnabled) {
                        LOG.debug(String.format("Fetched paged results round: %s", ++paged));
                        ldapContext.setRequestControls(new Control[] {
                                new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) });
                    }
                } while (cookie != null);
                LOG.info("LdapDeltaUserGroupBuilder.getGroups() completed with group count: " + counter);
            } catch (Exception t) {
                LOG.error("LdapDeltaUserGroupBuilder.getGroups() failed with exception: " + t);
                LOG.info("LdapDeltaUserGroupBuilder.getGroups() group count: " + counter);
            }
        }

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

    if (groupHierarchyLevels > 0) {
        LOG.debug("deltaSyncGroupTime = " + deltaSyncGroupTime);
        if (deltaSyncGroupTime > 0) {
            LOG.info(
                    "LdapDeltaUserGroupBuilder.getGroups(): Going through group hierarchy for nested group evaluation for deltasync");
            goUpGroupHierarchyLdap(groupNameMap.keySet(), groupHierarchyLevels - 1);
        }
    }

    if (deltaSyncGroupTime < highestdeltaSyncGroupTime) {
        // Incrementing highestdeltaSyncGroupTime (for AD) in order to avoid search record repetition for next sync cycle.
        deltaSyncGroupTime = highestdeltaSyncGroupTime + 1;
        // Incrementing the highest timestamp value (for OpenLdap) with 1min in order to avoid search record repetition for next sync cycle.
        deltaSyncGroupTimeStamp = dateFormat.format(new Date(highestdeltaSyncGroupTime + 60000l));
    }
}

From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java

private void goUpGroupHierarchyLdap(Set<String> groupDNs, int groupHierarchyLevels) throws Throwable {
    if (groupHierarchyLevels <= 0 || groupDNs.isEmpty()) {
        return;//w w  w .  j a v a 2 s .c  o m
    }
    Set<String> nextLevelGroups = new HashSet<String>();

    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    try {
        createLdapContext();
        int total;
        // Activate paged results
        if (pagedResultsEnabled) {
            ldapContext.setRequestControls(
                    new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) });
        }
        String groupFilter = "(&(objectclass=" + groupObjectClass + ")";
        if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) {
            String customFilter = groupSearchFilter.trim();
            if (!customFilter.startsWith("(")) {
                customFilter = "(" + customFilter + ")";
            }
            groupFilter += customFilter + "(|";
        }
        StringBuilder filter = new StringBuilder();

        for (String groupDN : groupDNs) {
            filter.append("(").append(groupMemberAttributeName).append("=").append(groupDN).append(")");
        }
        filter.append("))");
        groupFilter += filter;

        LOG.info("extendedAllGroupsSearchFilter = " + groupFilter);
        for (int ou = 0; ou < groupSearchBase.length; ou++) {
            byte[] cookie = null;
            int counter = 0;
            try {
                do {
                    groupSearchResultEnum = ldapContext.search(groupSearchBase[ou], groupFilter,
                            groupSearchControls);
                    while (groupSearchResultEnum.hasMore()) {
                        final SearchResult groupEntry = groupSearchResultEnum.next();
                        if (groupEntry == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info("groupEntry null, skipping sync for the entry");
                            }
                            continue;
                        }
                        counter++;
                        Attribute groupNameAttr = groupEntry.getAttributes().get(groupNameAttribute);
                        if (groupNameAttr == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info(groupNameAttribute + " empty for entry "
                                        + groupEntry.getNameInNamespace() + ", skipping sync");
                            }
                            continue;
                        }
                        nextLevelGroups.add(groupEntry.getNameInNamespace());
                        String gName = (String) groupNameAttr.get();

                        Attribute groupMemberAttr = groupEntry.getAttributes().get(groupMemberAttributeName);
                        int userCount = 0;
                        if (groupMemberAttr == null || groupMemberAttr.size() <= 0) {
                            LOG.info("No members available for " + gName);
                            continue;
                        }

                        NamingEnumeration<?> userEnum = groupMemberAttr.getAll();
                        while (userEnum.hasMore()) {
                            String originalUserFullName = (String) userEnum.next();
                            if (originalUserFullName == null || originalUserFullName.trim().isEmpty()) {
                                continue;
                            }
                            userCount++;
                            originalUserFullName = originalUserFullName.toLowerCase();
                            if (userNameMap.get(originalUserFullName) != null) {
                                groupUserTable.put(gName, originalUserFullName,
                                        userNameMap.get(originalUserFullName));
                            } else {
                                groupUserTable.put(gName, originalUserFullName, originalUserFullName);
                            }
                            groupNameMap.put(groupEntry.getNameInNamespace().toLowerCase(), gName);
                        }
                        LOG.info("No. of members in the group " + gName + " = " + userCount);
                    }
                    // Examine the paged results control response
                    Control[] controls = ldapContext.getResponseControls();
                    if (controls != null) {
                        for (int i = 0; i < controls.length; i++) {
                            if (controls[i] instanceof PagedResultsResponseControl) {
                                PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                                total = prrc.getResultSize();
                                if (total != 0) {
                                    LOG.debug("END-OF-PAGE total : " + total);
                                } else {
                                    LOG.debug("END-OF-PAGE total : unknown");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOG.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    if (pagedResultsEnabled) {
                        ldapContext.setRequestControls(new Control[] {
                                new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) });
                    }
                } while (cookie != null);
                LOG.info("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() completed with group count: "
                        + counter);
            } catch (RuntimeException re) {
                LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with runtime exception: ",
                        re);
                throw re;
            } catch (Exception t) {
                LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with exception: ", t);
                LOG.info("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() group count: " + counter);
            }
        }

    } catch (RuntimeException re) {
        LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with exception: ", re);
        throw re;
    } finally {
        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
        closeLdapContext();
    }
    goUpGroupHierarchyLdap(nextLevelGroups, groupHierarchyLevels - 1);
}

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 {/*  ww  w  .j av  a2 s  .  co 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.apache.zeppelin.realm.LdapRealm.java

private void addRoleIfMember(final String userDn, final SearchResult group, final Set<String> roleNames,
        final Set<String> groupNames, final LdapContextFactory ldapContextFactory) throws NamingException {
    NamingEnumeration<? extends Attribute> attributeEnum = null;
    NamingEnumeration<?> ne = null;
    try {//from  w  w w .j a  v  a  2  s  . co m
        LdapName userLdapDn = new LdapName(userDn);
        Attribute attribute = group.getAttributes().get(getGroupIdAttribute());
        String groupName = attribute.get().toString();

        attributeEnum = group.getAttributes().getAll();
        while (attributeEnum.hasMore()) {
            final Attribute attr = attributeEnum.next();
            if (!memberAttribute.equalsIgnoreCase(attr.getID())) {
                continue;
            }
            ne = attr.getAll();
            while (ne.hasMore()) {
                String attrValue = ne.next().toString();
                if (memberAttribute.equalsIgnoreCase(MEMBER_URL)) {
                    boolean dynamicGroupMember = isUserMemberOfDynamicGroup(userLdapDn, attrValue,
                            ldapContextFactory);
                    if (dynamicGroupMember) {
                        groupNames.add(groupName);
                        String roleName = roleNameFor(groupName);
                        if (roleName != null) {
                            roleNames.add(roleName);
                        } else {
                            roleNames.add(groupName);
                        }
                    }
                } else {
                    // posix groups' members don' include the entire dn
                    if (groupObjectClass.equalsIgnoreCase(POSIX_GROUP)) {
                        attrValue = memberDn(attrValue);
                    }
                    if (userLdapDn.equals(new LdapName(attrValue))) {
                        groupNames.add(groupName);
                        String roleName = roleNameFor(groupName);
                        if (roleName != null) {
                            roleNames.add(roleName);
                        } else {
                            roleNames.add(groupName);
                        }
                        break;
                    }
                }
            }
        }
    } finally {
        try {
            if (attributeEnum != null) {
                attributeEnum.close();
            }
        } finally {
            if (ne != null) {
                ne.close();
            }
        }
    }
}

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

boolean isUserMemberOfDynamicGroup(LdapName userLdapDn, String memberUrl,
        final LdapContextFactory ldapContextFactory) throws NamingException {
    // ldap://host:port/dn?attributes?scope?filter?extensions
    if (memberUrl == null) {
        return false;
    }/*from   w w  w  . j a v a 2s  .c o m*/
    String[] tokens = memberUrl.split("\\?");
    if (tokens.length < 4) {
        return false;
    }

    String searchBaseString = tokens[0].substring(tokens[0].lastIndexOf("/") + 1);
    String searchScope = tokens[2];
    String searchFilter = tokens[3];

    LdapName searchBaseDn = new LdapName(searchBaseString);

    // do scope test
    if (searchScope.equalsIgnoreCase("base")) {
        log.debug("DynamicGroup SearchScope base");
        return false;
    }
    if (!userLdapDn.toString().endsWith(searchBaseDn.toString())) {
        return false;
    }
    if (searchScope.equalsIgnoreCase("one") && (userLdapDn.size() != searchBaseDn.size() - 1)) {
        log.debug("DynamicGroup SearchScope one");
        return false;
    }
    // search for the filter, substituting base with userDn
    // search for base_dn=userDn, scope=base, filter=filter
    LdapContext systemLdapCtx = null;
    systemLdapCtx = ldapContextFactory.getSystemLdapContext();
    boolean member = false;
    NamingEnumeration<SearchResult> searchResultEnum = null;
    try {
        searchResultEnum = systemLdapCtx.search(userLdapDn, searchFilter,
                searchScope.equalsIgnoreCase("sub") ? SUBTREE_SCOPE : ONELEVEL_SCOPE);
        if (searchResultEnum.hasMore()) {
            return true;
        }
    } finally {
        try {
            if (searchResultEnum != null) {
                searchResultEnum.close();
            }
        } finally {
            LdapUtils.closeContext(systemLdapCtx);
        }
    }
    return member;
}

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 av  a  2s  .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.apereo.portal.groups.ldap.LDAPGroupStore.java

protected void processLdapResults(NamingEnumeration results, ArrayList keys) {
    //long time1 = System.currentTimeMillis();
    //long casting=0;
    //long getting=0;
    //long setting=0;
    //long looping=0;
    //long loop1=System.currentTimeMillis();
    try {//from   w w  w  .  j a va  2  s. c  o m
        while (results.hasMore()) {
            //long loop2 = System.currentTimeMillis();
            //long cast1=System.currentTimeMillis();
            //looping=looping+loop2-loop1;
            SearchResult result = (SearchResult) results.next();
            //long cast2 = System.currentTimeMillis();
            //long get1 = System.currentTimeMillis();
            Attributes ldapattribs = result.getAttributes();
            //long get2 = System.currentTimeMillis();
            //long set1 = System.currentTimeMillis();
            Attribute attrib = ldapattribs.get(keyfield);
            if (attrib != null) {
                keys.add(String.valueOf(attrib.get()).toLowerCase());
            }
            //long set2 = System.currentTimeMillis();
            //loop1=System.currentTimeMillis();
            //casting=casting+cast2-cast1;
            //setting=setting+set2-set1;
            //getting=getting+get2-get1;
        }
    } catch (NamingException nex) {
        log.error("LDAPGroupStore: error processing results", nex);
    } finally {
        try {
            results.close();
        } catch (Exception e) {
        }
    }
    //long time5 = System.currentTimeMillis();
    //System.out.println("Result processing took "+(time5-time1)+": "+getting+" for getting, "
    //  +setting+" for setting, "+casting+" for casting, "+looping+" for looping,"
    //  +(time5-loop1)+" for closing");
}

From source file:org.ballerinalang.auth.ldap.util.LdapUtils.java

/**
 * Closes the used NamingEnumerations to free up resources.
 *
 * @param namingEnumeration enumeration needs to be closed
 * @throws NamingException if a naming exception is encountered
 *//*from   w w  w .  jav a  2s.  c om*/
public static void closeNamingEnumeration(NamingEnumeration<?> namingEnumeration) throws NamingException {
    if (namingEnumeration != null) {
        namingEnumeration.close();
    }
}

From source file:org.beangle.security.ldap.connect.SimpleLdapUserStore.java

public String getUserDN(String uid) {
    DirContext ctx = getContext();
    if (ctx == null)
        return null;
    String result = null;//w w w .  j  a v  a  2s.  c  o  m
    String condition = StrUtils.concat(uidName, "=", uid);
    try {
        String attrList[] = { uidName };
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(2);
        constraints.setReturningAttributes(attrList);
        NamingEnumeration<SearchResult> results = ctx.search(base, condition, constraints);
        if (results.hasMore()) {
            SearchResult si = results.next();
            result = StrUtils.concat(si.getName(), ",", base);
        }
        results.close();
        results = null;
    } catch (Throwable e) {
        logger.error("Ldap search error,uid=" + uid, e);
    }
    return result;
}

From source file:org.codehaus.plexus.redback.authentication.ldap.LdapBindAuthenticator.java

private void closeNamingEnumeration(NamingEnumeration<SearchResult> results) {
    try {//from w  w w .  j a  v  a2s  .  c  om
        if (results != null) {
            results.close();
        }
    } catch (NamingException e) {
        log.warn("skip exception closing naming search result " + e.getMessage());
    }
}