import javax.naming.*;
import javax.naming.ldap.*;
import javax.naming.directory.*;
import java.util.Hashtable;
/**
* Backslash.java
*
* -- A sample code to demonstrate JNDI backslash (\) problem.
*
* In LDAP DIT there is an entry with the common name (cn) as part of dn and
* cn has a single backslash character inside. The ldif looks as follows:
*
* dn: cn=temp\\tester,cn=users,dc=mydomain,dc=com
* objectclass: top
* objectclass: person
* objectclass: organizationalPerson
* objectclass: inetOrgPerson
* cn: cn=temp\tester
* sn: tester
* givenName: temp
* telephoneNumber: (555)-1234
*
*/
public class Backslash
{
public static void main(String args[])
{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://myServer:389/");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=admin" );
env.put(Context.SECURITY_CREDENTIALS, "password" );
DirContext ctx = null;
try{
/* Open an LDAP connection for the provided principal and credentials */
ctx = new InitialLdapContext(env, null);
/* search constraints */
SearchControls ctls = new SearchControls();
ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
/* search */
String base_dn = "cn=users,dc=mydomain,dc=com";
NamingEnumeration enu = ctx.search(base_dn, "sn=test*", ctls);
/* process results */
while(enu.hasMore()){
SearchResult sr = (SearchResult)enu.next();
String dn = sr.getName(); // should return 'cn=temp\\tester'
if(sr.isRelative()){
dn += "," + base_dn;
}
System.out.println("dn: " + dn);
NamingEnumeration attrs = sr.getAttributes().getAll();
while(attrs.hasMoreElements()){
BasicAttribute attr = (BasicAttribute)attrs.nextElement();
String attrType = attr.getID();
NamingEnumeration vals = attr.getAll();
while(vals.hasMoreElements()){
String attrValue = vals.nextElement().toString();
System.out.println(attrType + ": " + attrValue);
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}