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:ldap.SearchUtility.java

/**
 * recursively walks the tree to depth 'depth', and returns
 * a list of all names found at that depth.
 * @param treeNode/* w ww .java2 s .c o  m*/
 * @param depth
 * @return
 * @throws NamingException
 */

private List<LdapName> getElementNames(LdapName treeNode, int depth, DirContext context)
        throws NamingException {
    depth--;
    NamingEnumeration<NameClassPair> children = context.list(treeNode);
    List<LdapName> elementNames = new ArrayList<LdapName>();

    // cycle through all the children we've found.
    while (children.hasMore()) {
        NameClassPair child = children.next();
        LdapName childName = new LdapName(child.getNameInNamespace());
        if (depth == 0) // return value - these are what we're looking for!
            elementNames.add(childName);
        else
            elementNames.addAll(getElementNames(childName, depth, context)); // keep going down!
    }

    return elementNames;
}

From source file:ldap.SearchUtility.java

/**
 * This returns a list of all users that match the particular attribute value.
 * Often this will be a single user, in which case the list will only contain one value.  If
 * you know this is the case, use the 'getUser()' form of this method instead.
 * @param attrType//from   w w  w .  jav  a2 s  .  c o m
 * @param attrValue
 * @return
 * @throws NamingException
 */
public List<Entry> getUsers(String attrType, String attrValue, DirContext context) throws NamingException {
    logger.info("getUsers(attrType,attrValue,context)");
    List<Entry> users = new ArrayList<Entry>();
    Attributes atts = new BasicAttributes();
    atts.put(attrType, attrValue);
    //NamingEnumeration<SearchResult> userResults = context.search(new LdapName(Config.SEARCH_BASE_DN), attrType + "={0}", new String[] {attrValue}, getSearchControls());
    NamingEnumeration<SearchResult> userResults = context.search(new LdapName(LdapConstants.ldapSearchBaseDn),
            attrType + "={0}", new String[] { attrValue }, getSearchControls());
    while (userResults.hasMore()) {
        SearchResult userResult = userResults.next();
        users.add(new Entry(userResult));
    }
    return users;
}

From source file:org.kitodo.production.services.data.LdapServerService.java

/**
 * Check if User already exists on system.
 *
 * @param user//from  w w w . ja v  a 2s  .  c  o m
 *            The User.
 * @return result as boolean
 */
public boolean isUserAlreadyExists(User user) {
    Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings(
            user.getLdapGroup().getLdapServer());
    DirContext ctx;
    boolean result = false;
    try {
        ctx = new InitialDirContext(ldapEnvironment);
        Attributes matchAttrs = new BasicAttributes(true);
        NamingEnumeration<SearchResult> answer = ctx.search(buildUserDN(user), matchAttrs);
        result = answer.hasMoreElements();

        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            logger.debug(">>>{}", sr.getName());
            Attributes attrs = sr.getAttributes();
            String givenName = getStringForAttribute(attrs, "givenName");
            String surName = getStringForAttribute(attrs, "sn");
            String mail = getStringForAttribute(attrs, "mail");
            String cn = getStringForAttribute(attrs, "cn");
            String homeDirectory = getStringForAttribute(attrs, "homeDirectory");

            logger.debug(givenName);
            logger.debug(surName);
            logger.debug(mail);
            logger.debug(cn);
            logger.debug(homeDirectory);
        }

        ctx.close();
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }
    return result;
}

From source file:com.evolveum.midpoint.model.common.expression.functions.BasicExpressionFunctions.java

public String determineLdapSingleAttributeValue(String dn, String attributeName, Collection<?> values)
        throws NamingException {
    if (values == null || values.isEmpty()) {
        return null;
    }/*from   w  ww  .  j a va  2s.co  m*/

    Collection<String> stringValues = null;
    // Determine item type, try to convert to strings
    Object firstElement = values.iterator().next();
    if (firstElement instanceof String) {
        stringValues = (Collection) values;
    } else if (firstElement instanceof Element) {
        stringValues = new ArrayList<String>(values.size());
        for (Object value : values) {
            Element element = (Element) value;
            stringValues.add(element.getTextContent());
        }
    } else {
        throw new IllegalArgumentException("Unexpected value type " + firstElement.getClass());
    }

    if (stringValues.size() == 1) {
        return stringValues.iterator().next();
    }

    if (StringUtils.isBlank(dn)) {
        throw new IllegalArgumentException(
                "No dn argument specified, cannot determine which of " + values.size() + " values to use");
    }

    LdapName parsedDn = new LdapName(dn);
    for (int i = 0; i < parsedDn.size(); i++) {
        Rdn rdn = parsedDn.getRdn(i);
        Attributes rdnAttributes = rdn.toAttributes();
        NamingEnumeration<String> rdnIDs = rdnAttributes.getIDs();
        while (rdnIDs.hasMore()) {
            String rdnID = rdnIDs.next();
            Attribute attribute = rdnAttributes.get(rdnID);
            if (attributeName.equals(attribute.getID())) {
                for (int j = 0; j < attribute.size(); j++) {
                    Object value = attribute.get(j);
                    if (stringValues.contains(value)) {
                        return (String) value;
                    }
                }
            }
        }
    }

    // Fallback. No values in DN. Just return the first alphabetically-wise value.
    return Collections.min(stringValues);
}

From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java

/**
 * Retrieves the roles for the from the identity provider.
 *
 * @param username the user to get the roles for
 * @return the list of roles for the user
 * @throws PortalServiceException for any errors encountered
 *//*from www . jav  a2s.c o  m*/
@SuppressWarnings("rawtypes")
public List<String> findRoles(String username) throws PortalServiceException {
    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);

        // Search for groups the user belongs to in order to get their names
        // Create the search controls
        SearchControls groupsSearchCtls = new SearchControls();

        // Specify the search scope
        groupsSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // Specify the attributes to return
        String groupsReturnedAtts[] = { "cn" };
        groupsSearchCtls.setReturningAttributes(groupsReturnedAtts);

        String userDn = MessageFormat.format(userDNPattern, username);
        // Search for objects using the filter
        NamingEnumeration groupsAnswer = ctx.search(groupsSearchBase,
                MessageFormat.format(groupsFilterPattern, userDn), groupsSearchCtls);

        List<String> groups = new ArrayList<String>();
        // Loop through the search results
        while (groupsAnswer.hasMoreElements()) {

            SearchResult sr = (SearchResult) groupsAnswer.next();
            Attributes attrs = sr.getAttributes();

            if (attrs != null) {
                groups.add((String) attrs.get("cn").get());
            }

            if (sr.getObject() instanceof Context) {
                closeContext((Context) sr.getObject());
            }
        }
        return groups;
    } catch (NamingException e) {
        throw new PortalServiceConfigurationException("Unable to get groups.", e);
    } finally {
        closeContext(ctx);
    }
}

From source file:ru.efo.security.ADUserDetailsService.java

private void describeRoles(DirContext context, Attribute memberOf, Set<String> groups, Set<String> roles)
        throws NamingException {
    if (memberOf != null) {
        for (int i = 0; i < memberOf.size(); i++) {
            Attribute attr = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" }).get("CN");
            if (attr != null) {
                final String role = attr.get().toString();
                if (rolesMapping != null) {
                    for (String key : rolesMapping.keySet()) {
                        if (role.matches(rolesMapping.get(key))) {
                            if (logger.isLoggable(Level.FINE)) {
                                if (!roles.contains(key)) {
                                    logger.log(Level.FINE, "Role: " + key);
                                }//from  w ww.  jav  a2s  .  co  m
                            }
                            roles.add(key);
                        }
                    }
                } else {
                    final String roleWithPrefix = (rolePrefix == null ? "" : rolePrefix)
                            + role.toUpperCase().replaceAll("(\\s|-)+", "_");
                    if (logger.isLoggable(Level.FINE)) {
                        if (!roles.contains(role)) {
                            logger.log(Level.FINE, "Role: " + roleWithPrefix);
                        }
                    }
                    roles.add(roleWithPrefix);
                }
                groups.add(role);

                if (recursiveRoleSearch) {
                    SearchControls controls = new SearchControls();
                    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                    NamingEnumeration<SearchResult> renum = context.search(
                            groupSearchBase != null ? groupSearchBase : userSearchBase, "(CN=" + role + ")",
                            controls);
                    if (renum.hasMore()) {
                        SearchResult searchResult = renum.next();
                        attr = searchResult.getAttributes().get("memberOf");
                        describeRoles(context, attr, groups, roles);
                    }
                }
            }
        }
    }
}

From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java

protected boolean authenticate(String username) throws Exception {
    DirContext context = open();//ww  w.  jav  a 2  s. c o  m
    try {

        String filter = userSearchMatchingFormat.format(new String[] { username });
        SearchControls constraints = new SearchControls();
        if (userSearchSubtreeBool) {
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        } else {
            constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }

        // setup attributes
        String[] attribs;
        if (userRoleName == null) {
            attribs = new String[] {};
        } else {
            attribs = new String[] { userRoleName };
        }
        constraints.setReturningAttributes(attribs);

        NamingEnumeration results = context.search(userBase, filter, constraints);

        if (results == null || !results.hasMore()) {
            log.error("No roles associated with user " + username);
            loginSucceeded = false;
            throw new FailedLoginException();
        }

        SearchResult result = (SearchResult) results.next();

        if (results.hasMore()) {
            // ignore for now
        }
        NameParser parser = context.getNameParser("");
        Name contextName = parser.parse(context.getNameInNamespace());
        Name baseName = parser.parse(userBase);
        Name entryName = parser.parse(result.getName());
        Name name = contextName.addAll(baseName);
        name = name.addAll(entryName);
        String dn = name.toString();

        Attributes attrs = result.getAttributes();
        if (attrs == null) {
            return false;
        }
        ArrayList<String> roles = null;
        if (userRoleName != null) {
            roles = addAttributeValues(userRoleName, attrs, roles);
        }
        // check the credentials by binding to server
        // bindUser(context, dn);
        // if authenticated add more roles
        roles = getRoles(context, dn, username, roles);
        for (String role : roles) {
            groups.add(role);
        }
        if (groups.isEmpty()) {
            log.error("No roles associated with user " + username);
            loginSucceeded = false;
            throw new FailedLoginException();
        } else
            loginSucceeded = true;

    } catch (CommunicationException e) {
        close(context);
        throw (LoginException) new FailedLoginException().initCause(e);
    } catch (NamingException e) {
        close(context);
        throw (LoginException) new FailedLoginException().initCause(e);
    }
    return true;
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * check if User already exists on system.
 *
 * @param inLogin// ww w . jav a2  s . co m
 *            String
 * @return path as string
 */
public boolean isUserAlreadyExists(String inLogin) {
    Hashtable<String, String> env = getLdapConnectionSettings();
    env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
    env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));
    DirContext ctx;
    boolean rueckgabe = false;
    try {
        ctx = new InitialDirContext(env);
        Attributes matchAttrs = new BasicAttributes(true);
        NamingEnumeration<SearchResult> answer = ctx.search("ou=users,dc=gdz,dc=sub,dc=uni-goettingen,dc=de",
                matchAttrs);
        rueckgabe = answer.hasMoreElements();

        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            if (logger.isDebugEnabled()) {
                logger.debug(">>>" + sr.getName());
            }
            Attributes attrs = sr.getAttributes();
            String givenName = " ";
            String surName = " ";
            String mail = " ";
            String cn = " ";
            String hd = " ";
            try {
                givenName = attrs.get("givenName").toString();
            } catch (Exception err) {
                givenName = " ";
            }
            try {
                surName = attrs.get("sn").toString();
            } catch (Exception e2) {
                surName = " ";
            }
            try {
                mail = attrs.get("mail").toString();
            } catch (Exception e3) {
                mail = " ";
            }
            try {
                cn = attrs.get("cn").toString();
            } catch (Exception e4) {
                cn = " ";
            }
            try {
                hd = attrs.get("homeDirectory").toString();
            } catch (Exception e4) {
                hd = " ";
            }
            logger.debug(givenName);
            logger.debug(surName);
            logger.debug(mail);
            logger.debug(cn);
            logger.debug(hd);

        }

        ctx.close();
    } catch (NamingException e) {
        logger.error(e);
    }
    return rueckgabe;
}

From source file:org.easy.ldap.AdminServiceImpl.java

@Override
public List<LdapUser> findAllUsers(String tenantId, LdapUser example) {

    NamingEnumeration<SearchResult> result = null;
    List<LdapUser> out = new ArrayList<LdapUser>();

    LdapName rootDn = namingFactory.createUsersDn(tenantId);
    result = ldapDao.findAll(rootDn, LdapDao.toAttributes(example));

    try {//from   ww  w .  j  a  va  2  s.co  m
        while (result.hasMore()) {
            out.add(LdapDao.toModel(tenantId, result.next().getAttributes()));
        }
    } catch (NamingException e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }

    return out;
}

From source file:org.rhq.enterprise.server.core.jaas.LdapLoginModule.java

/**
 * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#validatePassword(java.lang.String,java.lang.String)
 *//*from ww w. ja va2s. c om*/
protected boolean validatePassword(String inputPassword, String expectedPassword) {
    // Load our LDAP specific properties
    Properties env = getProperties();

    // Load the BaseDN
    String baseDN = (String) options.get("BaseDN");
    if (baseDN == null) {
        // If the BaseDN is not specified, log an error and refuse the login attempt
        log.info("BaseDN is not set, refusing login");
        return false;
    }

    // Many LDAP servers allow bind's with an emtpy password. We will deny all requests with empty passwords
    if ((inputPassword == null) || inputPassword.equals("")) {
        log.debug("Empty password, refusing login");
        return false;
    }

    // Load the LoginProperty
    String loginProperty = (String) options.get("LoginProperty");
    if (loginProperty == null) {
        // Use the default
        loginProperty = "cn";
    }

    // Load any search filter
    String searchFilter = (String) options.get("Filter");

    // Find the user that is calling us
    String userName = getUsername();

    // Load any information we may need to bind
    String bindDN = (String) options.get("BindDN");
    String bindPW = (String) options.get("BindPW");
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }

    try {
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        SearchControls searchControls = getSearchControls();

        // Add the search filter if specified.  This only allows for a single search filter.. i.e. foo=bar.
        String filter;
        if ((searchFilter != null) && (searchFilter.length() != 0)) {
            filter = "(&(" + loginProperty + "=" + userName + ")" + "(" + searchFilter + "))";
        } else {
            filter = "(" + loginProperty + "=" + userName + ")";
        }

        log.debug("Using LDAP filter=" + filter);

        // Loop through each configured base DN.  It may be useful
        // in the future to allow for a filter to be configured for
        // each BaseDN, but for now the filter will apply to all.
        String[] baseDNs = baseDN.split(BASEDN_DELIMITER);
        for (int x = 0; x < baseDNs.length; x++) {
            NamingEnumeration answer = ctx.search(baseDNs[x], filter, searchControls);
            boolean ldapApiNpeFound = false;
            if (!answer.hasMoreElements()) {//BZ:582471- ldap api bug
                log.debug("User " + userName + " not found for BaseDN " + baseDNs[x]);

                // Nothing found for this DN, move to the next one if we have one.
                continue;
            }

            // We use the first match
            SearchResult si = (SearchResult) answer.next();

            // Construct the UserDN
            String userDN = si.getName() + "," + baseDNs[x];

            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, inputPassword);
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");

            //if successful then verified that user and pw are valid ldap credentials
            ctx.reconnect(null);

            return true;
        }

        // If we try all the BaseDN's and have not found a match, return false
        return false;
    } catch (Exception e) {
        log.info("Failed to validate password: " + e.getMessage());
        return false;
    }
}