Example usage for javax.naming NamingEnumeration hasMoreElements

List of usage examples for javax.naming NamingEnumeration hasMoreElements

Introduction

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

Prototype

boolean hasMoreElements();

Source Link

Document

Tests if this enumeration contains more elements.

Usage

From source file:com.wfp.utils.LDAPUtils.java

@SuppressWarnings("unchecked")
public static Map<String, Map<String, String>> parseDataAsMap(NamingEnumeration searchResults,
        String optionalKey, String uniqueKey, String[] attrArray) {
    Logger.debug("Formatting the data as MAP", LDAPUtils.class);

    Map<String, Map<String, String>> resultMap = null;

    int totalResultLogger = 0;
    if (searchResults == null) {
        return null;
    }//from  ww w  .j  a  va 2s.  co m

    // Loop through the search results
    while (searchResults.hasMoreElements()) {
        SearchResult sr = null;
        try {
            sr = (SearchResult) searchResults.next();
        } catch (NamingException e1) {
            Logger.error("No Search results on LDAP ", LDAPUtils.class);
        }
        if (sr == null) {
            Logger.error("No Search results on LDAP ", LDAPUtils.class);
            return null;
        }

        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            if (resultMap == null) {
                resultMap = new HashMap<String, Map<String, String>>();
            }
            try {
                Map<String, String> resultAttrMap = new HashMap();
                for (String attr : attrArray) {
                    if (resultAttrMap.get(attr) == null) {
                        attrs.get(attr);
                        resultAttrMap.put(attr, "");
                    }
                }
                for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
                    Attribute attr = (Attribute) ae.next();
                    for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) {
                        String attrValue = (String) e.next();
                        //if it is external id
                        if (attr.getID().equals(EXTERNAL_ID)) {
                            if (attrValue.contains(COMPASS_ID)) {
                                resultAttrMap.put(attr.getID(), attrValue.replace(COMPASS_ID, ""));
                                break;
                            } else
                                resultAttrMap.put(attr.getID(), "inValidFormat");
                        }
                        resultAttrMap.put(attr.getID(), attrValue);
                    }
                }
                if (optionalKey != null && !StringUtils.isNull(resultAttrMap.get(optionalKey))) {
                    resultMap.put(resultAttrMap.get(optionalKey), resultAttrMap);
                } else {
                    resultAttrMap.put("compasId", "");
                    resultMap.put(resultAttrMap.get(uniqueKey), resultAttrMap);
                }

            } catch (NamingException e) {
                Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e);
            }

        } else {
            Logger.info("No attributes found on LDAP", LDAPUtils.class);
        }
    }

    return resultMap;
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

@SuppressWarnings("unchecked")
private SearchResult findUser(String username) throws NamingException, LoginException {
    SearchControls ctls = new SearchControls();
    ctls.setCountLimit(1);/*from  w  w  w.  j a v a 2 s .c  o m*/
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = OBJECT_CLASS_FILTER;

    debug("Searching for users with filter: \'" + filter + "\'" + " from base dn: " + _userBaseDn);

    Object[] filterArguments = new Object[] { _userObjectClass, _userIdAttribute, username };
    NamingEnumeration results = _rootContext.search(_userBaseDn, filter, filterArguments, ctls);

    debug("Found user?: " + results.hasMoreElements());

    if (!results.hasMoreElements()) {
        throw new LoginException("User not found.");
    }

    return (SearchResult) results.nextElement();
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

private ConcurrentHashMap<String, List<String>> buildRoleMemberOfMap(DirContext dirContext) {
    Object[] filterArguments = { _roleObjectClass };
    SearchControls ctls = new SearchControls();
    ctls.setDerefLinkFlag(true);// ww w.  j  av  a 2 s.c o  m
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    ConcurrentHashMap<String, List<String>> roleMemberOfMap = new ConcurrentHashMap<String, List<String>>();

    try {
        NamingEnumeration<SearchResult> results = dirContext.search(_roleBaseDn, _roleMemberFilter, ctls);
        while (results.hasMoreElements()) {
            SearchResult result = results.nextElement();
            Attributes attributes = result.getAttributes();

            if (attributes == null) {
                continue;
            }

            Attribute roleAttribute = attributes.get(_roleNameAttribute);
            Attribute memberAttribute = attributes.get(_roleMemberAttribute);

            if (roleAttribute == null || memberAttribute == null) {
                continue;
            }

            NamingEnumeration role = roleAttribute.getAll();
            NamingEnumeration members = memberAttribute.getAll();

            if (!role.hasMore() || !members.hasMore()) {
                continue;
            }

            String roleName = (String) role.next();
            if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
                roleName = roleName.replace(_rolePrefix, "");
            }

            while (members.hasMore()) {
                String member = (String) members.next();
                Matcher roleMatcher = rolePattern.matcher(member);
                if (!roleMatcher.find()) {
                    continue;
                }
                String roleMember = roleMatcher.group(1);
                List<String> memberOf;
                if (roleMemberOfMap.containsKey(roleMember)) {
                    memberOf = roleMemberOfMap.get(roleMember);
                } else {
                    memberOf = new ArrayList<String>();
                }

                memberOf.add(roleName);

                roleMemberOfMap.put(roleMember, memberOf);
            }

        }
    } catch (NamingException e) {
        e.printStackTrace();
    }
    return roleMemberOfMap;
}

From source file:com.wfp.utils.LDAPUtils.java

public static Map<String, String> parseAsMap(NamingEnumeration searchResults, String keyAttribute,
        String valueAttribute) {/*  ww  w .  j  a  va  2 s  .c o m*/
    Logger.debug("# START parseAsMap : Formatting the data as MAP", LDAPUtils.class);
    //System.out.println("# START parseAsMap : Formatting the data as MAP: "+searchResults );
    Map<String, String> resultMap = new HashMap<String, String>();
    if (searchResults == null) {
        return null;
    }
    // Loop through the search results
    while (searchResults.hasMoreElements()) {
        SearchResult sr = null;
        List<String> strList = new ArrayList<String>();
        try {
            sr = (SearchResult) searchResults.next();

        } catch (NamingException e1) {
            Logger.error("No Search results on LDAP ", LDAPUtils.class);
        }
        if (sr == null) {
            Logger.error("No Search results on LDAP ", LDAPUtils.class);
            return null;
        }
        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            try {
                for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
                    Attribute attr = (Attribute) ae.next();

                    for (NamingEnumeration e = attr.getAll(); e.hasMore(); e.next())
                        ;

                    //System.out.println(" attrs : "+attrs.get(keyAttribute) + ": "+ attrs.get(valueAttribute));
                    //if(attrs.get(keyAttribute)!=null && attrs.get(keyAttribute)!=null)
                    resultMap.put(attrs.get(keyAttribute).toString(), attrs.get(valueAttribute).toString());
                }
            } catch (NamingException ne) {
                ne.printStackTrace();
            }

        } else {
            Logger.info("No attributes found on LDAP", LDAPUtils.class);
        }
    }
    //Logger.debug("# END parseAsMap : Formatting the data as MAP", LDAPUtils.class );
    return resultMap;
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

/**
 * attempts to get the users credentials from the users context
 * <p/>/*from w w w  .j a va  2  s  .  co  m*/
 * NOTE: this is not an user authenticated operation
 *
 * @param username
 * @return
 * @throws LoginException
 */
@SuppressWarnings("unchecked")
private String getUserCredentials(String username) throws LoginException {
    String ldapCredential = null;

    SearchControls ctls = new SearchControls();
    ctls.setCountLimit(1);
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    try {
        Object[] filterArguments = { _userObjectClass, _userIdAttribute, username };
        NamingEnumeration results = _rootContext.search(_userBaseDn, OBJECT_CLASS_FILTER, filterArguments,
                ctls);

        debug("Found user?: " + results.hasMoreElements());

        if (!results.hasMoreElements()) {
            throw new LoginException("User not found.");
        }

        SearchResult result = findUser(username);

        Attributes attributes = result.getAttributes();

        setDemographicAttributes(attributes);
        Attribute attribute = attributes.get(_userPasswordAttribute);
        if (attribute != null) {
            try {
                byte[] value = (byte[]) attribute.get();

                ldapCredential = new String(value);
            } catch (NamingException e) {
                LOG.info("no password available under attribute: " + _userPasswordAttribute);
            }
        }
    } catch (NamingException e) {
        throw new LoginException("Root context binding failure.");
    }

    debug("user cred is present: " + (ldapCredential != null));

    return ldapCredential;
}

From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java

/** Get the AD-derived access tokens for a user and domain */
protected List<String> getADTokens(String userPart, String domainPart, String userName)
        throws NameNotFoundException, NamingException, ManifoldCFException {
    // Now, look through the rules for the matching domain controller
    String domainController = null;
    for (DCRule rule : dCRules) {
        String suffix = rule.getSuffix();
        if (suffix.length() == 0
                || domainPart.toLowerCase(Locale.ROOT).endsWith(suffix.toLowerCase(Locale.ROOT))
                        && (suffix.length() == domainPart.length()
                                || domainPart.charAt((domainPart.length() - suffix.length()) - 1) == '.')) {
            domainController = rule.getDomainControllerName();
            break;
        }//from ww  w . j av  a 2 s  .  c o  m
    }

    if (domainController == null)
        // No AD user
        return null;

    // Look up connection parameters
    DCConnectionParameters dcParams = dCConnectionParameters.get(domainController);
    if (dcParams == null)
        // No AD user
        return null;

    // Use the complete fqn if the field is the "userPrincipalName"
    String userBase;
    String userACLsUsername = dcParams.getUserACLsUsername();
    if (userACLsUsername != null && userACLsUsername.equals("userPrincipalName")) {
        userBase = userName;
    } else {
        userBase = userPart;
    }

    //Build the DN searchBase from domain part
    StringBuilder domainsb = new StringBuilder();
    int j = 0;
    while (true) {
        if (j > 0)
            domainsb.append(",");

        int k = domainPart.indexOf(".", j);
        if (k == -1) {
            domainsb.append("DC=").append(ldapEscape(domainPart.substring(j)));
            break;
        }
        domainsb.append("DC=").append(ldapEscape(domainPart.substring(j, k)));
        j = k + 1;
    }

    // Establish a session with the selected domain controller
    LdapContext ctx = createDCSession(domainController);

    //Get DistinguishedName (for this method we are using DomainPart as a searchBase ie: DC=qa-ad-76,DC=metacarta,DC=com")
    String searchBase = getDistinguishedName(ctx, userBase, domainsb.toString(), userACLsUsername);
    if (searchBase == null)
        return null;

    //specify the LDAP search filter
    String searchFilter = "(objectClass=user)";

    //Create the search controls for finding the access tokens   
    SearchControls searchCtls = new SearchControls();

    //Specify the search scope, must be base level search for tokenGroups
    searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);

    //Specify the attributes to return
    String returnedAtts[] = { "tokenGroups", "objectSid" };
    searchCtls.setReturningAttributes(returnedAtts);

    //Search for tokens.  Since every user *must* have a SID, the "no user" detection should be safe.
    NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);

    List<String> theGroups = new ArrayList<String>();
    String userToken = userTokenFromLoginName(domainPart + "\\" + userPart);
    if (userToken != null)
        theGroups.add(userToken);

    //Loop through the search results
    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        //the sr.GetName should be null, as it is relative to the base object

        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            try {
                for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
                    Attribute attr = (Attribute) ae.next();
                    for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
                        String sid = sid2String((byte[]) e.next());
                        String token = attr.getID().equals("objectSid") ? userTokenFromSID(sid)
                                : groupTokenFromSID(sid);
                        theGroups.add(token);
                    }
                }
            } catch (NamingException e) {
                throw new ManifoldCFException(e.getMessage(), e);
            }
        }
    }

    if (theGroups.size() == 0)
        return null;

    // User is in AD, so add the 'everyone' group
    theGroups.add(everyoneGroup());
    return theGroups;
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

@SuppressWarnings("unchecked")
private List getUserRolesByDn(DirContext dirContext, String userDn, String username)
        throws LoginException, NamingException {
    List<String> roleList = new ArrayList<String>();

    if (dirContext == null || _roleBaseDn == null
            || (_roleMemberAttribute == null && _roleUsernameMemberAttribute == null)
            || _roleObjectClass == null) {
        LOG.warn(//from www. ja  v a  2  s.c  om
                "JettyCachingLdapLoginModule: No user roles found: roleBaseDn, roleObjectClass and roleMemberAttribute or roleUsernameMemberAttribute must be specified.");
        addSupplementalRoles(roleList);
        return roleList;
    }

    String[] attrIDs = { _roleNameAttribute };
    SearchControls ctls = new SearchControls();
    ctls.setReturningAttributes(attrIDs);
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = OBJECT_CLASS_FILTER;
    final NamingEnumeration results;

    if (null != _roleUsernameMemberAttribute) {
        Object[] filterArguments = { _roleObjectClass, _roleUsernameMemberAttribute, username };
        results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
    } else {
        Object[] filterArguments = { _roleObjectClass, _roleMemberAttribute, userDn };
        results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
    }

    while (results.hasMoreElements()) {
        SearchResult result = (SearchResult) results.nextElement();

        Attributes attributes = result.getAttributes();

        if (attributes == null) {
            continue;
        }

        Attribute roleAttribute = attributes.get(_roleNameAttribute);

        if (roleAttribute == null) {
            continue;
        }

        NamingEnumeration roles = roleAttribute.getAll();
        while (roles.hasMore()) {
            if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
                String role = (String) roles.next();
                roleList.add(role.replace(_rolePrefix, ""));
            } else {
                roleList.add((String) roles.next());
            }
        }
    }

    addSupplementalRoles(roleList);

    if (_nestedGroups) {
        roleList = getNestedRoles(dirContext, roleList);
    }

    if (roleList.size() < 1) {
        LOG.warn("JettyCachingLdapLoginModule: User '" + username
                + "' has no role membership; role query configuration may be incorrect");
    } else {
        debug("JettyCachingLdapLoginModule: User '" + username + "' has roles: " + roleList);
    }

    return roleList;
}

From source file:edu.umich.ctools.sectionsUtilityTool.SectionUtilityToolFilter.java

private boolean ldapAuthorizationVerification(String user) {
    M_log.debug("ldapAuthorizationVerification(): called");
    boolean isAuthorized = false;
    DirContext dirContext = null;
    NamingEnumeration listOfPeopleInAuthGroup = null;
    NamingEnumeration allSearchResultAttributes = null;
    NamingEnumeration simpleListOfPeople = null;
    Hashtable<String, String> env = new Hashtable<String, String>();
    if (!isEmpty(providerURL) && !isEmpty(mcommunityGroup)) {
        env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CTX_FACTORY);
        env.put(Context.PROVIDER_URL, providerURL);
    } else {// w w  w.j ava 2  s  .  c  o m
        M_log.error(
                " [ldap.server.url] or [mcomm.group] properties are not set, review the sectionsToolPropsLessSecure.properties file");
        return isAuthorized;
    }
    try {
        dirContext = new InitialDirContext(env);
        String[] attrIDs = { "member" };
        SearchControls searchControls = new SearchControls();
        searchControls.setReturningAttributes(attrIDs);
        searchControls.setReturningObjFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchBase = OU_GROUPS;
        String filter = "(&(cn=" + mcommunityGroup + ") (objectclass=rfc822MailGroup))";
        listOfPeopleInAuthGroup = dirContext.search(searchBase, filter, searchControls);
        String positiveMatch = "uid=" + user + ",";
        outerloop: while (listOfPeopleInAuthGroup.hasMore()) {
            SearchResult searchResults = (SearchResult) listOfPeopleInAuthGroup.next();
            allSearchResultAttributes = (searchResults.getAttributes()).getAll();
            while (allSearchResultAttributes.hasMoreElements()) {
                Attribute attr = (Attribute) allSearchResultAttributes.nextElement();
                simpleListOfPeople = attr.getAll();
                while (simpleListOfPeople.hasMoreElements()) {
                    String val = (String) simpleListOfPeople.nextElement();
                    if (val.indexOf(positiveMatch) != -1) {
                        isAuthorized = true;
                        break outerloop;
                    }
                }
            }
        }
        return isAuthorized;
    } catch (NamingException e) {
        M_log.error("Problem getting attribute:" + e);
        return isAuthorized;
    } finally {
        try {
            if (simpleListOfPeople != null) {
                simpleListOfPeople.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration list \"simpleListOfPeople\" list ",
                    e);
        }
        try {
            if (allSearchResultAttributes != null) {
                allSearchResultAttributes.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"allSearchResultAttributes\" list ",
                    e);
        }
        try {
            if (listOfPeopleInAuthGroup != null) {
                listOfPeopleInAuthGroup.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"listOfPeopleInAuthGroup\" list ",
                    e);
        }
        try {
            if (dirContext != null) {
                dirContext.close();
            }
        } catch (NamingException e) {
            M_log.error("Problem occurred while closing the  \"dirContext\"  object", e);
        }
    }

}

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java

@Override
public User importUser(long ldapServerId, long companyId, String emailAddress, String screenName)
        throws Exception {

    LdapContext ldapContext = null;

    NamingEnumeration<SearchResult> enu = null;

    try {//  ww  w . j a v  a2  s.  c  o  m
        LDAPServerConfiguration ldapServerConfiguration = _ldapServerConfigurationProvider
                .getConfiguration(companyId, ldapServerId);

        String baseDN = ldapServerConfiguration.baseDN();

        ldapContext = _portalLDAP.getContext(ldapServerId, companyId);

        if (ldapContext == null) {
            _log.error("Unable to bind to the LDAP server");

            return null;
        }

        String filter = ldapServerConfiguration.authSearchFilter();

        if (_log.isDebugEnabled()) {
            _log.debug("Search filter before transformation " + filter);
        }

        filter = StringUtil.replace(filter, new String[] { "@company_id@", "@email_address@", "@screen_name@" },
                new String[] { String.valueOf(companyId), emailAddress, screenName });

        LDAPUtil.validateFilter(filter);

        if (_log.isDebugEnabled()) {
            _log.debug("Search filter after transformation " + filter);
        }

        Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId);

        String userMappingsScreenName = GetterUtil.getString(userMappings.getProperty("screenName"));

        userMappingsScreenName = StringUtil.toLowerCase(userMappingsScreenName);

        SearchControls searchControls = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0,
                new String[] { userMappingsScreenName }, false, false);

        enu = ldapContext.search(baseDN, filter, searchControls);

        if (enu.hasMoreElements()) {
            if (_log.isDebugEnabled()) {
                _log.debug("Search filter returned at least one result");
            }

            Binding binding = enu.nextElement();

            Attributes attributes = _portalLDAP.getUserAttributes(ldapServerId, companyId, ldapContext,
                    binding.getNameInNamespace());

            return importUser(ldapServerId, companyId, ldapContext, attributes, null);
        } else {
            return null;
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn("Problem accessing LDAP server " + e.getMessage());
        }

        if (_log.isDebugEnabled()) {
            _log.debug(e, e);
        }

        throw new SystemException("Problem accessing LDAP server " + e.getMessage());
    } finally {
        if (enu != null) {
            enu.close();
        }

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

From source file:com.concursive.connect.web.webdav.servlets.WebdavServlet.java

/**
 * Copy a collection.//  www . j ava2  s  .co  m
 *
 * @param resources Resources implementation to be used
 * @param errorList Hashtable containing the list of errors which occurred
 *                  during the copy operation
 * @param source    Path of the resource to be copied
 * @param dest      Destination path
 * @return Description of the Return Value
 */
private boolean copyResource(DirContext resources, Hashtable errorList, String source, String dest) {

    if (debug > 1) {
        System.out.println("Copy: " + source + " To: " + dest);
    }

    Object object = null;
    try {
        object = resources.lookup(source);
    } catch (NamingException e) {
    }

    if (object instanceof DirContext) {

        try {
            resources.createSubcontext(dest);
        } catch (NamingException e) {
            errorList.put(dest, new Integer(WebdavStatus.SC_CONFLICT));
            return false;
        }

        try {
            NamingEnumeration enum1 = resources.list(source);
            while (enum1.hasMoreElements()) {
                NameClassPair ncPair = (NameClassPair) enum1.nextElement();
                String childDest = dest;
                if (!childDest.equals("/")) {
                    childDest += "/";
                }
                childDest += ncPair.getName();
                String childSrc = source;
                if (!childSrc.equals("/")) {
                    childSrc += "/";
                }
                childSrc += ncPair.getName();
                copyResource(resources, errorList, childSrc, childDest);
            }
        } catch (NamingException e) {
            errorList.put(dest, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
            return false;
        }

    } else {

        if (object instanceof Resource) {
            try {
                resources.bind(dest, object);
            } catch (NamingException e) {
                errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
                return false;
            }
        } else {
            errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
            return false;
        }

    }

    return true;
}