Example usage for javax.naming NamingEnumeration hasMoreElements

List of usage examples for javax.naming NamingEnumeration hasMoreElements

Introduction

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

Prototype

boolean hasMoreElements();

Source Link

Document

Tests if this enumeration contains more elements.

Usage

From source file:com.globalsight.everest.usermgr.UserLdapHelper.java

static Vector getNamesVectorFromSearchResults(NamingEnumeration p_SearchResults) throws NamingException {
    Vector userNames = new Vector();

    while (p_SearchResults.hasMoreElements()) {
        /* Next directory entry */
        Object searchResultObj = p_SearchResults.nextElement();
        if (searchResultObj instanceof SearchResult) {
            SearchResult tempSearchResult = (SearchResult) searchResultObj;
            Attributes entry = tempSearchResult.getAttributes();
            String userName = getSingleAttributeValue(entry.get(LDAP_ATTR_USER_NAME));
            userNames.addElement(userName);
        }//  w w w.  j  a  v  a 2  s. com
    }

    p_SearchResults.close();

    return userNames;
}

From source file:com.globalsight.everest.usermgr.UserLdapHelper.java

/**
 * Generates a collection of UserInfo objects from a NamingEnumeration after
 * a search is carried out.//  w  w w .  j  a v a2 s  .co  m
 */
static Vector getUserInfosFromSearchResults(NamingEnumeration p_SearchResults) throws NamingException {

    Vector userInfoList = new Vector();
    while (p_SearchResults.hasMoreElements()) {
        /* Next directory entry */
        Object searchResultObj = p_SearchResults.nextElement();
        if (searchResultObj instanceof SearchResult) {
            SearchResult tempSearchResult = (SearchResult) searchResultObj;
            Attributes entry = tempSearchResult.getAttributes();
            userInfoList.addElement(getUserInfoFromLDAPEntry(entry));
        }
    }
    p_SearchResults.close();

    return userInfoList;
}

From source file:com.globalsight.everest.usermgr.UserLdapHelper.java

/**
 * Generates a collection of User objects from a NamingEnumeration after a
 * search is carried out.//from  w w  w .  j  ava 2  s . c  o m
 */
static Vector<User> getUsersFromSearchResults(NamingEnumeration p_SearchResults) throws NamingException {

    Vector<User> userList = new Vector<User>();
    while (p_SearchResults.hasMoreElements()) {
        /* Next directory entry */
        Object searchResultObj = p_SearchResults.nextElement();
        if (searchResultObj instanceof SearchResult) {
            SearchResult tempSearchResult = (SearchResult) searchResultObj;
            Attributes entry = tempSearchResult.getAttributes();
            userList.addElement(getUserFromLDAPEntry(entry));
        }
    }

    p_SearchResults.close();
    return userList;
}

From source file:org.picketlink.idm.performance.TestBase.java

public void removeContext(Context mainCtx, String name) throws Exception {
    Context deleteCtx = (Context) mainCtx.lookup(name);
    NamingEnumeration subDirs = mainCtx.listBindings(name);

    while (subDirs.hasMoreElements()) {
        Binding binding = (Binding) subDirs.nextElement();
        String subName = binding.getName();

        removeContext(deleteCtx, subName);
    }/*from   w  w w.j a  v a  2s.  com*/

    mainCtx.unbind(name);
}

From source file:info.jtrac.acegi.JtracLdapAuthenticationProvider.java

/**
 * displayName and mail are returned always, the map allows us to support
 * getting arbitrary properties in the future, hopefully
 *///from w w w  . ja  v  a 2  s. c  o  m
public Map<String, String> bind(String loginName, String password) throws Exception {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    LdapContext ctx = null;
    if (activeDirectoryDomain != null) { // we are using Active Directory            
        Control[] controls = new Control[] { control };
        ctx = new InitialLdapContext(env, controls);
        logger.debug("Active Directory LDAP context initialized");
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, activeDirectoryDomain + "\\" + loginName);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        // javax.naming.AuthenticationException
        ctx.reconnect(controls);
        logger.debug("Active Directory LDAP bind successful");
    } else { // standard LDAP            
        env.put(Context.SECURITY_PRINCIPAL, searchKey + "=" + loginName + "," + searchBase);
        env.put(Context.SECURITY_CREDENTIALS, password);
        ctx = new InitialLdapContext(env, null);
        logger.debug("Standard LDAP bind successful");
    }
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(returningAttributes);
    NamingEnumeration results = ctx.search(searchBase, searchKey + "=" + loginName, sc);
    while (results.hasMoreElements()) {
        SearchResult sr = (SearchResult) results.next();
        Attributes attrs = sr.getAttributes();
        logger.debug("attributes: " + attrs);
        Map<String, String> map = new HashMap<String, String>(returningAttributes.length);
        for (String key : returningAttributes) {
            Attribute attr = attrs.get(key);
            if (attr != null) {
                map.put(key, (String) attr.get());
            }
        }
        return map; // there should be only one anyway            
    }
    // if we reached here, there was no search result
    throw new Exception("no results returned from ldap");
}

From source file:com.healthcit.cacure.businessdelegates.LdapUserManager.java

public Set<UserCredentials> loadUsersByRole(RoleCode roleCode) {
    Role role = roleDao.getByRoleCode(roleCode);

    String groupFilter = createGroupFilter(roleCode);

    Set<UserCredentials> userCredentials = new HashSet<UserCredentials>();

    try {/*ww  w  . j a v  a  2 s.c  om*/
        Attributes attrs = contextSource.getReadOnlyContext().getAttributes(groupFilter);
        Attribute memAttr = attrs.get(Constants.LDAP_GROUP_UNIQUE_MEMBER);

        NamingEnumeration<?> elements = memAttr.getAll();
        while (elements.hasMoreElements()) {
            DistinguishedName dn = new DistinguishedName((String) elements.nextElement());
            String userName = dn.getValue(Constants.LDAP_UID);
            DirContextOperations dir = searchForUser(userName);
            String email = dir.getStringAttribute("mail");
            UserCredentials user = getUserFromDatabase(userName);
            user.setEmail(email);
            userCredentials.add(user);
        }

    } catch (NamingException e) {
        log.error(e.getMessage());
    }

    return userCredentials;
}

From source file:com.globalsight.everest.usermgr.UserLdapHelper.java

/**
 * Get the company names from a NamingEnumeration
 *//*w w  w  .  j  a  v a  2 s  .  c o m*/
static String[] getCompanyNamesFromSearchResults(NamingEnumeration p_searchResults) throws NamingException {

    // use a set so duplicates are not saved
    Set companyNames = new TreeSet();

    while (p_searchResults.hasMoreElements()) {

        String cName = null;
        Object searchResultObj = p_searchResults.nextElement();
        if (searchResultObj instanceof SearchResult) {
            SearchResult tempSearchResult = (SearchResult) searchResultObj;
            Attributes entry = tempSearchResult.getAttributes();
            cName = getSingleAttributeValue(entry.get(LDAP_ATTR_COMPANY));
        }

        if (cName != null && cName.trim().length() > 0) {
            // adds it to the set
            // if it already exists just returns (NOP)
            companyNames.add(cName);
        }
    }
    p_searchResults.close();

    String[] cns = new String[companyNames.size()];
    return (String[]) companyNames.toArray(cns);
}

From source file:eu.uqasar.util.ldap.LdapManager.java

public List<LdapUser> getUsersFromGroup(int maximum, LdapGroup group) throws NamingException {
    List<LdapUser> users = new ArrayList<>();
    final String mapping = settings.getGroupMemberMapping();
    javax.naming.directory.Attribute members = group.getMappedAttribute(mapping);
    if (members == null) {
        return users;
    }/* w  w w.j  av  a2  s .c  om*/
    NamingEnumeration<?> results = members.getAll();
    while (results.hasMoreElements() && users.size() < maximum) {
        try {
            final String userDN = (String) results.next();
            LdapUser user = getUserByDNAndFilter(userDN, settings.getUserFilter());
            if (user != null) {
                users.add(user);
            }
        } catch (LdapReferralException ex) {
            logger.warn(ex.getMessage(), ex);
        }
    }
    Collections.sort(users, new LdapUserComparator());
    return users;
}

From source file:eu.uqasar.util.ldap.LdapManager.java

private int countLdapEntities(int maximum, final String baseDN, final String preferredFilter)
        throws NamingException {
    if (maximum <= 0) {
        return 0;
    }//from w ww .  ja  v a2  s  .co m
    int count = 0;
    NamingEnumeration<SearchResult> results = searchLDAP(baseDN, preferredFilter);
    while (results.hasMoreElements() && count < maximum) {
        try {
            results.next();
            count++;
        } catch (LdapReferralException ex) {
            logger.warn(ex.getMessage(), ex);
        }
    }
    return count;
}

From source file:eu.uqasar.util.ldap.LdapManager.java

private <T extends LdapEntity> List<T> getLdapEntities(int maximum, final String baseDN,
        final String preferredFilter, Class<T> clazz, Comparator<T> comparator) throws NamingException {
    if (maximum <= 0) {
        return Collections.emptyList();
    }/*from www .ja  v  a2s . c o  m*/
    List<T> entities = new ArrayList<>();
    NamingEnumeration<SearchResult> results = searchLDAP(baseDN, preferredFilter);
    while (results.hasMoreElements() && entities.size() < maximum) {
        try {
            SearchResult group = results.next();
            Constructor<T> constructor = clazz.getConstructor(Attributes.class, LdapSettings.class);
            T entity = constructor.newInstance(group.getAttributes(), settings);
            entities.add(entity);
        } catch (LdapReferralException ex) {
            logger.warn(ex.getMessage(), ex);
        } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException
                | IllegalArgumentException | InvocationTargetException ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
    Collections.sort(entities, comparator);
    return entities;
}