Java Reference
In-Depth Information
So what is going on here? This constructor is a bit unusual, isn't it? The
InitialDirContext
is a “context factory.” It takes an “environment,” which
is a
Hashtable
, that provides the information needed to make the context.
And what is that information? At a minimum, the constant value associated
with
Context.INITIAL_CONTEXT_FACTORY
must be associated with the class
name of the real context factory for the directory system—in this case,
com.sun.jndi.dns.DnsContextFactory
. If you are from a C/C++
background, think of this as a function pointer.
8
We now have an initial directory context, which we can use to search.
Going from the initial context to a DNS entry.
Let's now consider a use
case for this little program. The program begins at
main()
, line 21. We create
an instance of our class and an instance of
NamingEnumeration
(which we
will discuss in a moment). We do some very lazy error handling by enclosing
the entire process in a simple
try
/
catch
block
9
and treating all exceptions the
same. The first thing we do is construct an instance of our class, passing in the
first command-line argument
10
as the domain name to use for setting the initial
context.
Next, we get an enumeration of all the names in that context. This is done
through a method in our class that simply wraps the actual JNDI call that ob-
tains this enumeration. The real event is on line 18. The
list()
method of
the directory context returns a
NamingEnumeration
, which is an extension of
the classic
Enumeration
Java class. With it, you can iterate over the contents
of the context—which we do in lines 29-33. We rely on our old
Object
method,
toString()
, to make these names readable for us. Of course, each
8. Of course, it is not. What really happens here is that the code in
InitialDirContext
uses the
Class
class to load the specified class by name. All JNDI context factory classes imple-
ment the
Context
interface, so
InitialDirContext
uses the ability of
Class
to load the
class by its name as an instance of
Context
.
9. JNDI has a particularly rich collection of exceptions. When a naming or directory operation
fails, it is usually possible to determine exactly how and why it failed from the type of
Exception
thrown. All JNDI
Exception
s extend
NamingException
, so they also make it
quite easy to handle them in a lazy manner. In a real production application, you should at
least make some effort to differentiate between failures where the network is not working and
failures where the network is working fine, but the named resource does not exist. Believe us,
if you have to support your application in production you will care about the difference.
10. Again, very bad production coding. Note that no attempt is made to check the number of
arguments passed or their contents.