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.

No comments:

Post a Comment