Monday, October 6, 2014

Sample JNDI code to connect and get Active Directory Group properties

import java.util.Hashtable;
import java.util.Date;

import javax.naming.*;
import javax.naming.directory.*;

class GetGroupProps
{
public static void main(String[] args)
{
int totalResults = 0;
Hashtable env = new Hashtable(5, 0.75f);
final String ldapSearchBase = "dc=addemo,dc=com";
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://spsolutions.addemo.com:389");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=Administrator,cn=users,dc=addemo,dc=com");
env.put(Context.SECURITY_CREDENTIALS, "Oracle@1234");
try
{
        DirContext ctx = new InitialDirContext(env);
        System.out.println("Login Successful");
        String searchFilter = "(&(objectClass=group)(CN=Administrators))";
        SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls);
while (results.hasMoreElements())
{
SearchResult sr = (SearchResult)results.next();
System.out.println(">>>" + sr.getName());
Attributes attrs = sr.getAttributes();
if (attrs != null
{
try 
{
for (NamingEnumeration ae = attrs.getAll();ae.hasMore();) 
{
Attribute attr = (Attribute)ae.next();
System.out.println("Attribute: " + attr.getID());
for (NamingEnumeration e = attr.getAll();e.hasMore();totalResults++) 
{
System.out.println(" " +  totalResults + ". " +  e.next());
}
}
}
catch (NamingException e)    
{
System.err.println("Problem listing membership: " + e);
}
}
}
}
catch(Exception e)
        {
System.out.println("Exception "+ e);
        }
}
}


No comments:

Post a Comment