Tuesday, May 10, 2011

LDAP Acess by Java

public static void setLdapAttribute(String username,String password,MessageHeaderVO messageHeaderVO){

String attributeName[] ={"extensionattribute1","extensionattribute2","extensionattribute3"};
DirContext ctx=null;
try{

Hashtable env = new Hashtable();
//String password ="password";
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
String providerurl =CommonUtil.getResourceBundleMsg("ads_service_url", "com.ibm.ahb.idt.nl.AlHilalPortalPortletResourceMessages");
env.put(Context.PROVIDER_URL,providerurl);
//env.put(Context.PROVIDER_URL,PortletConstant.LDAP_PROVIDER_URL);
env.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.SECURITY_PRINCIPAL,"CN="+username+",CN=Users,DC=testbank,DC=ae");
env.put(Context.SECURITY_CREDENTIALS,password);
ctx=new InitialDirContext(env);

Attributes attrs = ctx.getAttributes("CN="+username+",CN=Users,DC=testbank,DC=ae",attributeName);
NamingEnumeration answer = attrs.getAll();
while (answer.hasMoreElements()) {
Attribute attr = (Attribute) answer.nextElement();
NamingEnumeration attributevalues= attr.getAll();
while(attributevalues.hasMoreElements())
{
if(attr.getID().equalsIgnoreCase(attributeName[0])){
messageHeaderVO.setRequestorRole((String)attributevalues.nextElement());
}
if(attr.getID().equalsIgnoreCase(attributeName[1])){
messageHeaderVO.setIsManagerFlag((String)attributevalues.nextElement());
}
if(attr.getID().equalsIgnoreCase(attributeName[2])){
messageHeaderVO.setBranchCode((String)attributevalues.nextElement());
}
}

}

}catch (AuthenticationException authe) {
logger.error("Error while creating Ldapcontext " + authe.getMessage());
}catch (Exception e) {
logger.error("Error while creating Ldapcontext" + e.getMessage());
}finally{
try{
ctx.close();
}catch(Exception Ignore)
{
}
}
}

No comments:

Post a Comment

Followers