views:

26

answers:

1

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.

+2  A: 

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".

Roman
Yup, that's what I am currently doing, but due to Spring Exception translation, I get lots of stack traces in the log file and it's really ugly.
seanizer
@seanizer: I don't know why spring designers desided to use exceptions so hardly, but if you'll look at Spring Security, you'll see that throwing AuthenticationException is a pretty valid solution when you want to swith to another AuthenticationProvider (from LDAP to LocalDB for example). And if you don't enjoy manipulations with exceptions, then don't even look at Spring WebFlow - there you can find over 9k exceptions thrown during one usual request-response cycle.
Roman