JNDI overview, Part 3: Advanced JNDI

Use JNDI to store your distributed applications' objects

I need to cover a lot of ground this month, so I'll leave out the fluff and cut right to the bullet points. First, the Java Naming and Directory Interface plays an important role in several Java technologies. We're going to take a look at this role to better understand JNDI's strategic position in the overall Java picture. Next, in recognition of your need for a working JNDI service to play with, I'll introduce you to a freely available, portable LDAP implementation, and I'll teach you how to connect to and use a JNDI service provider. Finally, I'll take you in for a close look at binding objects to entries in JNDI.

TEXTBOX:

TEXTBOX_HEAD: JNDI overview: Read the whole series!

:END_TEXTBOX

Before I begin, a little doublethink is in order. Over the last two months, I've tried to convince you that naming and directory services are roughly the electronic equivalent of the card catalogs found in libraries. Now as we begin our tour of the advanced features of JNDI, I want you to forget this analogy completely -- it grossly underillustrates the power of JNDI.

Let's begin with a look at how JNDI appears in other Java technologies.

JNDI everywhere

JNDI plays a role in a number of Java technologies. Let's consider three of them: JDBC (the Java Database Connectivity package), JMS (the Java Messaging Service), and EJB (Enterprise JavaBeans).

JDBC is the Java technology for relational databases. JNDI first appeared in the JDBC 2.0 Optional Package (see Resources) in conjunction with the DataSource interface. A DataSource instance, as its name implies, represents a source of data -- often from a database but not always. A DataSource instance stores information about a data source -- such as its name, the driver to load and use, and its location -- and allows an application to obtain a connection to the data source without regard to the underlying details. The JDBC specification recommends using JNDI to store DataSource objects.

JMS is the Java technology for messaging. The JMS specification describes administered objects -- objects that contain JMS configuration information and are used by JMS clients to locate specific message queues and topics. As is the case with JDBC, the specification recommends locating JMS administered objects via JNDI.

Finally, consider Enterprise JavaBeans. All enterprise beans publish a home interface -- the single location through which clients locate a specific enterprise bean -- via JNDI.

What does JNDI bring to the table that causes it to be so highly regarded?

First, JNDI promotes the notion of a centrally managed information source -- a key requirement for enterprise applications. A centrally managed information source is easier to administer than a distributed collection of information sources. It's also simpler for clients to locate needed information if they only have to look in one place.

Second, as you shall see, JNDI's ability to directly store Java objects allows it to integrate almost transparently into Java applications.

The point of the provider

To use JNDI, you need a naming and directory service and a JNDI service provider. Sun supplies several providers of common naming and directory services (COS naming, NIS, the RMI registry, LDAP, and more). I've settled on LDAP.

LDAP (Lightweight Directory Access Protocol) has the dual advantages of being widely implemented (both in commercial and free forms) and being reasonably easy to use. Its features are also well supported by Sun's LDAP service provider and JNDI.

Since obtaining and configuring an LDAP server isn't really a Java subject matter, I'll only get you headed in the right direction and supply you with references to Internet resources.

Numerous LDAP implementations are available. Many are commercial products such as the Netscape Directory Server and IBM's Secure Way Directory. Some are packaged as part of larger offerings (Microsoft's Active Directory is part of Windows 2000). If you have access to such an implementation, you can skip most of this section. Otherwise, I'm going to describe OpenLDAP -- a freely available implementation of LDAP based on the University of Michigan's reference implementation -- as well as its installation and configuration.

OpenLDAP is available from the OpenLDAP Foundation (see Resources). Its license is based on Perl's "artistic license," which means that OpenLDAP is free (or open source) software. Prepackaged binaries are available for various flavors of Linux (Debian, Red Hat) as well as BSD Unix. Work is under way on a port to Windows NT.

If you plan to install OpenLDAP, you should read the SLAPD and SLURPD Administrator's Guide (slapd is the name of the LDAP server executable and slurpd is the name of the LDAP replication server; see Resources for the location).

I have one final suggestion to make your entire experience more pleasing: no matter which LDAP implementation you use, turn schema checking off. An LDAP schema, like a database schema, defines constraints on the stored information. In normal use, schema checking helps ensure that entries (think of address book entries) conform to the correct format. However, since you'll probably be playing rather than building something of lasting significance, schema checking will just get in the way. Take my word for it.

Connecting to a JNDI context

In previous articles, I tried to avoid explaining in detail how to interact with a JNDI service provider such as the LDAP service provider. I mentioned that you need an initial context to do JNDI operations, but I didn't spend much time telling you how to get one. Let me fill in the gaps. (For more on initial contexts, see the first two articles in this series.)

Before you can do anything with JNDI, you need an initial context. All operations are performed relative to the context or one of its subcontexts.

Obtaining an initial context requires three steps:

  1. First, select a service provider. If you're going to use OpenLDAP or some other LDAP implementation, Sun supplies a reference LDAP service provider (see Resources). Add the name of the service provider to the set of environment properties (stored in a Hashtable instance):

      Hashtable hashtableEnvironment = new Hashtable();
      hashtableEnvironment.put(
        Context.INITIAL_CONTEXT_FACTORY,
        "com.sun.jndi.ldap.LdapCtxFactory"
      );
    
  2. Add any extra information the service provider requires. For LDAP, that includes the URL that identifies the service, the root context, and the name and password to connect with:

      // the service: ldap://localhost:389/
      // the root context: dc=etcee,dc=com
      hashtableEnvironment.put(
        Context.PROVIDER_URL,
        "ldap://localhost:389/dc=etcee,dc=com"
      );
      hashtableEnvironment.put(
        Context.SECURITY_PRINCIPAL,
        "name"
      );
      hashtableEnvironment.put(
        Context.SECURITY_CREDENTIALS,
        "password"
      );
    
  3. Finally, get the initial context. If you just intend to perform naming operations, you'll only need a Context instance. If you intend to perform a directory operation as well, you'll need a DirContext instance instead. Not all providers supply both:

      Context context = new InitialContext(hashtableEnvironment);
    

    Or:

      DirContext dircontext = new InitialDirContext(hashtableEnvironment);
    

That's all there is to it. Now let's look at how applications store objects to and retrieve objects from JNDI.

Work with objects

The ability to store Java objects is useful: object storage provides persistence and allows objects to be shared between applications or between different executions of the same application.

From the standpoint of the code involved, object storage is surprisingly easy:

  context.bind("name", object)

The bind() operation binds a name to a Java object. The syntax of the command is reminiscent of RMI, but the semantics are not as clearly defined. It's permissible for the bind() operation to store either a snapshot of the object or a reference to a "live" object, for example.

Be aware that the bind() operation throws a NamingException if an exception occurs during the execution of the operation.

Now let's take a look at the bind() operation's complement -- lookup():

  Object object = context.lookup("name")

The lookup() operation retrieves the object bound to the specified name. Once again, the syntax is reminiscent of RMI, but the method's semantics are not as clearly defined.

Just as with bind(), the lookup() operation throws a NamingException if an exception occurs during the execution of the operation.

Object storage

What does it mean to store an object in a JNDI naming and directory service? We've already mentioned that the exact semantics of the bind() and lookup() operations aren't tightly defined; it's up to the JNDI service provider to define their semantics.

According to the JNDI specification, service providers are encouraged (but not required) to support object storage in one of the following formats:

  • Serialized data
  • Reference
  • Attributes in a directory context

If all JNDI service providers support these standard mechanisms, Java programmers are free to develop generic solutions that work even when the underlying service provider layer changes.

Each of the methods above has advantages and disadvantages. The best method will depend on the requirements of the application under development.

Let's consider each in turn.

As serialized data

The most obvious approach to storing an object in a directory is to store the serialized representation of an object. The only requirement is that the object's class implement the Serializable interface.

When an object is serialized, its state becomes transformed into a stream of bytes. The service provider takes the stream of bytes and stores it in the directory. When a client looks up the object, the service provider reconstructs it from the stored data.

The following code demonstrates how to bind a LinkedList to an entry in an JNDI service:

  // create linked list
  LinkedList linkedlist = new LinkedList();
    .
    .
    .
  // bind
  context.bind("cn=foo", linkedlist);
    .
    .
    .
  // lookup
  linkedlist = (LinkedList)context.lookup("cn=foo");

It's that easy!

Unfortunately, the other two methods are more complicated. I will describe them briefly but reserve a detailed discussion for a later date.

As a reference

Sometimes it's not appropriate (or possible) to serialize an object. If the object provides a service on a network, for example, it doesn't make sense to store the state of the object itself. We're interested in the information necessary to find and communicate with the object.

An example is a connection to an external resource (one outside the scope of the Java Virtual Machine) such as a database or file. It clearly doesn't make sense to try to store the database or the file itself in the JNDI service. Instead, we want to store the information necessary to reconstruct the connection.

In this case the programmer should either bind a Reference instance that corresponds to the object or have the object's class implement the Referenceable interface (in which the object generates and provides a Reference instance when requested by the service provider).

The Reference instance contains enough information to recreate the reference. If a reference to a file was stored, the reference contains enough information to create a File object that points to the correct file.

As attributes

If you're using a service provider that provides directory functionality instead of only naming functionality, you can also store an object as a collection of attributes on a DirContext object (a DirContext instance differs from a Context instance in that it may have attributes).

To use this method, you must create objects that implement the DirContext interface and contain the code necessary to write their internal state as an Attributes object. You must also create an object factory to reconstitute the object.

This approach is useful when the object must be accessible by non-Java applications.

Conclusion

If you've read the series, you should understand and appreciate the power and importance of JNDI -- you don't hear much about it, but it's there under the covers.

Next month we'll take a look at a JNDI-based application. In the meantime, you should try to get JNDI up and running on an LDAP server.

Learn more about this topic

Join the discussion
Be the first to comment on this article. Our Commenting Policies