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:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

/**
* Tries to find the value of the given attribute. Note that this method
* only uses the first search result.//from w w  w .  jav  a2  s  .c  o  m
* 
* @param username
*            a username
* @param attrName
*            the name of the attribute to find
* @return the value of the attribute, or an empty string
*/
public String getAttr(String username, String attrName) {
    String val = "";
    try {
        DirContext dc = new InitialDirContext(env);
        NamingEnumeration<SearchResult> ne = performLdapSearch(username, dc);

        if (ne.hasMore()) {
            val = getAttrValue(attrName, ne.next());
        }

        ne.close();
        dc.close();
    } catch (NamingException ne) {
        log.warn("Failed LDAP lookup getAttr", ne);
        log.warn("username:", username);
        log.warn("attrName:", attrName);
    }

    log.trace(String.format("getAttr search result: %s", val));
    return val;
}

From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java

/**
 * //from   w  w  w  . j  a  va 2s  .  c o  m
 * @see edu.internet2.middleware.subject.provider.BaseSourceAdapter#search(java.lang.String)
 */
@Override
public Set<Subject> search(String searchValue) {
    Set<Subject> result = new HashSet<Subject>();
    Search search = getSearch("search");
    if (search == null) {
        log.error("searchType: \"search\" not defined.");
        return result;
    }
    String[] attributeNames = { this.nameAttributeName, this.subjectIDAttributeName,
            this.descriptionAttributeName };
    NamingEnumeration ldapResults = getLdapResults(search, searchValue, attributeNames);
    if (ldapResults == null) {
        return result;
    }
    try {
        while (ldapResults.hasMore()) {
            SearchResult si = (SearchResult) ldapResults.next();
            Attributes attributes1 = si.getAttributes();
            Subject subject = createSubject(attributes1);
            result.add(subject);
        }
    } catch (NamingException ex) {
        log.error("LDAP Naming Except: " + ex.getMessage(), ex);
    }

    return result;
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

private String performRoleSearch(String location, String roleName) {
    String val = null;
    try {/*  ww w .  j a  va  2  s.com*/

        DirContext dc = new InitialDirContext(env);
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);

        //String filter = "(" + filterPrefix + roleName + ")";
        NamingEnumeration<SearchResult> ne = dc.search(location, roleName, sc);
        if (ne.hasMore()) {
            val = getAttrValue("memberOf", ne.next());
        }
        ne.close();
        dc.close();
    } catch (NamingException ne) {
        log.warn("Failed LDAP lookup getAttr", ne);
        log.warn("roleName:", roleName);
        log.warn("location:", location);
    }
    return val;

}

From source file:org.tolven.gatekeeper.bean.LdapBean.java

private List<TolvenPerson> findTolvenPerson(LdapContext ctx, String peopleBaseName, String principalLdapName,
        String realm, int maxResults, int timeLimit) {
    NamingEnumeration<SearchResult> namingEnum = null;
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setCountLimit(maxResults);/*from w  w w.java2s .c o m*/
    ctls.setTimeLimit(timeLimit);
    ArrayList<TolvenPerson> searchResults = new ArrayList<TolvenPerson>(10);
    try {
        namingEnum = ctx.search(peopleBaseName, principalLdapName, ctls);
        while (namingEnum.hasMore()) {
            SearchResult rslt = namingEnum.next();
            searchResults.add(new TolvenPerson(rslt));
        }
    } catch (GatekeeperSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new RuntimeException(
                "Could not search for TolvenPerson: " + principalLdapName + " in realm: " + realm + ": ", ex);
    }
    return searchResults;
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Get all ldap groups//  ww w . j a va 2 s.  c  o  m
 * 
 * @param siteBean
 * @param baseDnGroup
 * @param ldapFilterGroups
 * @param groupAttributeName
 * @param groupToMemberReferencesMap
 * @return
 * @throws Exception
 */
public static Map<String, TPersonBean> getLdapGroupsByList(String baseURL, TSiteBean siteBean,
        String groupAttributeName, Map<String, List<String>> groupToMemberReferencesMap,
        Map<String, String> groups) throws Exception {
    HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>();
    String bindDN = siteBean.getLdapBindDN();
    String bindPassword = siteBean.getLdapBindPassword();
    String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER);
    if (groupMemberAttributName == null) {
        LOGGER.debug(
                "No groupMember attribute defined in quartz-jobs.xml. Fall back to " + DEFAULT_GROUP_MEMBER);
        groupMemberAttributName = DEFAULT_GROUP_MEMBER;
    }
    LdapContext baseContext = getInitialContext(baseURL, bindDN, bindPassword);
    if (baseContext == null) {
        LOGGER.warn("Context is null for baseURL " + baseURL);
        return ldapGroupsMap;
    }
    for (Map.Entry<String, String> groupEntry : groups.entrySet()) {
        String groupName = groupEntry.getKey();
        String groupDN = groupEntry.getValue();
        int index = groupDN.indexOf(",");
        if (index != -1) {
            String searchPart = groupDN.substring(0, index);
            String searchStr = "(" + searchPart + ")";
            String parentDNPart = groupDN.substring(index + 1);
            LdapContext context = (LdapContext) baseContext.lookup(parentDNPart);
            if (context == null) {
                LOGGER.warn("Context is null after lookup for " + parentDNPart);
                continue;
            }
            int recordCount = 0;
            SearchControls ctls = null;
            try {
                // Activate paged results
                int pageSize = 5;
                byte[] cookie = null;
                context.setRequestControls(
                        new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
                int total;
                // Control the search
                ctls = new SearchControls();
                ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers()
                        + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can
                                                                                                                                                                             // handle anyways
                do {
                    /* perform the search */
                    NamingEnumeration<SearchResult> results = context.search("", searchStr, ctls);
                    /*
                     * for each entry print out name + all attrs and values
                     */
                    while (results != null && results.hasMore()) {
                        SearchResult searchResult = (SearchResult) results.next();
                        // Attributes atrs = sr.getAttributes();
                        Attributes attributes = searchResult.getAttributes();
                        if (attributes == null) {
                            LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName());
                            continue;
                        }
                        TPersonBean personBean = new TPersonBean();
                        try {
                            personBean.setLoginName(groupName);
                            ldapGroupsMap.put(personBean.getLoginName(), personBean);
                            Attribute memberAttribute = attributes.get(groupMemberAttributName);
                            if (memberAttribute != null) {
                                NamingEnumeration<?> members = memberAttribute.getAll();
                                while (members != null && members.hasMore()) {
                                    String memberSearchResult = (String) members.next();
                                    List<String> memberDNList = groupToMemberReferencesMap.get(groupName);
                                    if (memberDNList == null) {
                                        memberDNList = new ArrayList<String>();
                                        groupToMemberReferencesMap.put(groupName, memberDNList);
                                    }
                                    LOGGER.debug("Member found: " + memberSearchResult);
                                    memberDNList.add(memberSearchResult);
                                }
                            } else {
                                LOGGER.info("Could not find value(s) for group member attribute "
                                        + groupMemberAttributName + " for group " + groupName);
                            }
                            LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get());
                            LOGGER.debug("Processed group " + groupName);
                        } catch (Exception e) {
                            LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage());
                            LOGGER.warn(
                                    "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml");
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("Stack trace:", e);
                            }
                        }
                        ++recordCount;
                    }
                    // Examine the paged results control response
                    Control[] controls = context.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) {
                                    LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total
                                            + ") *****************\n");
                                } else {
                                    LOGGER.debug("***************** END-OF-PAGE "
                                            + "(total: unknown) ***************\n");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOGGER.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    context.setRequestControls(
                            new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

                } while (cookie != null);
            } catch (SizeLimitExceededException sle) {
                if (recordCount < ctls.getCountLimit()) {
                    LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server.");
                    LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with "
                            + sle.getMessage());
                    LOGGER.error(
                            "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter.");
                } else {
                    LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server ("
                            + recordCount + ").");
                    LOGGER.error(
                            "You have to get more user licenses for Genji or specify a more suitable search base or filter.");
                }
                LOGGER.error("The LDAP synchronization is most likely incomplete.");
            } catch (NamingException e) {
                LOGGER.error("PagedSearch failed.");
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            } catch (IOException ie) {
                LOGGER.error("PagedSearch failed.");
                LOGGER.debug(ExceptionUtils.getStackTrace(ie));
            } finally {
                context.close();
            }
        }
    }
    return ldapGroupsMap;
}

From source file:org.pentaho.platform.plugin.services.security.userrole.ldap.search.GenericLdapSearch.java

public List search(final Object[] filterArgs) {
    Object[] transformedArgs = filterArgs;
    // transform the filterArgs
    if (null != filterArgsTransformer) {
        transformedArgs = (Object[]) filterArgsTransformer.transform(filterArgs);
    }//from www.  j av a2  s .  c o m
    LdapSearchParams params = paramsFactory.createParams(transformedArgs);
    // use a set internally to store intermediate results
    Set results = new HashSet();
    NamingEnumeration matches = null;
    try {
        matches = contextSource.getReadOnlyContext().search(params.getBase(), params.getFilter(),
                params.getFilterArgs(), params.getSearchControls());
    } catch (NamingException e1) {
        if (GenericLdapSearch.logger.isErrorEnabled()) {
            // TODO: Throw an exception here
            GenericLdapSearch.logger.error("Directory search failed", e1); //$NON-NLS-1$
        }
        return new ArrayList(results);
    }
    try {
        while (matches.hasMore()) {
            SearchResult result = (SearchResult) matches.next();
            if (null != resultsTransformer) {
                results.addAll((Collection) resultsTransformer.transform(result));
            } else {
                results.add(result);
            }
        }
    } catch (NamingException e) {
        if (GenericLdapSearch.logger.isErrorEnabled()) {
            // TODO: Throw an exception here
            GenericLdapSearch.logger.error("Enumerating directory search results failed", e); //$NON-NLS-1$
        }
    }
    return new ArrayList(results);
}

From source file:org.apache.directory.server.operations.bind.SaslBindIT.java

/**
 * Tests to make sure the server properly returns the supportedSASLMechanisms.
 *//*from  w w  w.jav  a 2  s .c o  m*/
@Test
public void testSupportedSASLMechanisms() throws Exception {
    // We have to tell the server that it should accept anonymous
    // auth, because we are reading the rootDSE
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Point on rootDSE
    DirContext context = new InitialDirContext();

    Attributes attrs = context.getAttributes(Network.ldapLoopbackUrl(getLdapServer().getPort()),
            new String[] { "supportedSASLMechanisms" });

    //             Thread.sleep( 10 * 60 * 1000 );
    NamingEnumeration<? extends Attribute> answer = attrs.getAll();
    Attribute result = answer.next();
    assertEquals(6, result.size());
    assertTrue(result.contains(SupportedSaslMechanisms.GSSAPI));
    assertTrue(result.contains(SupportedSaslMechanisms.DIGEST_MD5));
    assertTrue(result.contains(SupportedSaslMechanisms.CRAM_MD5));
    assertTrue(result.contains(SupportedSaslMechanisms.NTLM));
    assertTrue(result.contains(SupportedSaslMechanisms.PLAIN));
    assertTrue(result.contains(SupportedSaslMechanisms.GSS_SPNEGO));
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private List searchGroupMember(DirContext context, Map filters) throws NamingException {

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    Set userList = new HashSet();
    String filter = buildFilter(filters);
    if (log.isInfoEnabled())
        log.info("Search User from " + userBase + " by " + filter);
    NamingEnumeration searchResultEnum = context.search(this.groupBase, filter, searchControls);

    while (searchResultEnum.hasMore()) {
        SearchResult searchResult = (SearchResult) searchResultEnum.next();
        Attributes attrs = searchResult.getAttributes();
        String dn = searchResult.getName() + "," + groupBase;
        String uniquememberAttrName = "uniqueMember";
        if (this.propAttrMap.containsKey("org_member")) {
            try {
                uniquememberAttrName = (String) this.propAttrMap.get("org_member");
            } catch (Exception ex) {
                //ignore
            }/*w  w  w .ja  v  a 2s . c o m*/
        }
        Attribute uniquememberAttr = attrs.get(uniquememberAttrName);
        if (uniquememberAttr == null)
            continue;
        NamingEnumeration memberDNs = uniquememberAttr.getAll();
        while (memberDNs.hasMoreElements()) {
            //System.out.println(memberDNs[j]);
            userList.add(memberDNs.next());//DN of user
        }
    }

    List members = new ArrayList();

    for (Iterator userDns = userList.iterator(); userDns.hasNext();) {

        /* Next directory entry */
        String userDn = (String) userDns.next();
        Attributes userEntry = null;
        try {
            userEntry = context.getAttributes(userDn);//DN of user
        } catch (Exception e) {
            log.error(userDn + ": " + e.getMessage());
        }
        if (userEntry == null)
            continue;

        LDAPAccount user = createLDAPUser(userDn, userEntry);
        if (user.getUid() == null)
            continue;

        members.add(user);

    }

    return members;

}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private void setGroup(DirContext context, LDAPAccount user) throws NamingException {

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    //create the filter of group
    Map filters = new HashMap();
    String uniqueMemberAttrName = "uniquemember";
    if (this.propAttrMap.containsKey("org_member"))
        uniqueMemberAttrName = (String) this.propAttrMap.get("org_member");

    filters.put(uniqueMemberAttrName, user.getDn());
    String grpFilter = buildGroupFilterByDN(filters);

    NamingEnumeration grpRes = context.search(groupBase, grpFilter, searchControls);

    List grpList = new ArrayList();

    while (grpRes.hasMoreElements()) {
        SearchResult findGrpEntry = (SearchResult) grpRes.next();
        if (log.isDebugEnabled())
            log.debug("Found Groups: " + findGrpEntry.getAttributes().toString());
        String grpdn = findGrpEntry.getName() + "," + groupBase;

        grpList.add(createLDAPGroup(grpdn, findGrpEntry.getAttributes()));
    }//from   ww w . j  av  a  2 s.  c  om

    IGroup[] igroup = new IGroup[grpList.size()];

    for (int i = 0; i < igroup.length; i++) {
        igroup[i] = (IGroup) grpList.get(i);
    }
    user.setGroups(igroup);

}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

/**
 * Tries to find the value(s) of the given attribute. Note that this method
 * uses all search results./*from   w  ww.  j a va  2 s .c  om*/
 * 
 * @param username
 *            a username
 * @param attrName
 *            the name of the attribute to find
 * @return a list of values for the attribute, or an empty list
 */
public List<String> getAllAttrs(String username, String attrName) {
    List<String> resultList = new ArrayList<String>();

    try {
        DirContext dc = new InitialDirContext(env);
        NamingEnumeration<SearchResult> ne = performLdapSearch(username, dc);

        while (ne.hasMore()) {
            resultList.add(getAttrValue(attrName, ne.next()));
        }

        ne.close();
        dc.close();
    } catch (NamingException ne) {
        log.warn("Failed LDAP lookup getAllAttrs" + username, ne);
    }

    log.trace("getAllAttrs search result: " + resultList);
    if (log.isTraceEnabled()) {
        log.trace("getAllAttrs search result: " + resultList);
    }

    return resultList;
}