In a previous post I’ve described an initial implementation of OpenDS as a naming and directory service, including extending the directory schema and reading and writing directory objects with JNDI. As actual (read: competent) Java developers took over my prototype, they switched from JNDI to spring-ldap. The resulting code is much more pleasant, and I got to learn a bit more about Spring.
Service Object
Let’s get something useful in and out of the directory: a Service object. Naturally it doesn’t matter where it came from, so the Service class is a simple container.
You’ll immediately notice that in contrast with the previous implementation, this object knows nothing about being stored in a directory. I was lazy then, but this time Spring helps (forces) me to write better code.
Service DAO
At the core of spring-ldap lies LdapTemplate that executes core LDAP functionality and encapsulates all the plumbing. We’re going to implement a simple DAO for our Service objects that can, for example, retrieve all services.
Notice a few important things here. First, we have not specified how to connect to the LDAP server - that will appear in the runtime configuration. Secondly, we use ServiceAttributesMapper, a class that knows how to map LDAP attributes into a Service object, achieving a very nice separation of concerns.
Spring Configuration
To make it all work we need some configuration. We can define a springldap.xml configuration file for our tests, another one for production, etc.
What does this do?
Defines the values for the LdapContextSource. In our case, a url to our OpenDS installation, a base path to the objects, a user and password to access the directory.
Defines how to construct an LdapTemplate that encapsulates LDAP core functionality. It takes the context source defined above.
Tells Spring to set the LdapTemplate property of the ServiceDAO with the value above.
We could have done this all in code, but Spring helps us create another level of abstraction and enables a complete configuration-based runtime experience.
Getting Services
We still need to tell Spring to use this configuration at runtime before we can call DAO methods such as getAllServices.
This is nice! With Spring, we have achieved complete separation of responsibilities and pluggable configuration and, all things considered, wrote a lot less code.
More DAO
Create or Update a Service
Delete a Service
Get a Service by Name
Running the Code
You can run the source code from this article with OpenDS and Eclipse.