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:com.wfp.utils.LDAPUtils.java

public static Map<String, Object> parseDataAsMap(NamingEnumeration searchResults, String listValues) {
    //Logger.info("Formatting the data as MAP", LDAPUtils.class);
    Map<String, Object> resultAttrMap = null;
    int totalResultLogger = 0;
    if (searchResults == null) {
        return null;
    }//from   ww w  .java 2 s . com
    // 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 (resultAttrMap == null) {
                resultAttrMap = new HashMap<String, Object>();
            }
            try {
                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();
                        List<String> attrValuesList = null;
                        if (listValues.indexOf(attr.getID()) >= 0) {
                            attrValuesList = resultAttrMap.get(attr.getID()) == null ? null
                                    : (List<String>) resultAttrMap.get(attr.getID());
                            if (attrValuesList == null) {
                                attrValuesList = new ArrayList<String>();
                            }
                            attrValuesList.add(attrValue);
                            resultAttrMap.put(attr.getID(), attrValuesList);
                        } else {
                            resultAttrMap.put(attr.getID(), attrValue);
                        }
                    }
                }
            } 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 resultAttrMap;
}

From source file:org.apache.cxf.sts.claims.LdapClaimsHandler.java

public ProcessedClaimCollection retrieveClaimValues(ClaimCollection claims, ClaimsParameters parameters) {
    String user = null;/*from w ww. j  a v a  2s .  c o  m*/
    boolean useLdapLookup = false;

    Principal principal = parameters.getPrincipal();
    if (principal instanceof KerberosPrincipal) {
        KerberosPrincipal kp = (KerberosPrincipal) principal;
        StringTokenizer st = new StringTokenizer(kp.getName(), "@");
        user = st.nextToken();
    } else if (principal instanceof X500Principal) {
        X500Principal x500p = (X500Principal) principal;
        LOG.warning("Unsupported principal type X500: " + x500p.getName());
        return new ProcessedClaimCollection();
    } else if (principal != null) {
        user = principal.getName();
        if (user == null) {
            LOG.warning("User must not be null");
            return new ProcessedClaimCollection();
        }
        useLdapLookup = LdapUtils.isDN(user);

    } else {
        LOG.warning("Principal is null");
        return new ProcessedClaimCollection();
    }

    if (LOG.isLoggable(Level.FINEST)) {
        LOG.finest("Retrieve claims for user " + user);
    }

    Map<String, Attribute> ldapAttributes = null;
    if (useLdapLookup) {
        AttributesMapper mapper = new AttributesMapper() {
            public Object mapFromAttributes(Attributes attrs) throws NamingException {
                Map<String, Attribute> map = new HashMap<String, Attribute>();
                NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
                while (attrEnum.hasMore()) {
                    Attribute att = attrEnum.next();
                    map.put(att.getID(), att);
                }
                return map;
            }
        };

        Object result = ldap.lookup(user, mapper);
        ldapAttributes = CastUtils.cast((Map<?, ?>) result);
    } else {
        List<String> searchAttributeList = new ArrayList<String>();
        for (Claim claim : claims) {
            if (getClaimsLdapAttributeMapping().keySet().contains(claim.getClaimType().toString())) {
                searchAttributeList.add(getClaimsLdapAttributeMapping().get(claim.getClaimType().toString()));
            } else {
                if (LOG.isLoggable(Level.FINER)) {
                    LOG.finer("Unsupported claim: " + claim.getClaimType());
                }
            }
        }

        String[] searchAttributes = null;
        searchAttributes = searchAttributeList.toArray(new String[searchAttributeList.size()]);

        ldapAttributes = LdapUtils.getAttributesOfEntry(ldap, this.userBaseDn, this.getObjectClass(),
                this.getUserNameAttribute(), user, searchAttributes);
    }

    if (ldapAttributes == null || ldapAttributes.size() == 0) {
        //No result
        if (LOG.isLoggable(Level.INFO)) {
            LOG.finest("User '" + user + "' not found");
        }
        return new ProcessedClaimCollection();
    }

    ProcessedClaimCollection claimsColl = new ProcessedClaimCollection();

    for (Claim claim : claims) {
        URI claimType = claim.getClaimType();
        String ldapAttribute = getClaimsLdapAttributeMapping().get(claimType.toString());
        Attribute attr = ldapAttributes.get(ldapAttribute);
        if (attr == null) {
            if (LOG.isLoggable(Level.FINEST)) {
                LOG.finest("Claim '" + claim.getClaimType() + "' is null");
            }
        } else {
            ProcessedClaim c = new ProcessedClaim();
            c.setClaimType(claimType);
            c.setPrincipal(principal);

            StringBuilder claimValue = new StringBuilder();
            try {
                NamingEnumeration<?> list = (NamingEnumeration<?>) attr.getAll();
                while (list.hasMore()) {
                    Object obj = list.next();
                    if (!(obj instanceof String)) {
                        LOG.warning("LDAP attribute '" + ldapAttribute + "' has got an unsupported value type");
                        break;
                    }
                    String itemValue = (String) obj;
                    if (this.isX500FilterEnabled()) {
                        try {
                            X500Principal x500p = new X500Principal(itemValue);
                            itemValue = x500p.getName();
                            int index = itemValue.indexOf('=');
                            itemValue = itemValue.substring(index + 1, itemValue.indexOf(',', index));
                        } catch (Exception ex) {
                            //Ignore, not X500 compliant thus use the whole string as the value
                        }
                    }
                    claimValue.append(itemValue);
                    if (list.hasMore()) {
                        claimValue.append(this.getDelimiter());
                    }
                }
            } catch (NamingException ex) {
                LOG.warning("Failed to read value of LDAP attribute '" + ldapAttribute + "'");
            }

            c.addValue(claimValue.toString());
            // c.setIssuer(issuer);
            // c.setOriginalIssuer(originalIssuer);
            // c.setNamespace(namespace);
            claimsColl.add(c);
        }
    }

    return claimsColl;
}

From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java

public List<String> getGroupsMember(String group, DirContext context) throws MappingException {

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {/* www. jav  a2s.co m*/

        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String filter = "objectClass=" + getLdapGroupClass();

        namingEnumeration = context.search("cn=" + group + "," + getGroupsDn(), filter, searchControls);

        List<String> allMembers = new ArrayList<String>();

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();

            Attribute uniqueMemberAttr = searchResult.getAttributes().get(getLdapGroupMember());

            if (uniqueMemberAttr != null) {
                NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr
                        .getAll();
                while (allMembersEnum.hasMore()) {
                    String userName = allMembersEnum.next();
                    // uid=blabla we only want bla bla
                    userName = StringUtils.substringAfter(userName, "=");
                    userName = StringUtils.substringBefore(userName, ",");
                    log.debug("found userName for group {}: '{}", group, userName);

                    allMembers.add(userName);
                }
                close(allMembersEnum);
            }

        }

        return allMembers;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    }

    finally {
        close(namingEnumeration);
    }
}

From source file:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java

/**
 * Gathers attributes from JNDI storage to the supplied attributes object.
 * @see com.alfaariss.oa.engine.core.attribute.gather.processor.IProcessor#process(java.lang.String, com.alfaariss.oa.api.attribute.IAttributes)
 *///from w ww  .  ja  v  a  2s.c o  m
public void process(String sUserId, IAttributes oAttributes) throws AttributeException {
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new AttributeException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        if (_listGather.size() > 0) {
            String[] saAttributes = _listGather.toArray(new String[0]);
            oScope.setReturningAttributes(saAttributes);
        }

        String searchFilter = resolveSearchQuery(sUserId);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(searchFilter);
            sbFailed.append(" while searching for attributes for id: ");
            sbFailed.append(sUserId);
            _logger.error(sbFailed.toString(), e);
            throw new AttributeException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        } catch (NamingException e) {
            _logger.debug("User unknown: " + sUserId);
            return;
        }

        if (oNamingEnumeration.hasMore()) {
            SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();
            Attributes oSearchedAttributes = oSearchResult.getAttributes();
            NamingEnumeration neAttributes = oSearchedAttributes.getAll();
            while (neAttributes.hasMore()) {
                Attribute oAttribute = (Attribute) neAttributes.next();
                String sAttributeName = oAttribute.getID();
                String sMappedName = _htMapper.get(sAttributeName);
                if (sMappedName != null)
                    sAttributeName = sMappedName;

                if (oAttribute.size() > 1) {
                    Vector<Object> vValue = new Vector<Object>();
                    NamingEnumeration neAttribute = oAttribute.getAll();
                    while (neAttribute.hasMore())
                        vValue.add(neAttribute.next());

                    oAttributes.put(sAttributeName, vValue);
                } else {
                    Object oValue = oAttribute.get();
                    if (oValue == null)
                        oValue = "";
                    oAttributes.put(sAttributeName, oValue);
                }
            }
        }
    } catch (AttributeException e) {
        throw e;
    } catch (NamingException e) {
        _logger.debug("Failed to fetch attributes for user: " + sUserId, e);
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields for user with id: " + sUserId, e);
        throw new AttributeException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + sUserId,
                        e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + sUserId, e);
            }
        }
    }
}

From source file:net.spfbl.core.Analise.java

public static TreeSet<String> getIPv4Set(String hostname) {
    TreeSet<String> ipv4Set = new TreeSet<String>();
    try {//from   ww w . j ava 2  s  .com
        Attributes attributesA = Server.getAttributesDNS(hostname, new String[] { "A" });
        if (attributesA != null) {
            Enumeration enumerationA = attributesA.getAll();
            while (enumerationA.hasMoreElements()) {
                Attribute attributeA = (Attribute) enumerationA.nextElement();
                NamingEnumeration enumeration = attributeA.getAll();
                while (enumeration.hasMoreElements()) {
                    String address = (String) enumeration.next();
                    if (SubnetIPv4.isValidIPv4(address)) {
                        address = SubnetIPv4.normalizeIPv4(address);
                        ipv4Set.add(address);
                    }
                }
            }
        }
    } catch (NameNotFoundException ex) {
        return null;
    } catch (NamingException ex) {
        // Ignore.
    }
    return ipv4Set;
}

From source file:net.spfbl.core.Analise.java

public static TreeSet<String> getIPv6Set(String hostname) {
    TreeSet<String> ipv6Set = new TreeSet<String>();
    try {//w w w. ja  va  2 s.c o m
        Attributes attributesAAAA = Server.getAttributesDNS(hostname, new String[] { "AAAA" });
        if (attributesAAAA != null) {
            Enumeration enumerationAAAA = attributesAAAA.getAll();
            while (enumerationAAAA.hasMoreElements()) {
                Attribute attributeAAAA = (Attribute) enumerationAAAA.nextElement();
                NamingEnumeration enumeration = attributeAAAA.getAll();
                while (enumeration.hasMoreElements()) {
                    String address = (String) enumeration.next();
                    if (SubnetIPv6.isValidIPv6(address)) {
                        address = SubnetIPv6.normalizeIPv6(address);
                        ipv6Set.add(address);
                    }
                }
            }
        }
    } catch (NameNotFoundException ex) {
        return null;
    } catch (NamingException ex) {
        // Ignore.
    }
    return ipv6Set;
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * This method will perform multiple queries into Active Directory
 * in order to resolve what groups a user is a member of.  The
 * logic will identify nested groups and add them to the table.
 * <p>//from  w  w  w .j  a v  a 2s .  c o m
 * The LDAP_ACCOUNT_NAME field must be populated in the user bag
 * prior to invoking this method.  Any site specific fields can be
 * assigned to the user bag will be included in the attribute query.
 * </p>
 * <p>
 * Any site specific fields can be assigned to the group bag will
 * be included in the attribute query.
 * </p>
 *
 * @param aUserBag Active Directory user attributes.
 * @param aGroupBag Active Directory group attributes.
 *
 * @return Table of groups that the user is a member of.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 */
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
public DataTable loadUserGroupsByAccountName(DataBag aUserBag, DataBag aGroupBag) throws NSException {
    byte[] objectSid;
    DataBag groupBag;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Logger appLogger = mAppMgr.getLogger(this, "loadUserGroupsByAccountName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    // First, we will populate our user bag so that we can obtain the distinguished name.

    loadUserByAccountName(aUserBag);

    // Now we will use the DN to find all of the groups the user is a member of.

    String distinguishedName = aUserBag.getValueAsString(LDAP_DISTINGUISHED_NAME);
    if (StringUtils.isEmpty(distinguishedName))
        distinguishedName = getPropertyValue("user_searchbasedn", null);

    // Next, we will initialize our group membership table.

    DataTable memberTable = new DataTable(aUserBag);
    memberTable.setName(String.format("%s Group Membership", aUserBag.getValueAsString(LDAP_COMMON_NAME)));

    // The next logic section will query AD for all of the groups the user is a member
    // of.  Because we are following tokenGroups, we will gain access to nested groups.

    String groupSearchBaseDN = getPropertyValue("group_searchbasedn", null);

    SearchControls userSearchControls = new SearchControls();
    userSearchControls.setSearchScope(SearchControls.OBJECT_SCOPE);

    StringBuffer groupsSearchFilter = null;
    String ldapAttrNames[] = { "tokenGroups" };
    userSearchControls.setReturningAttributes(ldapAttrNames);

    try {
        NamingEnumeration<?> userSearchResponse = mLdapContext.search(distinguishedName, "(objectClass=user)",
                userSearchControls);
        if ((userSearchResponse != null) && (userSearchResponse.hasMoreElements())) {
            groupsSearchFilter = new StringBuffer();
            groupsSearchFilter.append("(|");

            SearchResult userSearchResult = (SearchResult) userSearchResponse.next();
            Attributes userResultAttributes = userSearchResult.getAttributes();
            if (userResultAttributes != null) {
                try {
                    for (NamingEnumeration<?> searchResultAttributesAll = userResultAttributes
                            .getAll(); searchResultAttributesAll.hasMore();) {
                        Attribute attr = (Attribute) searchResultAttributesAll.next();
                        for (NamingEnumeration<?> namingEnumeration = attr.getAll(); namingEnumeration
                                .hasMore();) {
                            objectSid = (byte[]) namingEnumeration.next();
                            groupsSearchFilter.append("(objectSid=" + objectSidToString2(objectSid) + ")");
                        }
                        groupsSearchFilter.append(")");
                    }
                } catch (NamingException e) {
                    String msgStr = String.format("LDAP Listing Member Exception: %s", e.getMessage());
                    appLogger.error(msgStr, e);
                    throw new NSException(msgStr);
                }
            }
            userSearchResponse.close();

            // Finally, we will query each group in the search filter and add it to the table.

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

            int field = 0;
            int attrCount = aGroupBag.count();
            String[] groupsReturnedAtts = new String[attrCount];
            for (DataField complexField : aGroupBag.getFields()) {
                fieldName = complexField.getName();
                groupsReturnedAtts[field++] = fieldName;
            }
            groupSearchControls.setReturningAttributes(groupsReturnedAtts);
            NamingEnumeration<?> groupSearchResponse = mLdapContext.search(groupSearchBaseDN,
                    groupsSearchFilter.toString(), groupSearchControls);
            while ((groupSearchResponse != null) && (groupSearchResponse.hasMoreElements())) {
                SearchResult groupSearchResult = (SearchResult) groupSearchResponse.next();
                Attributes groupResultAttributes = groupSearchResult.getAttributes();
                if (groupResultAttributes != null) {
                    groupBag = new DataBag(aGroupBag);
                    for (DataField complexField : groupBag.getFields()) {
                        fieldName = complexField.getName();
                        responseAttribute = groupResultAttributes.get(fieldName);
                        if (responseAttribute != null) {
                            if (fieldName.equals(LDAP_OBJECT_SID)) {
                                objectSid = (byte[]) responseAttribute.get();
                                fieldValue = objectSidToString2(objectSid);
                            } else
                                fieldValue = (String) responseAttribute.get();
                            if (StringUtils.isNotEmpty(fieldValue))
                                complexField.setValue(fieldValue);
                        }
                    }
                    memberTable.addRow(groupBag);
                }
            }
            if (groupSearchResponse != null)
                groupSearchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", distinguishedName, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return memberTable;
}

From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java

public List<String> getGroups(String username, DirContext context) throws MappingException {

    List<String> userGroups = new ArrayList<String>();

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {/* w  w w . j  a v a 2s .  c  o m*/

        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String groupEntry = null;
        try {
            //try to look the user up
            User user = userManager.findUser(username);
            if (user instanceof LdapUser) {
                LdapUser ldapUser = LdapUser.class.cast(user);
                Attribute dnAttribute = ldapUser.getOriginalAttributes().get(getLdapDnAttribute());
                if (dnAttribute != null) {
                    groupEntry = String.class.cast(dnAttribute.get());
                }

            }
        } catch (UserNotFoundException e) {
            log.warn("Failed to look up user {}. Computing distinguished name manually", username, e);
        } catch (UserManagerException e) {
            log.warn("Failed to look up user {}. Computing distinguished name manually", username, e);
        }
        if (groupEntry == null) {
            //failed to look up the user's groupEntry directly
            StringBuilder builder = new StringBuilder();
            String posixGroup = "posixGroup";
            if (posixGroup.equals(getLdapGroupClass())) {
                builder.append(username);
            } else {
                builder.append(this.userIdAttribute).append("=").append(username).append(",")
                        .append(getBaseDn());
            }
            groupEntry = builder.toString();
        }

        String filter = new StringBuilder().append("(&").append("(objectClass=" + getLdapGroupClass() + ")")
                .append("(").append(getLdapGroupMember()).append("=").append(Rdn.escapeValue(groupEntry))
                .append(")").append(")").toString();

        log.debug("filter: {}", filter);

        namingEnumeration = context.search(getGroupsDn(), filter, searchControls);

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();

            List<String> allMembers = new ArrayList<String>();

            Attribute uniqueMemberAttr = searchResult.getAttributes().get(getLdapGroupMember());

            if (uniqueMemberAttr != null) {
                NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr
                        .getAll();
                while (allMembersEnum.hasMore()) {

                    String userName = allMembersEnum.next();
                    //the original dn
                    allMembers.add(userName);
                    // uid=blabla we only want bla bla
                    userName = StringUtils.substringAfter(userName, "=");
                    userName = StringUtils.substringBefore(userName, ",");
                    allMembers.add(userName);
                }
                close(allMembersEnum);
            }

            if (allMembers.contains(username)) {
                String groupName = searchResult.getName();
                // cn=blabla we only want bla bla
                groupName = StringUtils.substringAfter(groupName, "=");
                userGroups.add(groupName);

            } else if (allMembers.contains(groupEntry)) {
                String groupName = searchResult.getName();
                // cn=blabla we only want bla bla
                groupName = StringUtils.substringAfter(groupName, "=");
                userGroups.add(groupName);
            }

        }

        return userGroups;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    } finally {
        close(namingEnumeration);
    }
}

From source file:net.spfbl.core.Analise.java

public static TreeSet<String> getIPSet(String hostname) {
    TreeSet<String> ipSet = new TreeSet<String>();
    try {/*  w ww .j  av  a  2s. co m*/
        Attributes attributesA = Server.getAttributesDNS(hostname, new String[] { "A" });
        if (attributesA != null) {
            Enumeration enumerationA = attributesA.getAll();
            while (enumerationA.hasMoreElements()) {
                Attribute attributeA = (Attribute) enumerationA.nextElement();
                NamingEnumeration enumeration = attributeA.getAll();
                while (enumeration.hasMoreElements()) {
                    String address = (String) enumeration.next();
                    if (SubnetIPv4.isValidIPv4(address)) {
                        address = SubnetIPv4.normalizeIPv4(address);
                        ipSet.add(address);
                    }
                }
            }
        }
        Attributes attributesAAAA = Server.getAttributesDNS(hostname, new String[] { "AAAA" });
        if (attributesAAAA != null) {
            Enumeration enumerationAAAA = attributesAAAA.getAll();
            while (enumerationAAAA.hasMoreElements()) {
                Attribute attributeAAAA = (Attribute) enumerationAAAA.nextElement();
                NamingEnumeration enumeration = attributeAAAA.getAll();
                while (enumeration.hasMoreElements()) {
                    String address = (String) enumeration.next();
                    if (SubnetIPv6.isValidIPv6(address)) {
                        address = SubnetIPv6.normalizeIPv6(address);
                        ipSet.add(address);
                    }
                }
            }
        }
    } catch (NameNotFoundException ex) {
        return null;
    } catch (NamingException ex) {
        // Ignore.
    }
    return ipSet;
}

From source file:it.webappcommon.lib.LDAPHelper.java

/**
 * @param args/*from   ww  w  . ja  v a2  s. c  o  m*/
 *            the command line arguments
 */
// public static void main(String[] args) {
private List<UserInfo> search(String filter) throws NamingException {
    DirContext ctx = null;
    SearchControls ctls = null;
    Properties env = new Properties();
    List<UserInfo> res = new ArrayList<UserInfo>();
    boolean trovatiRisultati = false;

    env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT);

    env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port);

    env.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (org.apache.commons.lang3.StringUtils.isEmpty(loginDomain)) {
        env.put(Context.SECURITY_PRINCIPAL, loginUserName);
    } else {
        env.put(Context.SECURITY_PRINCIPAL, loginDomain + "\\" + loginUserName);
    }
    env.put(Context.SECURITY_CREDENTIALS, loginPassword);

    try {
        ctx = new InitialDirContext(env);

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

        // String filter = "";
        // // filter = "(&(objectClass=inetOrgPerson)(objectClass=person))";
        // filter = FILTER_USERS_ACTIVE;

        // Tutti i membri di un gruppo
        // (objectCategory=user)(memberOf=CN=QA Users,OU=Help
        // Desk,DC=dpetri,DC=net)

        // ESEMPI
        // http://www.petri.co.il/ldap_search_samples_for_windows_2003_and_exchange.htm

        // Account disabled
        // (UserAccountControl:1.2.840.113556.1.4.803:=2)

        NamingEnumeration<SearchResult> answer = ctx.search(areaWhereSearch, filter, ctls);

        UserInfo userInfo = null;
        while (answer.hasMoreElements()) {
            trovatiRisultati = true;

            SearchResult a = answer.nextElement();
            // logger.debug(a.getNameInNamespace());

            Attributes result = a.getAttributes();

            if (result == null) {
                // System.out.print("Attributi non presenti");
            } else {
                NamingEnumeration<? extends Attribute> attributi = result.getAll();

                userInfo = new UserInfo();
                while (attributi.hasMoreElements()) {
                    Attribute att = attributi.nextElement();
                    // logger.debug(att.getID());

                    String value = "";
                    // for (NamingEnumeration vals = att.getAll();
                    // vals.hasMoreElements(); logger.debug("\t" +
                    // vals.nextElement()))
                    // ;
                    NamingEnumeration<?> vals = att.getAll();
                    while (vals.hasMoreElements()) {
                        Object val = vals.nextElement();

                        // logger.debug("\t" + val);
                        value = (value.isEmpty()) ? value + val.toString() : value + ";" + val.toString();
                    }

                    if (att.getID().equalsIgnoreCase(FIELD_ACCOUNT_NAME)) {
                        // userInfo.setFIELD_ACCOUNT_NAME(value);
                        userInfo.setAccount(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_COGNOME)) {
                        // userInfo.setFIELD_COGNOME(value);
                        userInfo.setCognome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_EMAIL)) {
                        // userInfo.setFIELD_EMAIL(value);
                        userInfo.setEmail(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_GROUPS)) {
                        // userInfo.setFIELD_GROUPS(value);
                        userInfo.setGruppi(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME)) {
                        // userInfo.setFIELD_NOME(value);
                        userInfo.setNome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME_COMPLETO)) {
                        // userInfo.setFIELD_NOME_COMPLETO(value);
                        userInfo.setNomeCompleto(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME_VISUALIZZATO)) {
                        // userInfo.setFIELD_NOME_VISUALIZZATO(value);
                        // userInfo.setNome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_TEL)) {
                        // userInfo.setFIELD_TEL(value);
                        userInfo.setTel(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_UFFICIO)) {
                        // userInfo.setFIELD_UFFICIO(value);
                        userInfo.setUfficio(value);
                    }
                    // res.put(att.getID(), value);
                }

                // Attribute attr = result.get("cn");
                // if (attr != null) {
                // logger.debug("cn:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // attr = result.get("sn");
                // if (attr != null) {
                // logger.debug("sn:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // attr = result.get("mail");
                // if (attr != null) {
                // logger.debug("mail:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // // attr = result.get("uid");
                // // if (attr != null) {
                // // logger.debug("uid:");
                // // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // // }
                // //
                // // attr = result.get("userPassword");
                // // if (attr != null) {
                // // logger.debug("userPassword:");
                // // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // // }

                if (userInfo != null) {
                    res.add(userInfo);
                }
            }
        }
    } catch (NamingException ne) {
        // ne.printStackTrace();
        logger.error(ne);
        throw ne;
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (Exception e) {
        }
    }

    // Azzero l'hash map
    if (!trovatiRisultati) {
        res = null;
    }

    return res;
}