Java Reference
In-Depth Information
database table, but is unique through the entire directory, not just in a single seg-
ment of it like the primary key for a row in a table. The following method in the
DAO
implementation creates a unique
DN
for our contact bean:
private String getDn(String userId){
return MessageFormat.format(this.dnTemplate, userId);
}
The second setting we need is for getting the initial directory context. The default
constructor for our
DAO
will use the hardcoded properties to connect to our
LDAP
directory, but again, the second constructor will allow us to inject custom
properties if needed for other purposes. Those properties are used to get the ini-
tial directory context:
private DirContext getInitialContext() {
DirContext ctx = null;
try {
ctx = new InitialDirContext(env);
} catch (NamingException e) {
log.error("Exception getting initial context", e);
throw new DaoException(e);
}
return ctx;
}
Now that we have all of the required infrastructure code in place to deal with
mapping our bean and connecting to our
LDAP
directory, we can start to build
our
DAO
implementation.
The first method we will look at is the simplest—we will look up a contact by
userId
. Here is the code to implement that method:
public Contact getById(String id) {
DirContext ctx = getInitialContext();
Attributes attributes;
try {
attributes = ctx.getAttributes(getDn(id));
} catch (NamingException e) {
throw new DaoException(e);
}
return getContact(attributes);
}
Here, we take the directory context, and use it to get the attributes of our contact,
based on the DN of the passed-in user's
id
value. Once we have the attributes, we
convert them into a contact bean and return it. If an
LDAP
-specific
NamingExcep-
tion
is thrown, it is re-thrown as
DaoException
instead to make sure that the
method signature does not indicate the data source.
