Question

Using LdapTemplate in Spring LDAP, I have this code:

Object object=null;
try{
    String dn = "cn=readers,ou=groups,dc=mycompany, dc=com";
    object = this.ldapTemplate.lookup(dn);
} catch(final NameNotFoundException e){
    // create Object
}

But since I've read my Joshua Bloch I know that exceptions should not be used for control flow. Is there a way to look up a dn to see if it exists without throwing an exception if it doesn't? There must be, but I can't find it. I'm looking for code that works like this (or similar):

String dn = "cn=readers,ou=groups,dc=mycompany, dc=com";
Object object=this.ldapTemplate.someMethod(dn);
if(object==null){
    // create Object
}

Can anybody help?

BTW: just looking at the JavaDoc won't help. None of the methods that throw NameNotFoundException say so in the JavaDocs.

Was it helpful?

Solution

The lookup() method is only supposed to be used when you know for certain that the DN exists. This is normally because you've searched for and found a user or group previously, and cached the DN returned from the server.

If you're looking for something that might or might not be there, the right API to use is ldapTemplate.search(), with an appropriate filter. This returns a list of results, and in the case where no results are found it returns an empty list rather than throwing an exception.

OTHER TIPS

Actually, Spring force you here to use exceptions for flow control (i.e. it's not your fault, it's their decision).

I worked with LdapTemplate few months ago and I couldn't find anything better then catch that exception and evaluate that situation as "User not found".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top