Monday, June 28, 2010

Working with Java LDAP API

import java.io.Serializable;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import org.apache.log4j.Logger;



/**
* @author Kiran
*
*/
public class LDAPInfo implements Serializable {

private static Logger log = Logger
.getLogger(LDAPInfo.class);
private final static String CLASS_NAME = "LDAPInfo";
private static final long serialVersionUID = 19931047L;

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String userName = null;
try {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://dsxstage.mycompany.com:389");
// env.put(Context.SECURITY_AUTHENTICATION,"OU=ccoentities,O=cco.mycompany.com");
env.put(Context.SECURITY_PRINCIPAL,"liferay_stage.gen"); // specify the username
env.put(Context.SECURITY_CREDENTIALS,"1!f3ray"); // specify the password
DirContext ctx = new InitialDirContext(env);
Attributes matchAttrs = new BasicAttributes(true);
log.info("The Connection Established to the LDAP Server Succeessfully");
log.info("Now trying to search the values in the LDAP Server");

userName = "kiran";
Attributes answer = ctx.getAttributes("uid="+userName+", OU=ccoentities,O=cco.mycompany.com");

for (NamingEnumeration ae = answer.getAll(); ae.hasMore();) {
Attribute attr = (Attribute)ae.next();
System.out.println("attribute: " + attr.getID());
/* Print each value */
for (NamingEnumeration e = attr.getAll(); e.hasMore();
System.out.println("value: " + e.next()))
;
}


Attribute at = null;
// at.
// matchAttrs.put(attr);

//NamingEnumeration answer = ctx.search("Country",matchAttrs);


//ctx.getSchema("")
// ctx.bind(name, obj)
//ctx.search(name, matchingAttributes);


} catch(NamingException ex) {

log.error("The Exception while connecting to the LDAP Server is:"+ ex.getMessage());
ex.printStackTrace();


} catch(Exception ex) {
log.error("The Exception while retrieving the attribute values from the LDAP Server is:"+ ex.getMessage());
ex.printStackTrace();


}
}

}

No comments: