December 15, 2010

Easily Persist Java To Any Directory Server

Simply providing a trivial example to get you started.

The Meat
To make it really trivial, I will use a very simple object that already exists in the default schema, the person object class. This class only requires the person to have a first and last name, respectively stored in the cn (or commonName) and sn (or surname) attributes. To spice it up a bit and make it remotely useful, let's say we also expect a person to have a password so we can authenticate them later. The default schema allows us to do so in the userPassword attribute.

The whole idea of persistence is that you don't have to worry at all about the LDAP. All you need to do is 

>generate-source-from-schema -h localhost -p 389 -D "cn=directory manager" -w password --outputDirectory src/com/example --structuralClass person --rdnAttribute cn --defaultParentDN dc=example,dc=com --packageName com.example --className Person --terse

When you have done this, you have a in src/com/example created for you.
We'll go ahead and create a groovy script file in src/com/example to add a new guy in our directory server:

package com.example
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.persist.LDAPPersister;
def cx = new LDAPConnection("localhost",389,"cn=directory manager","password")
def persister = LDAPPersister.getInstance(Person.class)
def newGuy = new Person()
persister.add(newGuy, cx, null)

That's it!
Yes, that really is it. Unbelievable? Try for yourself.


  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training India . Nowadays Java has tons of job opportunities on various vertical industry.

  2. Pretty blog, so many ideas in a single site, thanks for the informative article, keep updating more article.
    appvn app