April 26, 2010

Groovy+LDAP: How Easy Can It Get?

Rationale
I was trying to simulate a particular client application this week end and I decided to go with a quick Groovy script. I decided to share here how easy it was to interact with server here.

The Meat
First things first, you should know to read the getting started guide, it makes it nice and easy for you to store your data in any LDAP server. I will break down here what needs to happen for you to do a search:
  1. get a connection
  2. issue the search
  3. get the results
And here is how it is done step by step:
  1. cx = new LDAPConnection("localhost", 1389, "cn=Directory manager", "password")
  2. result = cx.search("",SearchScope.ONE,"(objectclass=*)",null)
  3. result.getSearchEntries()
And now the complete groovy script that connects to your server and prints the results:
new LDAPConnection("localhost", 1389, "cn=Directory Manager", "password")?.search("o=company",SearchScope.ONE,"(objectclass=*)",null)?.getSearchEntries()?.each({println it.getDN()})

That's right!
One line is all you need to connect, search and print all entries DNs below the base which here is o=company.

Now that's easy!