Example usage for javax.naming.directory Attributes getAll

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

Introduction

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

Prototype

NamingEnumeration<? extends Attribute> getAll();

Source Link

Document

Retrieves an enumeration of the attributes in the attribute set.

Usage

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

public static Map<String, String> parseAsMap(NamingEnumeration searchResults, String keyAttribute,
        String valueAttribute) {/*www . j  ava  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:org.apache.cxf.sts.ldap.LDAPClaimsTest.java

@org.junit.Test
@org.junit.Ignore/*from w  w  w.  ja v  a  2 s  . co m*/
public void testLdapTemplate() throws Exception {

    try {
        LdapTemplate ldap = (LdapTemplate) appContext.getBean("ldapTemplate");

        String user = props.getProperty("claimUser");
        Assert.notNull(user, "Property 'claimUser' not configured");

        String dn = null;

        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("cn", user));

        //find DN of user
        AttributesMapper mapper = new AttributesMapper() {
            public Object mapFromAttributes(Attributes attrs) throws NamingException {
                return attrs.get("distinguishedName").get();
            }
        };
        @SuppressWarnings("rawtypes")
        List users = ldap.search("OU=users,DC=emea,DC=mycompany,DC=com", filter.toString(),
                SearchControls.SUBTREE_SCOPE, mapper);

        Assert.isTrue(users.size() == 1, "Only one user expected");
        dn = (String) users.get(0);

        // get attributes
        AttributesMapper mapper2 = new AttributesMapper() {
            public Object mapFromAttributes(Attributes attrs) throws NamingException {
                Map<String, String> map = new HashMap<String, String>();
                NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
                while (attrEnum.hasMore()) {
                    Attribute att = attrEnum.next();
                    System.out.println(att.toString());
                }

                map.put("cn", (String) attrs.get("cn").get());
                map.put("mail", (String) attrs.get("mail").get());
                map.put("sn", (String) attrs.get("sn").get());
                map.put("givenName", (String) attrs.get("givenName").get());
                return map;
            }
        };
        ldap.lookup(dn, new String[] { "cn", "mail", "sn", "givenName", "c" }, mapper2);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

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

@SuppressWarnings("unchecked")
public static List parseDataAsList(NamingEnumeration searchResults) {
    //Logger.info("Formatting the data as List", LDAPUtils.class   );
    List<String> resultAttr = null;
    int totalResultLogger = 0;
    if (searchResults == null) {
        return null;
    }/*from ww w. j  a  va2  s  .  c o 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 (resultAttr == null) {
                resultAttr = new ArrayList();
            }
            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();

                        resultAttr.add(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 resultAttr;
}

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 www  .  ja  v  a 2  s  .c om
 * 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:com.wfp.utils.LDAPUtils.java

@SuppressWarnings("unchecked")
public static Map<String, String> parseDataAsMap(NamingEnumeration searchResults) {
    Map<String, String> resultAttrMap = null;
    int totalResultLogger = 0;
    if (searchResults == null) {
        return null;
    }//from ww  w . j  ava2s.  c  o  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 (resultAttrMap == null) {
                resultAttrMap = new HashMap<String, String>();
            }
            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();

                        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: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 www.j  a v a  2s.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.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;
        }// w w  w .j a  v  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.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;
    }//w ww.j a  v  a 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:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

/**
 * Gets the values of a repeating attribute that may have range restriction options. If an attribute is range
 * restricted, it will appear in the attribute set with a ";range=i-j" option, where i and j indicate the start and
 * end index, and j is '*' if it is at the end.
 *
 * @param attributes//from w ww  .j av a 2  s  .c  o m
 *            the attributes
 * @param attributeName
 *            the attribute name
 * @return the range restricted attribute
 * @throws NamingException
 *             the naming exception
 */
protected Attribute getRangeRestrictedAttribute(final Attributes attributes, final String attributeName)
        throws NamingException {
    final Attribute unrestricted = attributes.get(attributeName);
    if (unrestricted != null) {
        return unrestricted;
    }
    final NamingEnumeration<? extends Attribute> i = attributes.getAll();
    final String searchString = attributeName.toLowerCase(Locale.ENGLISH) + ';';
    while (i.hasMore()) {
        final Attribute attribute = i.next();
        if (attribute.getID().toLowerCase(Locale.ENGLISH).startsWith(searchString)) {
            return attribute;
        }
    }
    return null;
}

From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java

/**
 * Gets the values of a repeating attribute that may have range restriction options. If an attribute is range
 * restricted, it will appear in the attribute set with a ";range=i-j" option, where i and j indicate the start and
 * end index, and j is '*' if it is at the end.
 *
 * @param attributes//from   w w  w. j a va 2  s .com
 *            the attributes
 * @param attributeName
 *            the attribute name
 * @return the range restricted attribute
 * @throws javax.naming.NamingException
 *             the naming exception
 */
private Attribute getRangeRestrictedAttribute(Attributes attributes, String attributeName)
        throws NamingException {
    Attribute unrestricted = attributes.get(attributeName);
    if (unrestricted != null) {
        return unrestricted;
    }
    NamingEnumeration<? extends Attribute> i = attributes.getAll();
    String searchString = attributeName.toLowerCase() + ';';
    while (i.hasMore()) {
        Attribute attribute = i.next();
        if (attribute.getID().toLowerCase().startsWith(searchString)) {
            return attribute;
        }
    }
    return null;
}