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:catalina.mbeans.GlobalResourcesLifecycleListener.java

/**
 * Create the MBeans for the interesting global JNDI resources in
 * the specified naming context.//from  w  w w  . j ava  2  s . c  o m
 *
 * @param prefix Prefix for complete object name paths
 * @param context Context to be scanned
 *
 * @exception NamingException if a JNDI exception occurs
 */
protected void createMBeans(String prefix, Context context) throws NamingException {

    if (debug >= 1) {
        log("Creating MBeans for Global JNDI Resources in Context '" + prefix + "'");
    }

    NamingEnumeration bindings = context.listBindings("");
    while (bindings.hasMore()) {
        Binding binding = (Binding) bindings.next();
        String name = prefix + binding.getName();
        Object value = context.lookup(binding.getName());
        if (debug >= 2) {
            log("Checking resource " + name);
        }
        if (value instanceof Context) {
            createMBeans(name + "/", (Context) value);
        } else if (value instanceof UserDatabase) {
            try {
                createMBeans(name, (UserDatabase) value);
            } catch (Exception e) {
                log("Exception creating UserDatabase MBeans for " + name, e);
            }
        }
    }

}

From source file:org.springframework.ejb.support.JndiEnvironmentBeanDefinitionReader.java

/**
 * Creates new JNDIBeanFactory//from w w  w.  j  a va  2s .c  o m
 * @param root likely to be "java:comp/env"
 */
public JndiEnvironmentBeanDefinitionReader(BeanDefinitionRegistry beanFactory, String root)
        throws BeansException {
    // We'll take everything from the NamingContext and dump it in a
    // Properties object, so that the superclass can efficiently manipulate it
    // after we've closed the context.
    HashMap m = new HashMap();

    Context initCtx = null;
    try {
        initCtx = new InitialContext();
        // Parameterize
        NamingEnumeration bindings = initCtx.listBindings(root);

        // Orion 1.5.2 doesn't seem to regard anything under a /
        // as a true subcontext, so we need to search all bindings
        // Not all that fast, but it doesn't matter            
        while (bindings.hasMore()) {
            Binding binding = (Binding) bindings.next();
            logger.debug("Name: " + binding.getName());
            logger.debug("Type: " + binding.getClassName());
            logger.debug("Value: " + binding.getObject());
            m.put(binding.getName(), binding.getObject());
        }
        bindings.close();

        PropertiesBeanDefinitionReader propReader = new PropertiesBeanDefinitionReader(beanFactory);
        propReader.registerBeanDefinitions(m, BEANS_PREFIX);
    } catch (NamingException ex) {
        logger.debug("----- NO PROPERTIES FOUND " + ex);
    } finally {
        try {
            if (initCtx != null) {
                initCtx.close();
            }
        } catch (NamingException ex) {
            // IGNORE OR THROW RTE?
        }
    }
}

From source file:org.apache.zeppelin.realm.ActiveDirectoryGroupRealm.java

public List<String> searchForUserName(String containString, LdapContext ldapContext) throws NamingException {
    List<String> userNameList = new ArrayList<>();

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

    String searchFilter = "(&(objectClass=*)(userPrincipalName=*" + containString + "*))";
    Object[] searchArguments = new Object[] { containString };

    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);

    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        if (log.isDebugEnabled()) {
            log.debug("Retrieving userprincipalname names for user [" + sr.getName() + "]");
        }/* ww w . j  a  v  a2s .  co m*/

        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            NamingEnumeration ae = attrs.getAll();
            while (ae.hasMore()) {
                Attribute attr = (Attribute) ae.next();
                if (attr.getID().toLowerCase().equals("cn")) {
                    userNameList.addAll(LdapUtils.getAllAttributeValues(attr));
                }
            }
        }
    }
    return userNameList;
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static String getOrgDN(String organisation, String countryCode) {
    NamingEnumeration results = null;
    DirContext ctx = null;/*  w  ww. jav  a  2  s  .  c om*/
    String dn = null;
    try {
        ctx = getContext();
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String retAttrs[] = { "dn" };
        controls.setReturningAttributes(retAttrs);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        results = ctx.search("c=" + countryCode + "," + rb.getString("organisationsRoot"),
                "(&(objectclass=organization)(o=" + organisation + "))", controls);

        if (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            dn = searchResult.getNameInNamespace();
        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }

    return dn;
}

From source file:org.georchestra.security.LdapUserDetailsRequestHeaderProvider.java

@SuppressWarnings("unchecked")
@Override/* ww  w.ja va2  s  .co  m*/
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.jboss.additional.testsuite.jdkall.present.elytron.sasl.OtpSaslTestCase.java

/**
 * Check correct user attribute values in the LDAP when using OTP algorithm.
 *//*ww w .  j  a v a2  s  .c  o  m*/
private void assertSequenceAndHash(Integer expectedSequence, byte[] expectedHash) throws NamingException {
    final Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, LDAP_URL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    final LdapContext ctx = new InitialLdapContext(env, null);
    NamingEnumeration<?> namingEnum = ctx.search("dc=wildfly,dc=org", new BasicAttributes("cn", "jduke"));
    if (namingEnum.hasMore()) {
        SearchResult sr = (SearchResult) namingEnum.next();
        Attributes attrs = sr.getAttributes();
        assertEquals("Unexpected sequence number in LDAP attribute", expectedSequence,
                new Integer(attrs.get("telephoneNumber").get().toString()));
        assertEquals("Unexpected hash value in LDAP attribute",
                Base64.getEncoder().encodeToString(expectedHash), attrs.get("title").get().toString());
    } else {
        fail("User not found in LDAP");
    }

    namingEnum.close();
    ctx.close();
}

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

/**
 * Returns the CN (common name) for a given login name
 * /*from   ww w  .  j  a  v a 2 s .  c  o  m*/
 * @param loginName
 *            the loginName of the user
 * @return CN as a String(if found), or null (else)
 */
private static String getCn(TSiteBean siteBean, String loginName) throws NamingException {
    String keyDn = null;
    DirContext ctx = getInitialContext(siteBean.getLdapServerURL(), siteBean.getLdapBindDN(),
            siteBean.getLdapBindPassword());
    if (ctx != null) {
        SearchControls ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        // Search for the user-id
        String searchStr = "(" + siteBean.getLdapAttributeLoginName() + "=" + loginName + ")";
        NamingEnumeration<SearchResult> answer = ctx.search("", searchStr, ctls);
        if (answer.hasMore()) {
            // retrieve the CN
            SearchResult sr = answer.next();
            keyDn = sr.getName();// + "," + ctx.getNameInNamespace();
            LOGGER.debug("Name = " + keyDn);
            String nameInNamespace = ctx.getNameInNamespace();
            LOGGER.debug("Name in namespace " + nameInNamespace);
            if (nameInNamespace != null && nameInNamespace.trim().length() > 0) {
                keyDn += "," + ctx.getNameInNamespace();
            }
            LOGGER.debug("entry found for LDAP-search >" + searchStr + "<: dn= >" + keyDn + "<!");
            answer.close(); // wo don't need more answers
        } else {
            LOGGER.debug("no entry found for LDAP-search >" + searchStr + "<!");
        }
        ctx.close();
    }
    return keyDn;
}

From source file:jp.ikedam.jenkins.plugins.ldap_sasl.SearchGroupResolver.java

/**
 * Resolves groups by querying the LDAP directory. 
 * //w w  w  . j a v a2s. c o m
 * Never return null in any case. Returns empty list instead.
 * 
 * @param ctx
 * @param dn
 * @param username
 * @return List of authorities (not null)
 * @see jp.ikedam.jenkins.plugins.ldap_sasl.GroupResolver#resolveGroup(javax.naming.ldap.LdapContext, java.lang.String, java.lang.String)
 */
@Override
public List<GrantedAuthority> resolveGroup(LdapContext ctx, String dn, String username) {
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

    Logger logger = getLogger();

    if (dn == null) {
        logger.warning("Group cannot be resolved: DN of the user is not resolved!");
        return authorities;
    }

    try {
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        logger.fine(String.format("Searching groups base=%s, dn=%s", getSearchBase(), dn));
        NamingEnumeration<SearchResult> entries = ctx.search((getSearchBase() != null) ? getSearchBase() : "",
                getGroupSearchQuery(dn), searchControls);
        while (entries.hasMore()) {
            SearchResult entry = entries.next();
            String groupName = entry.getAttributes().get("cn").get().toString();
            if (getPrefix() != null) {
                groupName = getPrefix() + groupName;
            }
            authorities.add(new GrantedAuthorityImpl(groupName));
            logger.fine(String.format("group: %s", groupName));
        }
        entries.close();
    } catch (NamingException e) {
        logger.log(Level.WARNING, "Failed to search groups", e);
    }

    return authorities;
}

From source file:org.apache.zeppelin.realm.ActiveDirectoryGroupRealm.java

private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
    Set<String> roleNames = new LinkedHashSet<>();

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String userPrincipalName = username;
    if (this.principalSuffix != null && userPrincipalName.indexOf('@') < 0) {
        userPrincipalName += principalSuffix;
    }/*from   w w w  .  ja v a2  s.c  o m*/

    String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";
    Object[] searchArguments = new Object[] { userPrincipalName };

    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);

    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        if (log.isDebugEnabled()) {
            log.debug("Retrieving group names for user [" + sr.getName() + "]");
        }

        Attributes attrs = sr.getAttributes();

        if (attrs != null) {
            NamingEnumeration ae = attrs.getAll();
            while (ae.hasMore()) {
                Attribute attr = (Attribute) ae.next();

                if (attr.getID().equals("memberOf")) {

                    Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);

                    if (log.isDebugEnabled()) {
                        log.debug("Groups found for user [" + username + "]: " + groupNames);
                    }

                    Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
                    roleNames.addAll(rolesForGroups);
                }
            }
        }
    }
    return roleNames;
}

From source file:org.apache.zeppelin.server.ActiveDirectoryGroupRealm.java

private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
    Set<String> roleNames = new LinkedHashSet<>();

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String userPrincipalName = username;
    if (principalSuffix != null) {
        userPrincipalName += principalSuffix;
    }/*from w w w  .  j  a v a  2s  . c  o  m*/

    String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";
    Object[] searchArguments = new Object[] { userPrincipalName };

    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);

    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        if (log.isDebugEnabled()) {
            log.debug("Retrieving group names for user [" + sr.getName() + "]");
        }

        Attributes attrs = sr.getAttributes();

        if (attrs != null) {
            NamingEnumeration ae = attrs.getAll();
            while (ae.hasMore()) {
                Attribute attr = (Attribute) ae.next();

                if (attr.getID().equals("memberOf")) {

                    Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);

                    if (log.isDebugEnabled()) {
                        log.debug("Groups found for user [" + username + "]: " + groupNames);
                    }

                    Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
                    roleNames.addAll(rolesForGroups);
                }
            }
        }
    }
    return roleNames;
}