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.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java

protected ArrayList<String> getRoles(DirContext context, String dn, String username, ArrayList<String> list)
        throws NamingException {
    if (list == null) {
        list = new ArrayList<String>();
    }//w ww  .ja v  a  2s  .  c o  m
    if (roleName == null || "".equals(roleName)) {
        return list;
    }
    String filter = roleSearchMatchingFormat.format(new String[] { doRFC2254Encoding(dn), username });

    SearchControls constraints = new SearchControls();
    if (roleSearchSubtreeBool) {
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    } else {
        constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    }
    NamingEnumeration results = context.search(roleBase, filter, constraints);
    while (results.hasMore()) {
        SearchResult result = (SearchResult) results.next();
        Attributes attrs = result.getAttributes();
        if (attrs == null) {
            continue;
        }
        list = addAttributeValues(roleName, attrs, list);
    }
    return list;
}

From source file:com.springsource.insight.plugin.ldap.TestLdapContext.java

private void logAttributes(String location, Attributes attrs) throws NamingException {
    NamingEnumeration<? extends Attribute> values = attrs.getAll();
    try {// w w w. j a va  2 s  .  c  o  m
        while ((values != null) && values.hasMore()) {
            Attribute aValue = values.next();
            String id = aValue.getID();
            Collection<?> valsList = Collections.list(aValue.getAll());
            logger.trace(location + "[" + id + "]: " + valsList);
        }
    } finally {
        values.close();
    }
}

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

@Test
public void testSaslGssapiLdapAuth() throws Exception {

    final 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, "GSSAPI");

    LoginContext loginContext = new LoginContext("broker-sasl-gssapi");
    loginContext.login();//from  w w  w  .  j  a  v  a 2s .c  om
    try {
        Subject.doAs(loginContext.getSubject(), (PrivilegedExceptionAction<Object>) () -> {

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

            DirContext ctx = new InitialDirContext(env);
            NamingEnumeration<NameClassPair> list = ctx.list("ou=system");

            while (list.hasMore()) {
                NameClassPair ncp = list.next();
                set.add(ncp.getName());
            }

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

            ctx.close();
            return null;

        });
    } catch (PrivilegedActionException e) {
        throw e.getException();
    }
}

From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java

private boolean addLDAPSearchResult(List<User> users, NamingEnumeration<SearchResult> results)
        throws NamingException {
    boolean somethingAdded = false;
    while (results != null && results.hasMore()) {
        // Display an entry
        SearchResult entry = results.next();
        User user = processEntry(entry);
        if (user != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("Success reading from LDAP: {0}, {1} <{2}>", user.getUserId(),
                        user.getDisplayName(), user.getEmail()));
            }/*from w ww. j  av a 2 s. c  om*/
            users.add(user);
            somethingAdded = true;
        }
    }
    return somethingAdded;
}

From source file:org.wso2.carbon.connector.ldap.SearchEntry.java

@Override
public void connect(MessageContext messageContext) throws ConnectException {
    String objectClass = (String) getParameter(messageContext, LDAPConstants.OBJECT_CLASS);
    String filter = (String) getParameter(messageContext, LDAPConstants.FILTERS);
    String dn = (String) getParameter(messageContext, LDAPConstants.DN);
    String returnAttributes[] = ((String) getParameter(messageContext, LDAPConstants.ATTRIBUTES)).split(",");
    boolean onlyOneReference = Boolean
            .valueOf((String) getParameter(messageContext, LDAPConstants.ONLY_ONE_REFERENCE));

    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace ns = factory.createOMNamespace(LDAPConstants.CONNECTOR_NAMESPACE, LDAPConstants.NAMESPACE);
    OMElement result = factory.createOMElement(LDAPConstants.RESULT, ns);

    try {/*w ww.j  av  a2  s .  c  o m*/
        DirContext context = LDAPUtils.getDirectoryContext(messageContext);

        String attrFilter = generateAttrFilter(filter);
        String searchFilter = generateSearchFilter(objectClass, attrFilter);
        NamingEnumeration<SearchResult> results = null;
        try {
            results = searchInUserBase(dn, searchFilter, returnAttributes, SearchControls.SUBTREE_SCOPE,
                    context);
            SearchResult entityResult = null;

            if (!onlyOneReference) {
                if (results != null && results.hasMore()) {
                    while (results.hasMore()) {
                        entityResult = results.next();
                        result.addChild(prepareNode(entityResult, factory, ns, returnAttributes));
                    }
                }
            } else {
                entityResult = makeSureOnlyOneMatch(results);
                if (entityResult == null)
                    throw new NamingException(
                            "Multiple objects for the searched target have been found. Try to "
                                    + "change onlyOneReference option");
                result.addChild(prepareNode(entityResult, factory, ns, returnAttributes));
            }

            LDAPUtils.preparePayload(messageContext, result);

            if (context != null) {
                context.close();
            }

        } catch (NamingException e) { //LDAP Errors are catched
            LDAPUtils.handleErrorResponse(messageContext, LDAPConstants.ErrorConstants.SEARCH_ERROR, e);
            throw new SynapseException(e);
        }

    } catch (NamingException e) { //Authentication failures are catched
        LDAPUtils.handleErrorResponse(messageContext, LDAPConstants.ErrorConstants.INVALID_LDAP_CREDENTIALS, e);
        throw new SynapseException(e);
    }
}

From source file:com.openkm.principal.LdapPrincipalAdapter.java

@SuppressWarnings("unchecked")
private List<String> ldapSearch(List<String> searchBases, String searchFilter, String attribute) {
    log.debug("ldapSearch({}, {}, {})", new Object[] { searchBases, searchFilter, attribute });
    List<String> al = new ArrayList<String>();
    DirContext ctx = null;/*from w w w.ja va2  s .  c o  m*/
    Hashtable<String, String> env = getEnvironment();

    try {
        ctx = new InitialDirContext(env);
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        for (String searchBase : searchBases) {
            NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchCtls);

            while (results.hasMore()) {
                SearchResult searchResult = (SearchResult) results.next();
                Attributes attributes = searchResult.getAttributes();

                if (attribute.equals("")) {
                    StringBuilder sb = new StringBuilder();

                    for (NamingEnumeration<?> ne = attributes.getAll(); ne.hasMore();) {
                        Attribute attr = (Attribute) ne.nextElement();
                        sb.append(attr.toString());
                        sb.append("\n");
                    }

                    al.add(sb.toString());
                } else {
                    Attribute attrib = attributes.get(attribute);

                    if (attrib != null) {
                        // Handle multi-value attributes
                        for (NamingEnumeration<?> ne = attrib.getAll(); ne.hasMore();) {
                            String value = (String) ne.nextElement();

                            // If FQDN get only main part
                            if (value.startsWith("CN=") || value.startsWith("cn=")) {
                                String cn = value.substring(3, value.indexOf(','));
                                log.debug("FQDN: {}, CN: {}", value, cn);
                                al.add(cn);
                            } else {
                                al.add(value);
                            }
                        }
                    }
                }
            }
        }
    } catch (ReferralException e) {
        log.error("ReferralException: {}", e.getMessage());
        log.error("ReferralInfo: {}", e.getReferralInfo());
        log.error("ResolvedObj: {}", e.getResolvedObj());

        try {
            log.error("ReferralContext: {}", e.getReferralContext());
        } catch (NamingException e1) {
            log.error("NamingException logging context: {}", e1.getMessage());
        }
    } catch (NamingException e) {
        log.error("NamingException: {} (Base: {} - Filter: {} - Attribute: {})",
                new Object[] { e.getMessage(), searchBases, searchFilter, attribute });
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (NamingException e) {
            log.error("NamingException closing context: {}", e.getMessage());
        }
    }

    log.debug("ldapSearch: {}", al);
    return al;
}

From source file:org.apache.openaz.xacml.std.pip.engines.ldap.LDAPEngine.java

public void getAttributes(PIPRequest pipRequest, PIPFinder pipFinder, StdMutablePIPResponse mutablePIPResponse,
        LDAPResolver ldapResolver) throws PIPException {
    /*/*ww w . ja  v a  2  s .c o  m*/
     * Check with the resolver to get the base string
     */
    String stringBase = ldapResolver.getBase(this, pipRequest, pipFinder);
    if (stringBase == null) {
        this.logger.warn(this.getName() + " does not handle " + pipRequest.toString());
        return;
    }

    /*
     * Get the filter string
     */
    String stringFilter = ldapResolver.getFilterString(this, pipRequest, pipFinder);

    /*
     * Check the cache
     */
    Cache<String, PIPResponse> cache = this.getCache();
    String cacheKey = stringBase + "::" + (stringFilter == null ? "" : stringFilter);
    if (cache != null) {
        PIPResponse pipResponse = cache.getIfPresent(cacheKey);
        if (pipResponse != null) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Returning cached response: " + pipResponse);
            }
            mutablePIPResponse.addAttributes(pipResponse.getAttributes());
            return;
        }
    }
    /*
     * Not in the cache, so set up the LDAP query session
     */
    DirContext dirContext = null;
    PIPResponse pipResponse = null;
    try {
        /*
         * Create the DirContext
         */
        dirContext = new InitialDirContext(this.ldapEnvironment);

        /*
         * Set up the search controls
         */
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(this.ldapScope);

        /*
         * Do the search
         */
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(stringBase, stringFilter,
                searchControls);
        if (namingEnumeration != null && namingEnumeration.hasMore()) {
            while (namingEnumeration.hasMore()) {
                List<Attribute> listAttributes = ldapResolver.decodeResult(namingEnumeration.next());
                if (listAttributes != null && listAttributes.size() > 0) {
                    mutablePIPResponse.addAttributes(listAttributes);
                }
            }
        }
        /*
         * Put in the cache
         */
        if (cache != null) {
            cache.put(cacheKey, pipResponse);
        }
    } catch (NamingException ex) {
        this.logger.error("NamingException creating the DirContext: " + ex.getMessage(), ex);
    } finally {
        if (dirContext != null) {
            try {
                dirContext.close();
            } catch (Exception ex) {
                this.logger.warn("Exception closing DirContext: " + ex.getMessage(), ex);
            }
        }
    }
}

From source file:com.konakart.bl.LDAPMgrCore.java

/**
 * Called if the LDAP module is installed and active. This method should return:
 * <ul>/*from   w  w w.  j a va  2 s .c om*/
 * <li>A negative number in order for the login attempt to fail. The KonaKart login() method
 * will return a null sessionId</li>
 * <li>Zero to signal that this method is not implemented. The KonaKart login() method will
 * perform the credential check.</li>
 * <li>A positive number for the login attempt to pass. The KonaKart login() will not check
 * credentials, and will log in the customer, returning a valid session id.</li>
 * </ul>
 * This method may need to be modified slightly depending on the structure of your LDAP. The
 * example works when importing the exampleData.ldif file in the LDAP module jar:
 * 
 * dn: cn=Robert Smith,ou=people,dc=example,dc=com<br/>
 * objectclass: inetOrgPerson<br/>
 * cn: Robert Smith<br/>
 * cn: Robert J Smith<br/>
 * cn: bob smith<br/>
 * sn: smith<br/>
 * uid: rjsmith<br/>
 * userpassword: rJsmitH<br/>
 * carlicense: HISCAR 123<br/>
 * homephone: 555-111-2222<br/>
 * mail: r.smith@example.com<br/>
 * mail: rsmith@example.com<br/>
 * mail: bob.smith@example.com<br/>
 * description: swell guy<br/>
 * 
 * The code attempts to connect to LDAP using the username, password and URL in the
 * configuration variables set when the module was installed through the admin app.<br/>
 * 
 * After having connected, the person object is searched for using the email address of the
 * user. If found we use the "cn" attribute and the password of the user to attempt to bind to
 * LDAP. If the bind is successful, we return a positive number which means that authentication
 * was successful.
 * 
 * @param emailAddr
 *            The user name required to log in
 * @param password
 *            The log in password
 * @return Returns an integer
 * @throws Exception
 */
public int checkCredentials(String emailAddr, String password) throws Exception {
    DirContext ctx = null;

    try {
        Hashtable<String, String> environment = new Hashtable<String, String>();

        if (log.isDebugEnabled()) {
            log.debug("LDAP connection URL                          =   " + url);
            log.debug("LDAP user name                               =   " + ldapUserName);
            log.debug("LDAP person object distinguished name (DN)   =   " + personDN);
        }

        if (ldapUserName == null) {
            throw new KKException(
                    "Cannot access LDAP because the MODULE_OTHER_LDAP_USER_NAME configuration variable hasn't been set.");
        }
        if (ldapPassword == null) {
            throw new KKException(
                    "Cannot access LDAP because the MODULE_OTHER_LDAP_PASSWORD configuration variable hasn't been set.");
        }
        if (url == null) {
            throw new KKException(
                    "Cannot access LDAP because the MODULE_OTHER_LDAP_URL configuration variable hasn't been set.");
        }
        if (personDN == null) {
            throw new KKException(
                    "Cannot validate through LDAP because the MODULE_OTHER_LDAP_PERSON_DN (Distinguished Name of Person Object) configuration variable hasn't been set.");
        }

        environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        environment.put(Context.SECURITY_AUTHENTICATION, "simple");
        environment.put(Context.PROVIDER_URL, url);
        environment.put(Context.SECURITY_PRINCIPAL, ldapUserName);
        environment.put(Context.SECURITY_CREDENTIALS, ldapPassword);

        /*
         * connect to LDAP using the credentials and connection string from the configuration
         * variables
         */
        try {
            ctx = new InitialDirContext(environment);
        } catch (Exception e) {
            log.error("Cannot connect to LDAP", e);
            return -1;
        }

        /* Specify the search filter on the eMail address */
        String filter = "(mail=" + emailAddr + ")";

        /*
         * limit returned attributes to those we care about. In this case we only require the
         * "cn" attribute which we will use to attempt to bind the user in order to validate his
         * password
         */
        String[] attrIDs = { "cn" };
        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(attrIDs);
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        /* Search for objects using filter and controls */
        NamingEnumeration<SearchResult> answer = ctx.search(personDN, filter, ctls);

        /* close the connection */
        ctx.close();

        if (answer == null || !answer.hasMore()) {
            return -1;
        }

        SearchResult sr = answer.next();
        Attributes attrs = sr.getAttributes();
        String cn = attrs.get("cn").toString();
        if (log.isDebugEnabled()) {
            log.debug("cn of user with eMail (" + emailAddr + ") is " + cn);
        }

        /*
         * cn could be in the format "cn: Peter Smith, Pete Smith, Smithy" so we need to capture
         * just the first entry
         */
        if (cn != null) {
            if (cn.contains(",")) {
                cn = cn.split(",")[0];
                if (cn.contains(":")) {
                    cn = cn.split(":")[1];
                }
            } else if (cn.contains(":")) {
                cn = cn.split(":")[1];
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Cleaned cn of user with eMail (" + emailAddr + ") is " + cn);
        }

        /* Now we try to bind as the user */
        String userName = "cn=" + cn + "," + personDN;

        if (log.isDebugEnabled()) {
            log.debug("LDAP user name of user with eMail (" + emailAddr + ") is " + userName);
        }

        /* Bind as the user */
        environment.put(Context.SECURITY_PRINCIPAL, userName);
        environment.put(Context.SECURITY_CREDENTIALS, password);
        try {
            ctx = new InitialDirContext(environment);
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Could not bind user " + userName);
            }
            return -1;
        }
        ctx.close();
        if (log.isDebugEnabled()) {
            log.debug("user with eMail (" + emailAddr + ") was successfully authenticated using LDAP");
        }
        return 1;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.error("Received an exception while closing the LDAP DirContext", e);
            }
        }
    }
}

From source file:org.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java

private MetricValue getMetric(Metric metric, String tree, String attr)
        throws MetricNotFoundException, NamingException {
    NamingEnumeration enumer = null;
    try {/*  www . j  a  v  a  2s. c o  m*/
        String[] a = { attr };
        SearchControls cons = new SearchControls();
        cons.setSearchScope(SearchControls.OBJECT_SCOPE);
        cons.setReturningAttributes(a);
        enumer = getDirContext(metric.getProperties()).search(tree, "(&(objectClass=*))", cons);
        while (enumer.hasMore()) {
            SearchResult searchresult = (SearchResult) enumer.next();
            Attributes attrs = searchresult.getAttributes();
            Attribute val;
            if (null != (val = attrs.get(attr))) {
                return new MetricValue(new Double(val.get().toString()), System.currentTimeMillis());
            }
        }
        throw new MetricNotFoundException("");
    } finally {
        if (enumer != null) {
            enumer.close();
        }
    }
}

From source file:org.pegadi.server.user.LDAPUserServerImpl.java

/**
 * Returns an array of users./*from  w ww  .  ja v a 2  s.c o  m*/
 *
 * @param inactive <code>true</code> if inactive users should be included.
 * @return an array of <code>User</code>s.
 */
public List<Person> getAllUsers(boolean inactive) {
    ArrayList<Person> users = new ArrayList<Person>();
    try {
        SearchControls sc = new SearchControls();
        String[] getThese = { "sn", "gn", "mail", "uid", "employeeNumber" };
        sc.setReturningAttributes(getThese);
        if (inactive) {
            Attributes attrs = ctx.getAttributes("ou=people", getThese);
            users.add(this.createUser(attrs));
        } else {
            NamingEnumeration e = ctx.search("ou=people", "(active=1)", sc);
            while (e.hasMore()) {
                SearchResult sr = (SearchResult) e.next();
                users.add(this.createUser(sr.getAttributes()));
            }
        }
        Collections.sort(users);
        return users;
    } catch (NamingException er) {
        log.error("Could not get users", er);
    } catch (Exception e) {
        log.error("Something else", e);
    }
    return null;
}