Sun Java Solaris Communities My SDN Account Join SDN
 
Code sample

JNDI Examples

 

Following are some examples to illustrate the capabilities enabled by JNDI. You can get additional examples from the following sources.

  • You can also download the source of a JNDI demo program for browsing and editing namespaces and directories. This program uses the JNDI API and can be used to browse any naming and directory service for which you have a service provider.
  • The JNDI Tutorial contains over 200 working examples of basic to advanced uses of JNDI.

Accessing the Directory

A directory is typically used to associate attributes with objects. A person object, for example, can have a number of attributes, such as the person's surname, telephone numbers, electronic mail address, postal address, computer account, and authentication information such as his password or X.509 certificate. Using JNDI, to retrieve the email address of a person object, the code looks as follows.

	Attribute attr =
	    directory.getAttributes(personName).get("email");
	String email = (String)attr.get();

Searching the Directory

An application can also use JNDI to search the directory for objects by specifying some attributes. For example, to search for people whose surname is "Fox" in the Wiz organization, the code looks as follows.

	foxes = directory.search("o=Wiz,c=US", "sn=Fox", controls);

Looking up Objects

An intuitive model for the Java programmer is to be able to lookup objects like printers and databases from the naming/directory service. Using JNDI, to lookup a printer object, the code looks as follows.

	Printer printer = (Printer)namespace.lookup(printerName);
	printer.print(document);

Browsing the Namespace

When using almost any kind of interactive application that prompts the user for input names, the user's job is simplified if a namespace browser is made available to him. This browser can either be general-purpose or be supplied by the application. Using JNDI, to list the contents of a particular level in the namespace, the code looks as follows.

	NamingEnumeration list = namespace.list("o=Widget, c=US");
	while (list.hasMore()) {
		NameClassPair entry = (NameClassPair)list.next();
		display(entry.getName(), entry.getClassName());
	}

Oracle is reviewing the Sun product roadmap and will provide guidance to customers in accordance with Oracle's standard product communication policies. Any resulting features and timing of release of such features as determined by Oracle's review of roadmaps, are at the sole discretion of Oracle. All product roadmap information, whether communicated by Sun Microsystems or by Oracle, does not represent a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. It is intended for information purposes only, and may not be incorporated into any contract.