Example usage for javax.naming NamingEnumeration nextElement

List of usage examples for javax.naming NamingEnumeration nextElement

Introduction

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

Prototype

E nextElement();

Source Link

Document

Returns the next element of this enumeration if this enumeration object has at least one more element to provide.

Usage

From source file:org.apache.cloudstack.ldap.OpenLdapUserManagerImpl.java

public LdapUser searchUser(final String basedn, final String searchString, final LdapContext context)
        throws NamingException, IOException {
    final SearchControls searchControls = new SearchControls();

    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    NamingEnumeration<SearchResult> results = context.search(basedn, searchString, searchControls);
    final List<LdapUser> users = new ArrayList<LdapUser>();
    while (results.hasMoreElements()) {
        final SearchResult result = results.nextElement();
        users.add(createUser(result));/*from w  w w .  ja va 2s .  c  o m*/
    }

    if (users.size() == 1) {
        return users.get(0);
    } else {
        throw new NamingException("No user found for basedn " + basedn + " and searchString " + searchString);
    }
}

From source file:org.jasig.portal.security.provider.SimpleLdapSecurityContext.java

/**
 * <p>Return a single value of an attribute from possibly multiple values,
 * grossly ignoring anything else.  If there are no values, then
 * return an empty string.</p>//from   w  ww  . ja va 2  s  . c o  m
 *
 * @param attrs LDAP query results
 * @param attribute LDAP attribute we are interested in
 * @return a single value of the attribute
 */
private String getAttributeValue(Attributes attrs, int attribute) throws NamingException {
    NamingEnumeration values = null;
    String aValue = "";
    if (!isAttribute(attribute))
        return aValue;
    Attribute attrib = attrs.get(attributes[attribute]);
    if (attrib != null) {
        for (values = attrib.getAll(); values.hasMoreElements();) {
            aValue = (String) values.nextElement();
            break; // take only the first attribute value
        }
    }
    return aValue;
}

From source file:org.apache.cloudstack.ldap.OpenLdapUserManagerImpl.java

@Override
public List<LdapUser> searchUsers(final String username, final LdapContext context)
        throws NamingException, IOException {

    final SearchControls searchControls = new SearchControls();

    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    String basedn = _ldapConfiguration.getBaseDn();
    if (StringUtils.isBlank(basedn)) {
        throw new IllegalArgumentException("ldap basedn is not configured");
    }/* w  ww .j a  v  a 2s.co  m*/
    byte[] cookie = null;
    int pageSize = _ldapConfiguration.getLdapPageSize();
    context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
    final List<LdapUser> users = new ArrayList<LdapUser>();
    NamingEnumeration<SearchResult> results;
    do {
        results = context.search(basedn, generateSearchFilter(username), searchControls);
        while (results.hasMoreElements()) {
            final SearchResult result = results.nextElement();
            if (!isUserDisabled(result)) {
                users.add(createUser(result));
            }
        }
        Control[] contextControls = context.getResponseControls();
        if (contextControls != null) {
            for (Control control : contextControls) {
                if (control instanceof PagedResultsResponseControl) {
                    PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
                    cookie = prrc.getCookie();
                }
            }
        } else {
            s_logger.info("No controls were sent from the ldap server");
        }
        context.setRequestControls(
                new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
    } while (cookie != null);

    return users;
}

From source file:org.apache.cloudstack.ldap.LdapUserManager.java

public List<LdapUser> getUsersInGroup(String groupName, LdapContext context) throws NamingException {
    String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute();
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(_ldapConfiguration.getScope());
    controls.setReturningAttributes(new String[] { attributeName });

    NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(),
            generateGroupSearchFilter(groupName), controls);

    final List<LdapUser> users = new ArrayList<LdapUser>();
    //Expecting only one result which has all the users
    if (result.hasMoreElements()) {
        Attribute attribute = result.nextElement().getAttributes().get(attributeName);
        NamingEnumeration<?> values = attribute.getAll();

        while (values.hasMoreElements()) {
            String userdn = String.valueOf(values.nextElement());
            try {
                users.add(getUserForDn(userdn, context));
            } catch (NamingException e) {
                s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage());
            }//from  w  w w  .  j a  v  a2s.c o m
        }
    }

    Collections.sort(users);

    return users;
}

From source file:org.apache.archiva.redback.users.ldap.LdapUserManagerTest.java

private void assertExist(DirContext context, String dn, String attribute, String value) throws NamingException {
    SearchControls ctls = new SearchControls();

    ctls.setDerefLinkFlag(true);/*from  w ww. j  a v a2 s.  c om*/
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setReturningAttributes(new String[] { "*" });

    BasicAttributes matchingAttributes = new BasicAttributes();
    matchingAttributes.put(attribute, value);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("inetOrgPerson");
    matchingAttributes.put(objectClass);

    NamingEnumeration<SearchResult> results = context.search(suffix, matchingAttributes);
    // NamingEnumeration<SearchResult> results = context.search( suffix, "(" + attribute + "=" + value + ")", ctls
    // );

    assertTrue(results.hasMoreElements());
    SearchResult result = results.nextElement();
    Attributes attrs = result.getAttributes();
    Attribute testAttr = attrs.get(attribute);
    assertEquals(value, testAttr.get());

}

From source file:org.apache.hadoop.security.LdapGroupsMapping.java

List<String> doGetGroups(String user) throws NamingException {
    List<String> groups = new ArrayList<String>();

    DirContext ctx = getDirContext();

    // Search for the user. We'll only ever need to look at the first result
    NamingEnumeration<SearchResult> results = ctx.search(baseDN, userSearchFilter, new Object[] { user },
            SEARCH_CONTROLS);/*from  ww w . j a v a 2 s .c o  m*/
    if (results.hasMoreElements()) {
        SearchResult result = results.nextElement();
        String userDn = result.getNameInNamespace();

        NamingEnumeration<SearchResult> groupResults = null;

        if (isPosix) {
            String gidNumber = null;
            String uidNumber = null;
            Attribute gidAttribute = result.getAttributes().get(posixGidAttr);
            Attribute uidAttribute = result.getAttributes().get(posixUidAttr);
            if (gidAttribute != null) {
                gidNumber = gidAttribute.get().toString();
            }
            if (uidAttribute != null) {
                uidNumber = uidAttribute.get().toString();
            }
            if (uidNumber != null && gidNumber != null) {
                groupResults = ctx.search(
                        baseDN, "(&" + groupSearchFilter + "(|(" + posixGidAttr + "={0})" + "("
                                + groupMemberAttr + "={1})))",
                        new Object[] { gidNumber, uidNumber }, SEARCH_CONTROLS);
            }
        } else {
            groupResults = ctx.search(baseDN, "(&" + groupSearchFilter + "(" + groupMemberAttr + "={0}))",
                    new Object[] { userDn }, SEARCH_CONTROLS);
        }
        if (groupResults != null) {
            while (groupResults.hasMoreElements()) {
                SearchResult groupResult = groupResults.nextElement();
                Attribute groupName = groupResult.getAttributes().get(groupNameAttr);
                groups.add(groupName.get().toString());
            }
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("doGetGroups(" + user + ") return " + groups);
    }
    return groups;
}

From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java

/**
 * @see org.apache.archiva.redback.users.ldap.ctl.LdapController#getUser(String, javax.naming.directory.DirContext)
 *//*w  w w .  j  a  v  a  2s .c  o m*/
public LdapUser getUser(String username, DirContext context) throws LdapControllerException, MappingException {

    log.debug("Searching for user: {}", username);

    LdapUserQuery query = new LdapUserQuery();
    query.setUsername(username);

    NamingEnumeration<SearchResult> result = null;
    try {
        result = searchUsers(context, null, query);

        if (result.hasMoreElements()) {
            SearchResult next = result.nextElement();

            log.info("Found user: {}", username);

            return mapper.getUser(next.getAttributes());
        } else {
            return null;
        }
    } catch (NamingException e) {
        String message = "Failed to retrieve information for user: " + username;

        throw new LdapControllerException(message, e);
    } finally {
        if (result != null) {
            try {
                result.close();
            } catch (NamingException e) {
                log.warn("failed to close search results", e);
            }
        }
    }
}

From source file:org.apache.cloudstack.ldap.OpenLdapUserManagerImpl.java

@Override
public List<LdapUser> getUsersInGroup(String groupName, LdapContext context) throws NamingException {
    String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute();
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(_ldapConfiguration.getScope());
    controls.setReturningAttributes(new String[] { attributeName });

    NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(),
            generateGroupSearchFilter(groupName), controls);

    final List<LdapUser> users = new ArrayList<LdapUser>();
    //Expecting only one result which has all the users
    if (result.hasMoreElements()) {
        Attribute attribute = result.nextElement().getAttributes().get(attributeName);
        NamingEnumeration<?> values = attribute.getAll();

        while (values.hasMoreElements()) {
            String userdn = String.valueOf(values.nextElement());
            try {
                users.add(getUserForDn(userdn, context));
            } catch (NamingException e) {
                s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage());
            }/*from w  w  w . j ava2s . c  o m*/
        }
    }

    Collections.sort(users);

    return users;
}

From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java

/**
 * @see org.apache.archiva.redback.users.ldap.ctl.LdapController#getUsers(javax.naming.directory.DirContext)
 *//*from w ww.  ja  v  a 2s . co m*/
public Collection<User> getUsers(DirContext context) throws LdapControllerException, MappingException {
    NamingEnumeration<SearchResult> results = null;
    try {
        results = searchUsers(context, null, null);
        Set<User> users = new LinkedHashSet<User>();

        while (results.hasMoreElements()) {
            SearchResult result = results.nextElement();

            users.add(mapper.getUser(result.getAttributes()));
        }

        return users;
    } catch (NamingException e) {
        String message = "Failed to retrieve ldap information for users.";

        throw new LdapControllerException(message, e);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (NamingException e) {
                log.warn("failed to close search results", e);
            }
        }
    }
}

From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java

/**
 * @see org.apache.archiva.redback.users.ldap.ctl.LdapController#getUsersByQuery(org.apache.archiva.redback.users.ldap.LdapUserQuery, javax.naming.directory.DirContext)
 *///ww w  . j a  v a  2  s  .c o  m
public List<User> getUsersByQuery(LdapUserQuery query, DirContext context)
        throws LdapControllerException, MappingException {
    NamingEnumeration<SearchResult> results = null;
    try {
        results = searchUsers(context, null, query);
        List<User> users = new LinkedList<User>();

        while (results.hasMoreElements()) {
            SearchResult result = results.nextElement();

            users.add(mapper.getUser(result.getAttributes()));
        }

        return users;
    } catch (NamingException e) {
        String message = "Failed to retrieve ldap information for users.";

        throw new LdapControllerException(message, e);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (NamingException e) {
                log.warn("failed to close search results", e);
            }
        }
    }
}