Pages

Ads 468x60px

Wednesday, July 25, 2012

Java: Search User in IBM Tivoli Directory Server (TDS) LDAP using JNDI

It will help you to search user and other entries in IBM Tivoli Directory Server (TDS) using JNDI. I used default values, so you have to change it according your requirements. Also the user attributes will depend upon your directory server schema. For connection with IBM Tivoli Directory Server (TDS)/ LDAP visit: http://usmanali112.blogspot.com/2012/07/java-authentication-and-connection-with.html


import javax.naming.NamingEnumeration;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.directory.*;

//this class perform all LDAP actions for the user
public class LDAPService {

private String base = "c=us"; // base for LDAP
private String realm = "cn=realm1"; // LDAP realm for user
   
         public void getUserInfo(String name) {
String dn = "sn=" + name + "," + realm + "," + base;

try {
// Initialize LDAP Context
InitialLdapContext context = LDAPConnection.InitializeContext();
String[] att = { "givenName", "mail" };

// Set up Search Controls
SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
sc.setReturningAttributes(att);

// perform search on directory
NamingEnumeration results = context.search(base,
"(objectclass=inetorgperson)", sc);

while (results.hasMore()) {
SearchResult sr = (SearchResult) results.next();

// get the attributes and attribute list
Attributes atts = sr.getAttributes();
NamingEnumeration attrList = atts.getAll();
if (dn.equals(sr.getName() + "," + base)) {
// while we have attributes
while (attrList.hasMore()) {
Attribute attr = (Attribute) attrList.next();
NamingEnumeration values = attr.getAll();
String id, value = "";
while (values.hasMore()) {
id = attr.getID();
value = values.next().toString();
System.out.println(id + " " + value);
}
}
}
}

// Close LDAP Context
LDAPConnection.CloseContext();

} catch (Exception ex) {
ex.getMessage();
}
}
}

No comments:

Post a Comment