Example usage for javax.naming NamingEnumeration hasMore

List of usage examples for javax.naming NamingEnumeration hasMore

Introduction

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

Prototype

public boolean hasMore() throws NamingException;

Source Link

Document

Determines whether there are any more elements in the enumeration.

Usage

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

/**
 * Test to make sure that if anonymous binds are allowed a user may search
 * within a a partition.// w w w .  ja  v a  2  s .  c  om
 *
 * @throws Exception if anything goes wrong
 */
@Test
public void testAnonymousBindsEnabledBaseSearch() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Use the SUN JNDI provider to hit server port and bind as anonymous
    Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()));
    env.put(Context.SECURITY_AUTHENTICATION, "none");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    InitialDirContext ctx = new InitialDirContext(env);
    SearchControls cons = new SearchControls();
    cons.setSearchScope(SearchControls.OBJECT_SCOPE);
    NamingEnumeration<SearchResult> list = ctx.search("dc=apache,dc=org", "(objectClass=*)", cons);
    SearchResult result = null;

    if (list.hasMore()) {
        result = list.next();
    }

    assertFalse(list.hasMore());
    list.close();

    assertNotNull(result);
    assertNotNull(result.getAttributes().get("dc"));
}

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

static TPersonBean getLdapUser(String providerUrl, String bindDN, String bindPassword,
        String loginAttributeName, String searchStr) throws Exception {
    LdapContext ctx = null;//from  ww w  .  j  av a 2  s .  c  om
    try {
        ctx = getInitialContext(providerUrl, bindDN, bindPassword);
        if (ctx == null) {
            LOGGER.warn("The context is null");
        }
        // Control the search
        SearchControls ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        // Don't ask for more than we can handle anyways
        if (ldapMap == null || ldapMap.isEmpty()) {
            LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!");
            return null;
        }
        String firstNameAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.FIRST_NAME);
        String lastNameAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.LAST_NAME);
        String emailAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.EMAIL);
        String phoneAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.PHONE);
        NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls);
        /* for each entry print out name + all attrs and values */
        while (results != null && results.hasMore()) {
            SearchResult sr = (SearchResult) results.next();
            return getPersonBean(sr, loginAttributeName, firstNameAttributeName, lastNameAttributName,
                    emailAttributeName, phoneAttributName);
        }
    } catch (NamingException e) {
        LOGGER.warn(
                "Searching from " + providerUrl + " by filter " + searchStr + " failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
    return null;
}

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

/**
 * {@inheritDoc}/*from   ww  w. j  ava  2 s.  c  o m*/
 */
@Override
public Set<Subject> search(final String searchString) {

    final Set<Subject> result = new HashSet<Subject>();
    Search search = this.getSearch("search");
    String searchExpression;

    // If an scope value is found in the search string
    // the string is decomposed and a decorated Search instance is used.
    final int index = searchString.indexOf(ESCOJNDISourceAdapter.SCOPE_DELIM);
    if (index >= 0) {
        final String searchTerm = searchString.substring(0, index).trim();
        final String scopeTerm = searchString.substring(index + ESCOJNDISourceAdapter.SCOPE_DELIM.length())
                .trim();
        final String[] scopes = scopeTerm.split(ESCOJNDISourceAdapter.SCOPE_SEP);
        search = new ESCOSearchWithScopeDecorator(scopes, search);
        searchExpression = searchTerm;
    } else {
        searchExpression = searchString;
    }

    if (search == null) {
        LOGGER.error("searchType: \"search\" not defined.");
        return result;
    }
    final String[] attributeNames = { this.nameAttributeName, this.subjectIDAttributeName,
            this.descriptionAttributeName, };

    @SuppressWarnings("rawtypes")
    NamingEnumeration ldapResults = this.getLdapResults(search, searchExpression, attributeNames);
    if (ldapResults == null) {
        return result;
    }
    try {
        while (ldapResults.hasMore()) {
            SearchResult si = (SearchResult) ldapResults.next();
            Attributes attributes1 = si.getAttributes();
            Subject subject = this.createSubject(attributes1);
            result.add(subject);
        }
    } catch (NamingException ex) {
        LOGGER.error("LDAP Naming Except: " + ex.getMessage(), ex);
    }

    return result;

}

From source file:org.apache.ftpserver.usermanager.LdapUserManager.java

/**
 * Get all user names.//from w  ww  .  j  a  v  a  2 s . c om
 */
public synchronized Collection getAllUserNames() throws FtpException {

    try {
        // search ldap
        Attributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(m_objClassAttr);
        matchAttrs.put(new BasicAttribute(CLASS_NAME, BaseUser.class.getName()));
        NamingEnumeration answers = m_adminContext.search(m_userBaseDn, matchAttrs, CN_ATTRS);
        m_log.info("Getting all users under " + m_userBaseDn);

        // populate list
        ArrayList allUsers = new ArrayList();
        while (answers.hasMore()) {
            SearchResult sr = (SearchResult) answers.next();
            String cn = sr.getAttributes().get(CN).get().toString();
            allUsers.add(cn);
        }
        Collections.sort(allUsers);
        return allUsers;
    } catch (NamingException ex) {
        m_log.error("LdapUserManager.getAllUserNames()", ex);
        throw new FtpException("LdapUserManager.getAllUserNames()", ex);
    }
}

From source file:org.gbif.portal.registration.LDAPUtils.java

/**
 * Gets the common, phone and email for the
 * @param uid To use for searching in LDAP  
 * @return An array containing the 3 strings
 * @throws NamingException On error//from  www  . ja  v a 2 s. c  om
 */
@SuppressWarnings("unchecked")
public List<UserLogin> getUsernamePasswordForEmail(String email) throws NamingException {
    DirContext ctx = getUserContext();
    NamingEnumeration searchResults = ctx.search("", "mail=" + email, null, new SearchControls());
    List<UserLogin> uls = new ArrayList<UserLogin>();
    while (searchResults.hasMore()) {
        SearchResult sr = (SearchResult) searchResults.next();
        Attributes attributes = sr.getAttributes();
        debugAttributes(attributes);
        UserLogin ul = new UserLogin();
        ul.setSurname((String) attributes.get("sn").get());
        ul.setFirstName((String) attributes.get("givenName").get());
        ul.setEmail((String) attributes.get("mail").get());
        ul.setUsername((String) attributes.get("uid").get());
        uls.add(ul);
    }
    return uls;
}

From source file:com.predic8.membrane.core.interceptor.authentication.session.LDAPUserDataProvider.java

private String searchUser(String login, HashMap<String, String> userAttrs, DirContext ctx)
        throws NamingException {
    String uid;/*from   w  ww.  java 2s .co  m*/
    SearchControls ctls = new SearchControls();
    ctls.setReturningObjFlag(true);
    ctls.setSearchScope(searchScope);
    String search = searchPattern.replaceAll(Pattern.quote("%LOGIN%"), escapeLDAPSearchFilter(login));
    log.debug("Searching LDAP for " + search);
    NamingEnumeration<SearchResult> answer = ctx.search(base, search, ctls);
    try {
        if (!answer.hasMore())
            throw new NoSuchElementException();
        log.debug("LDAP returned >=1 record.");
        SearchResult result = answer.next();
        uid = result.getName();
        for (Map.Entry<String, String> e : attributeMap.entrySet()) {
            log.debug("found LDAP attribute: " + e.getKey());
            Attribute a = result.getAttributes().get(e.getKey());
            if (a != null)
                userAttrs.put(e.getValue(), a.get().toString());
        }
    } finally {
        answer.close();
    }
    return uid;
}

From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java

protected boolean userExists(String id) {
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_CREDENTIALS, "secret");

    try {//from w ww  . j  a  v  a2  s  .  com
        DirContext ctx = new InitialDirContext(env);

        /*
         * Setup subtree scope to tell LDAP to recursively descend directory structure during searches.
         */
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        /*
         * Setup the directory entry attributes we want to search for. In this case it is the user's ID.
         */

        String filter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(id) + "))";

        /* Execute the search, starting at the directory level of Users */

        NamingEnumeration hits = ctx.search(getBasePath(), filter, searchControls);

        /* All we need to know is if there were any hits at all. */

        if (hits.hasMore()) {
            hits.close();
            ctx.close();
            return true;
        } else {
            hits.close();
            ctx.close();
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java

@Test
public void testRunning() throws Exception {
    Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.PROVIDER_URL, "ldap://localhost:1024");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, PRINCIPAL);
    env.put(Context.SECURITY_CREDENTIALS, CREDENTIALS);
    DirContext ctx = new InitialDirContext(env);

    HashSet<String> set = new HashSet<>();

    NamingEnumeration<NameClassPair> list = ctx.list("ou=system");

    while (list.hasMore()) {
        NameClassPair ncp = list.next();
        set.add(ncp.getName());// w ww.  j  av  a2  s.c  o  m
    }

    Assert.assertTrue(set.contains("uid=admin"));
    Assert.assertTrue(set.contains("ou=users"));
    Assert.assertTrue(set.contains("ou=groups"));
    Assert.assertTrue(set.contains("ou=configuration"));
    Assert.assertTrue(set.contains("prefNodeName=sysPrefRoot"));

    ctx.close();
}

From source file:alpine.auth.LdapConnectionWrapper.java

/**
 * Convenience method that wraps {@link NamingEnumeration#hasMore()} but ignores {@link PartialResultException}s
 * that may be thrown as a result. This is typically an issue with a directory server that does not support
 * {@link Context#REFERRAL} being set to 'ignore' (which is the default value).
 *
 * Issue: https://github.com/stevespringett/Alpine/issues/19
 * @since 1.4.3/*  www  .  jav  a  2s. c o m*/
 */
private boolean hasMoreEnum(NamingEnumeration<SearchResult> ne) throws NamingException {
    if (ne == null) {
        return false;
    }
    boolean hasMore = true;
    try {
        if (!ne.hasMore()) {
            hasMore = false;
        }
    } catch (PartialResultException e) {
        hasMore = false;
        LOGGER.warn(
                "Partial results returned. If this is an Active Directory server, try using port 3268 or 3269 in "
                        + Config.AlpineKey.LDAP_SERVER_URL.name());
    }
    return hasMore;
}

From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java

public boolean authenticateUser(String userLogin, UserEdit edit, String password) {
    Hashtable env = new Hashtable();
    InitialDirContext ctx;//  w w  w.  j  a v  a2  s  .  c o m

    String INIT_CTX = "com.sun.jndi.ldap.LdapCtxFactory";
    String MY_HOST = getLdapHost() + ":" + getLdapPort();
    String cn;
    boolean returnVal = false;

    if (!password.equals("")) {

        env.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
        env.put(Context.PROVIDER_URL, MY_HOST);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_CREDENTIALS, "secret");

        String[] returnAttribute = { "ou" };
        SearchControls srchControls = new SearchControls();
        srchControls.setReturningAttributes(returnAttribute);
        srchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(userLogin) + "))";

        try {
            ctx = new InitialDirContext(env);
            NamingEnumeration answer = ctx.search(getBasePath(), searchFilter, srchControls);
            String trobat = "false";

            while (answer.hasMore() && trobat.equals("false")) {

                SearchResult sr = (SearchResult) answer.next();
                String dn = sr.getName().toString() + "," + getBasePath();

                // Second binding
                Hashtable authEnv = new Hashtable();
                try {
                    authEnv.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
                    authEnv.put(Context.PROVIDER_URL, MY_HOST);
                    authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
                    authEnv.put(Context.SECURITY_PRINCIPAL, sr.getName() + "," + getBasePath());
                    authEnv.put(Context.SECURITY_CREDENTIALS, password);
                    try {
                        DirContext authContext = new InitialDirContext(authEnv);
                        returnVal = true;
                        trobat = "true";
                        authContext.close();
                    } catch (AuthenticationException ae) {
                        M_log.info("Access forbidden");
                    }

                } catch (NamingException namEx) {
                    M_log.info("User doesn't exist");
                    returnVal = false;
                    namEx.printStackTrace();
                }
            }
            if (trobat.equals("false"))
                returnVal = false;

        } catch (NamingException namEx) {
            namEx.printStackTrace();
            returnVal = false;
        }
    }
    return returnVal;
}