Example usage for javax.naming.directory Attribute getAll

List of usage examples for javax.naming.directory Attribute getAll

Introduction

In this page you can find the example usage for javax.naming.directory Attribute getAll.

Prototype

NamingEnumeration<?> getAll() throws NamingException;

Source Link

Document

Retrieves an enumeration of the attribute's values.

Usage

From source file:org.ballerinalang.auth.ldap.nativeimpl.GetLdapScopesOfUser.java

private List<String> getListOfNames(List<String> searchBases, String searchFilter, SearchControls searchCtls,
        String property, boolean appendDn) throws NamingException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Result for searchBase: " + searchBases + " searchFilter: " + searchFilter + " property:"
                + property + " appendDN: " + appendDn);
    }//w  w w  .j a v  a 2 s .c  o m

    List<String> names = new ArrayList<String>();
    NamingEnumeration<SearchResult> answer = null;
    try {
        // handle multiple search bases
        for (String searchBase : searchBases) {
            answer = ldapConnectionContext.search(LdapUtils.escapeDNForSearch(searchBase), searchFilter,
                    searchCtls);
            while (answer.hasMoreElements()) {
                SearchResult searchResult = answer.next();
                if (searchResult.getAttributes() == null) {
                    continue;
                }
                Attribute attr = searchResult.getAttributes().get(property);
                if (attr == null) {
                    continue;
                }
                for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) {
                    String name = (String) vals.nextElement();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Found user: " + name);
                    }
                    names.add(name);
                }
            }

            if (LOG.isDebugEnabled()) {
                for (String name : names) {
                    LOG.debug("Result  :  " + name);
                }
            }
        }
    } finally {
        LdapUtils.closeNamingEnumeration(answer);
    }
    return names;
}

From source file:eu.uqasar.util.ldap.LdapManager.java

public List<LdapUser> getUsersFromGroup(int maximum, LdapGroup group) throws NamingException {
    List<LdapUser> users = new ArrayList<>();
    final String mapping = settings.getGroupMemberMapping();
    javax.naming.directory.Attribute members = group.getMappedAttribute(mapping);
    if (members == null) {
        return users;
    }//from   w w  w  .  j  a v a2s  . co m
    NamingEnumeration<?> results = members.getAll();
    while (results.hasMoreElements() && users.size() < maximum) {
        try {
            final String userDN = (String) results.next();
            LdapUser user = getUserByDNAndFilter(userDN, settings.getUserFilter());
            if (user != null) {
                users.add(user);
            }
        } catch (LdapReferralException ex) {
            logger.warn(ex.getMessage(), ex);
        }
    }
    Collections.sort(users, new LdapUserComparator());
    return users;
}

From source file:org.acegisecurity.userdetails.ldap.LdapUserDetailsMapper.java

public Object mapAttributes(String dn, Attributes attributes) throws NamingException {
    LdapUserDetailsImpl.Essence essence = new LdapUserDetailsImpl.Essence();

    essence.setDn(dn);//from w ww  .  j  a v a 2s. com
    essence.setAttributes(attributes);

    Attribute passwordAttribute = attributes.get(passwordAttributeName);

    if (passwordAttribute != null) {
        essence.setPassword(mapPassword(passwordAttribute));
    }

    // Map the roles
    for (int i = 0; (roleAttributes != null) && (i < roleAttributes.length); i++) {
        Attribute roleAttribute = attributes.get(roleAttributes[i]);

        if (roleAttribute == null) {
            logger.debug("Couldn't read role attribute '" + roleAttributes[i] + "' for user " + dn);
            continue;
        }

        NamingEnumeration attributeRoles = roleAttribute.getAll();

        while (attributeRoles.hasMore()) {
            GrantedAuthority authority = createAuthority(attributeRoles.next());

            if (authority != null) {
                essence.addAuthority(authority);
            } else {
                logger.debug(
                        "Failed to create an authority value from attribute with Id: " + roleAttribute.getID());
            }
        }
    }

    return essence;
}

From source file:org.sipfoundry.sipxconfig.bulk.ldap.UserMapper.java

/**
 * Returns all string values for an attribute with a given name, ignores the values that are
 * not string values// w w w .j  a v a  2s.  co m
 *
 * @param attrs collection of attributes
 * @param attr attribute name
 */
private Set<String> getValues(Attributes attrs, String attrName) throws NamingException {
    Attribute attribute = attrs.get(attrName);
    if (attribute == null) {
        return null;
    }
    Set<String> values = new TreeSet<String>();
    NamingEnumeration<?> allValues = attribute.getAll();
    while (allValues.hasMore()) {
        Object object = allValues.nextElement();
        if (object instanceof String) {
            values.add((String) object);
        }
    }
    return values;
}

From source file:org.apache.hadoop.hdfsproxy.LdapIpDirFilter.java

/**
 * check if client's ip is listed in the Ldap Roles if yes, return true and
 * update ldapent. if not, return false/*w ww. ja v  a  2s. c o m*/
 * */
@SuppressWarnings("unchecked")
private boolean getLdapRoleEntryFromUserIp(String userIp, LdapRoleEntry ldapent) throws NamingException {
    String ipMember = hdfsIpSchemaStrPrefix + userIp;
    Attributes matchAttrs = new BasicAttributes(true);
    matchAttrs.put(new BasicAttribute(hdfsIpSchemaStr, ipMember));
    matchAttrs.put(new BasicAttribute(hdfsUidSchemaStr));
    matchAttrs.put(new BasicAttribute(hdfsPathSchemaStr));

    String[] attrIDs = { hdfsUidSchemaStr, hdfsPathSchemaStr };

    NamingEnumeration<SearchResult> results = lctx.search(baseName, matchAttrs, attrIDs);
    if (results.hasMore()) {
        String userId = null;
        ArrayList<Path> paths = new ArrayList<Path>();
        SearchResult sr = results.next();
        Attributes attrs = sr.getAttributes();
        for (NamingEnumeration ne = attrs.getAll(); ne.hasMore();) {
            Attribute attr = (Attribute) ne.next();
            if (hdfsUidSchemaStr.equalsIgnoreCase(attr.getID())) {
                userId = (String) attr.get();
            } else if (hdfsPathSchemaStr.equalsIgnoreCase(attr.getID())) {
                for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
                    String pathStr = (String) e.next();
                    paths.add(new Path(pathStr));
                }
            }
        }
        ldapent.init(userId, paths);
        if (LOG.isDebugEnabled())
            LOG.debug(ldapent);
        return true;
    }
    LOG.info("Ip address " + userIp + " is not authorized to access the proxy server");
    return false;
}

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  ww  w  .jav  a  2s  .  com*/
        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.craftercms.studio.impl.v1.service.security.DbWithLdapExtensionSecurityProvider.java

private void extractGroupsFromAttribute(User user, String groupNameAttribName, Attribute groupNameAttrib,
        SiteFeed siteFeed) throws NamingException {
    if (groupNameAttrib != null && groupNameAttrib.size() > 0) {
        NamingEnumeration groupAttribValues = groupNameAttrib.getAll();
        while (groupAttribValues.hasMore()) {
            Object groupNameObj = groupAttribValues.next();
            if (groupNameObj != null) {
                String groupName = extractGroupNameFromAttributeValue(groupNameObj.toString());
                if (StringUtils.isNotEmpty(groupName)) {
                    addGroupToUser(user, groupName, siteFeed);
                }//from   ww  w  . j  a v a  2  s  .  c  o m
            }
        }
    } else {
        logger.debug("No LDAP attribute " + groupNameAttribName + " found for username " + user.getUsername());
    }
}

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

private ArrayList<String> addAttributeValues(String attrId, Attributes attrs, ArrayList<String> values)
        throws NamingException {

    if (attrId == null || attrs == null) {
        return values;
    }/*  www .  ja  v a 2 s. c  om*/
    if (values == null) {
        values = new ArrayList<String>();
    }
    Attribute attr = attrs.get(attrId);
    if (attr == null) {
        return (values);
    }
    NamingEnumeration e = attr.getAll();
    while (e.hasMore()) {
        String value = (String) e.next();
        values.add(value);
    }
    return values;
}

From source file:org.wso2.carbon.user.core.ldap.LDAPConnectionContext.java

private void populateDCMap() throws UserStoreException {
    try {/*  w  w w.  j a v a 2 s.  c om*/
        //get the directory context for DNS
        DirContext dnsContext = new InitialDirContext(environmentForDNS);
        //compose the DNS service to be queried
        String DNSServiceName = LDAPConstants.ACTIVE_DIRECTORY_DOMAIN_CONTROLLER_SERVICE + DNSDomainName;
        //query the DNS
        Attributes attributes = dnsContext.getAttributes(DNSServiceName,
                new String[] { LDAPConstants.SRV_ATTRIBUTE_NAME });
        Attribute srvRecords = attributes.get(LDAPConstants.SRV_ATTRIBUTE_NAME);
        //there can be multiple records with same domain name - get them all
        NamingEnumeration srvValues = srvRecords.getAll();
        dcMap = new TreeMap<Integer, SRVRecord>();
        //extract all SRV Records for _ldap._tcp service under the specified domain and populate dcMap
        //int forcedPriority = 0;
        while (srvValues.hasMore()) {
            String value = srvValues.next().toString();
            SRVRecord srvRecord = new SRVRecord();
            String valueItems[] = value.split(" ");
            String priority = valueItems[0];
            if (priority != null) {
                int priorityInt = Integer.parseInt(priority);

                /*if ((priorityInt == forcedPriority) || (priorityInt < forcedPriority)) {
                forcedPriority++;
                priorityInt = forcedPriority;
                }*/
                srvRecord.setPriority(priorityInt);
            } /* else {
              forcedPriority++;
              srvRecord.setPriority(forcedPriority);
              }*/
            String weight = valueItems[1];
            if (weight != null) {
                srvRecord.setWeight(Integer.parseInt(weight));
            }
            String port = valueItems[2];
            if (port != null) {
                srvRecord.setPort(Integer.parseInt(port));
            }
            String host = valueItems[3];
            if (host != null) {
                srvRecord.setHostName(host);
            }
            //we index dcMap on priority basis, therefore, priorities must be different
            dcMap.put(srvRecord.getPriority(), srvRecord);
        }
        //iterate over the SRVRecords for Active Directory Domain Controllers and figure out the
        //host records for that
        for (SRVRecord srvRecord : dcMap.values()) {
            Attributes hostAttributes = dnsContext.getAttributes(srvRecord.getHostName(),
                    new String[] { LDAPConstants.A_RECORD_ATTRIBUTE_NAME });
            Attribute hostRecord = hostAttributes.get(LDAPConstants.A_RECORD_ATTRIBUTE_NAME);
            //we know there is only one IP value for a given host. So we do just get, not getAll
            srvRecord.setHostIP((String) hostRecord.get());
        }
    } catch (NamingException e) {
        log.error("Error obtaining information from DNS Server" + e.getMessage(), e);
        throw new UserStoreException("Error obtaining information from DNS Server " + e.getMessage(), e);
    }
}

From source file:ldap.UserAccountImpl.java

public String toString() {
    StringBuffer buffer = new StringBuffer();
    String name = null;//w w w.  ja va2s  . c o  m
    try {
        NamingEnumeration attList = getAll();
        while (attList.hasMore()) {
            Attribute att = (Attribute) attList.next();
            //if (att.getID().equals(Config.USER_NAMING_ATT))
            if (att.getID().equals(LdapConstants.ldapAttrUid))
                name = att.get().toString() + "\n";

            buffer.append("    ").append(att.getID()).append(": ");

            if (att.size() == 1)
                buffer.append(att.get().toString()).append("\n");
            else {
                NamingEnumeration values = att.getAll();
                buffer.append("\n");
                while (values.hasMore())
                    buffer.append("        ").append(values.next()).append("\n");
            }
        }
        if (name != null)
            buffer.insert(0, name);
    } catch (NamingException e) {
        return "Unexpected Internal Error dumping UserAccount to text.\nError was: " + e.getMessage();
    }
    return buffer.toString();
}