[problem]
You want to talk to LDAP from Java.
[/problem]
[solution]
Java as well as Perl, PHP and plain old Shell have APIs to be able to talk to LDAP.
The Java API is probably most complex one to use – I have provided some demos on how to use the others on this site.
More will be added in time.
[/solution]
[example]
Here is a full example of using Java’s JNDI to talk to LDAP, performing a search and supplying results:
import java.util.*;
import java.io.*;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.*;
public class getLdapDetails {
public static void main(String argv[]) {
String url="ldap://127.0.0.1:389";
Hashtable env=new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL,url);
env.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.SECURITY_PRINCIPAL,
"cn=Manager,dc=demo,dc=net");
env.put(Context.SECURITY_CREDENTIALS,"secret");
try {
DirContext ctx=new InitialDirContext(env);
String[] attrIDs = { "givenname","sn","mail" } ;
Attributes matchAttrs = new BasicAttributes(true); //ignore case
matchAttrs.put(new BasicAttribute("sn",argv[0]));
NamingEnumeration myenum =
ctx.search("dc=demo,dc=net",matchAttrs, attrIDs);
while( myenum.hasMore()) {
String PersonRecord="";
SearchResult result = (SearchResult)myenum.next();
Attributes attributes = result.getAttributes();
Attribute attr = attributes.get( "givenname" );
NamingEnumeration values = attr.getAll();
while( values.hasMore()) {
PersonRecord += values.next().toString();
PersonRecord += ", ";
}
attr = attributes.get( "sn" );
values = attr.getAll();
while( values.hasMore()) {
PersonRecord += values.next().toString();
PersonRecord += " - ";
}
attr = attributes.get( "mail" );
values = attr.getAll();
while( values.hasMore()) {
PersonRecord += values.next().toString();
}
System.out.println(PersonRecord);
}
ctx.close();
} catch(NamingException ne) { System.err.println(ne.toString()); }
}
}
Then a run through:
$ java getLdapDetails Doe
John, Doe - [email protected]
[/example]
[reference]
[tags]Java JNDI to LDAP, JNDI LDAP, LDAP Training School[/tags]
[/reference]