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.aurel.track.util.LdapUtil.java

static TPersonBean getLdapUser(String providerUrl, String bindDN, String bindPassword,
        String loginAttributeName, String searchStr) throws Exception {
    LdapContext ctx = null;/*from   w w w  .  j ava  2 s  .c o  m*/
    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:com.aurel.track.util.LdapUtil.java

/**
 * Gets all persons for a group//ww  w.j  a  v  a2 s  .c  o m
 * 
 * @param groups
 * @param siteBean
 * @param filter
 * @return
 * @throws Exception
 */
static List<TPersonBean> getAllLdapUsersDescendants(String providerUrl, String bindDN, String bindPassword,
        String loginAttributeName, String filter) throws Exception {
    List<TPersonBean> personBeans = new ArrayList<TPersonBean>();
    if (filter == null || "".equals(filter) || "*".equals(filter)) {
        filter = loginAttributeName + "=*";
    }
    int recordCount = 0;
    SearchControls ctls = null;
    LdapContext ctx = null;
    try {
        ctx = getInitialContext(providerUrl, bindDN, bindPassword);
        if (ctx == null) {
            return personBeans;
        }
        // Activate paged results
        int pageSize = 5;
        // TODO replace for GROOVY
        ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
        int total;
        String searchStr = "(" + filter + ")";
        // 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
        if (ldapMap == null || ldapMap.isEmpty()) {
            LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!");
            return personBeans;
        }
        String firstNameAttributeName = ldapMap.get("firstName");
        String lastNameAttributName = ldapMap.get("lastName");
        String emailAttributeName = ldapMap.get("email");
        String phoneAttributName = ldapMap.get("phone");
        byte[] cookie = null;
        // TODO replace for GROOVY
        cookie = new byte[] {};
        // cookie = [] as byte[];
        while (cookie != null) {
            NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls);
            while (results != null && results.hasMore()) {
                SearchResult sr = (SearchResult) results.next();
                TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName,
                        lastNameAttributName, emailAttributeName, phoneAttributName);
                if (personBean != null) {
                    personBeans.add(personBean);
                    ++recordCount;
                }
            }
            // Examine the paged results control response
            Control[] controls = ctx.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
            // TODO replace for GROOVY
            ctx.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
        }
    } 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 {
        if (ctx != null) {
            ctx.close();
        }
    }
    return personBeans;
}

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());//from w  w w  .  j av a  2s .  c  om
    }

    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:edu.internet2.middleware.subject.provider.ESCOJNDISourceAdapter.java

/**
 * {@inheritDoc}/* w w  w.j a v  a2 s  .c  om*/
 */
@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 .  ja  v  a 2  s .  co  m*/
 */
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// ww  w  .  ja v  a 2  s.com
 */
@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.springsource.insight.plugin.ldap.TestLdapContext.java

private void logAttributes(String location, Attributes attrs) throws NamingException {
    NamingEnumeration<? extends Attribute> values = attrs.getAll();
    try {/*from   w  ww  .jav  a2  s. co  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.georchestra.security.LdapUserDetailsRequestHeaderProvider.java

@SuppressWarnings("unchecked")
@Override/*from w w w. j  a  va  2 s  . c om*/
protected Collection<Header> getCustomRequestHeaders(HttpSession session, HttpServletRequest originalRequest) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication instanceof AnonymousAuthenticationToken) {
        return Collections.emptyList();
    }
    String username = authentication.getName();
    DirContextOperations userData;

    Collection<Header> headers = Collections.emptyList();

    synchronized (session) {

        if (session.getAttribute("security-proxy-cached-attrs") != null) {
            try {
                headers = (Collection<Header>) session.getAttribute("security-proxy-cached-attrs");
                String expectedUsername = (String) session.getAttribute("security-proxy-cached-username");

                if (username.equals(expectedUsername)) {
                    return headers;
                }
            } catch (Exception e) {
                logger.info("Unable to lookup cached user's attributes for user :" + username, e);
            }
        } else {
            try {
                userData = _userSearch.searchForUser(username);
            } catch (Exception e) {
                logger.info("Unable to lookup user:" + username, e);
                return Collections.emptyList();
            }
            headers = new ArrayList<Header>();
            for (Map.Entry<String, String> entry : _headerMapping.entrySet()) {
                try {
                    Attribute attributes = userData.getAttributes().get(entry.getValue());
                    if (attributes != null) {
                        NamingEnumeration<?> all = attributes.getAll();
                        StringBuilder value = new StringBuilder();
                        while (all.hasMore()) {
                            if (value.length() > 0) {
                                value.append(',');
                            }
                            value.append(all.next());
                        }
                        headers.add(new BasicHeader(entry.getKey(), value.toString()));
                    }
                } catch (javax.naming.NamingException e) {
                    logger.error("problem adding headers for request:" + entry.getKey(), e);
                }
            }

            // Add user organization
            try {
                // Retreive memberOf attributes
                String[] attrs = { "memberOf" };
                ((FilterBasedLdapUserSearch) this._userSearch).setReturningAttributes(attrs);
                userData = _userSearch.searchForUser(username);
                Attribute attributes = userData.getAttributes().get("memberOf");
                if (attributes != null) {
                    NamingEnumeration<?> all = attributes.getAll();

                    while (all.hasMore()) {
                        String memberOf = all.next().toString();
                        Matcher m = this.pattern.matcher(memberOf);
                        if (m.matches()) {
                            headers.add(new BasicHeader("sec-org", m.group(2)));
                            break;
                        }
                    }
                }
            } catch (javax.naming.NamingException e) {
                logger.error("problem adding headers for request: organization", e);
            } finally {
                // restore standard attribute list
                ((FilterBasedLdapUserSearch) this._userSearch).setReturningAttributes(null);
            }

            logger.info("Storing attributes into session for user :" + username);
            session.setAttribute("security-proxy-cached-username", username);
            session.setAttribute("security-proxy-cached-attrs", headers);
        }
    }

    return headers;
}

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();/*  ww w .  ja va2 s .c  o m*/
    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:jp.ikedam.jenkins.plugins.ldap_sasl.SearchUserDnResolver.java

/**
 * Resolve the user DN by querying the LDAP directory.
 * /*from   w w  w  .  j  a v a 2  s  .com*/
 * @param ctx LDAP context, already authenticated.
 * @param username the username the user authenticated with.
 * 
 * @return the DN of the user.
 * @see jp.ikedam.jenkins.plugins.ldap_sasl.UserDnResolver#getUserDn(javax.naming.ldap.LdapContext, java.lang.String)
 */
@Override
public String getUserDn(LdapContext ctx, String username) {
    Logger logger = getLogger();
    if (StringUtils.isBlank(getSearchQueryTemplate())) {
        // not configured.
        logger.severe("Not configured.");

        return null;
    }

    try {
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        logger.fine(String.format("Searching users base=%s, username=%s", getSearchBase(), username));
        String query = expandUsername(getSearchQueryTemplate(), username);
        NamingEnumeration<SearchResult> entries = ctx.search((getSearchBase() != null) ? getSearchBase() : "",
                query, searchControls);
        if (!entries.hasMore()) {
            // no entry.
            logger.severe(String.format("User not found: %s", username));
            return null;
        }

        String userDn = entries.next().getNameInNamespace();

        if (entries.hasMore()) {
            // more than one entry.
            logger.severe(String.format("User found more than one: %s", username));
            return null;
        }
        entries.close();

        return userDn;
    } catch (NamingException e) {
        logger.log(Level.SEVERE, "Failed to search a user", e);
        return null;
    }
}