Tuesday, May 10, 2011

Access LDAP from Java Code

<%@page session="false" contentType="text/html" pageEncoding="ISO-8859-1" import="java.util.*,javax.portlet.*,com.ibm.jsr168.* ,com.ibm.portal.um.*,com.ibm.portal.um.PumaHome,javax.naming.*,javax.naming.directory.*"%>
<%@ taglib uri="http://java.sun.com/portlet" prefix="portlet"%>
<%@taglib uri="http://www.ibm.com/xmlns/prod/websphere/portal/v6.1/portlet-client-model" prefix="portlet-client-model" %>






<%

DirContext ctx=null;
Hashtable env = null;

String password ="123";

env=new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL,"Ldap://127.0.0.1:389");
env.put(Context.SECURITY_AUTHENTICATION,"simple");
// env.put(Context.SECURITY_PROTOCOL, "ssl");
/*
         * sample website: company.com.tw
         *
         * DN: DC=company,DC=com,DC=tw
         */
env.put(Context.SECURITY_PRINCIPAL,"cn="+acct+",cn=users,DC=COMPANY DOMAIN");//,DC=com,DC=tw");


env.put(Context.SECURITY_CREDENTIALS,password);
try{
System.out.println("connecting...");
ctx=new InitialDirContext(env);

// Ask for all attributes of the object
Attributes attrs = ctx.getAttributes("CN="+user+",CN=Users,DC=ldapname,DC=ae");


NamingEnumeration answer = attrs.getAll();
while (answer.hasMoreElements()) {
//System.out.println("Inside while1....");
Attribute attr = (Attribute) answer.nextElement();
System.out.println(attr.getID() + "=");
NamingEnumeration answer1 = attr.getAll();
while(answer1.hasMoreElements())
{ System.out.println(attr.getID() + ":Value =" + (String)answer1.nextElement());

}


}
Attribute attr1 = attrs.get("departmentNumber");
Attribute attr2 =attrs.get("localityName");
Attribute attr3 =attrs.get("description");
if(attr1 != null)
{System.out.println("departmentNumber" + attr1.toString());
}
else
{System.out.println("departmentNumber is null");
}
if(attr2 != null)
{System.out.println("localityName" + attr2.toString());
}
else
{System.out.println("localityName is null");
}
if(attr3 != null)
{System.out.println("description" + attr3.toString());
}
else
{System.out.println("description is null");
}



System.out.println("success");
}catch(AuthenticationException authe){
System.out.println("fail");
authe.printStackTrace();
}catch(Exception e){
System.out.println(e);
e.printStackTrace();
}finally{
try{
ctx.close();
}catch(Exception Ignore)
{
}
}

%>

No comments:

Post a Comment

Followers