YOUR FEEDBACK
Gregor Rosenauer wrote: well, not what's your take on this? Did I miss a second page of this article or...
AJAXWorld RIA Conference
Early Bird Savings Expire Friday Register Today and SAVE !..

2008 East
DIAMOND SPONSOR:
Data Direct
Frontiers in Data Access: The Coming Wave in Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
Intel
Virtualization – Path to Predictive Enterprise
Green Hills
IT Security in a Hostile World
JBoss / freedom oss
Practical SOA Approach
GOLD SPONSORS:
Software AG
The Art & Science of SOA: How Governance Enables Adoption
PlateSpin
Effective Planning for Virtual Infrastructure Growth
Fujitsu
Automated Business Process Discovery & Virtualization Service
Ceedo
Workspace Virtualization
Click For 2007 West
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts

SYS-CON.TV
TOP THREE LINKS YOU MUST CLICK ON


To Begin at the Beginning...
JNDI Initial Contexts

The Java Naming and Directory Interface (JNDI) has a central role in the Java 2 Platform, Enterprise Edition (J2EE). J2EE applications use JNDI to look up components and services, including JMS queues and topics, transaction services, JDBC connections, and EJBs.

The first programming step required to use JNDI is to create an initial context object that acts as the entry point into the JNDI namespace. In this article, I discuss how to create JNDI initial context objects for use with BEA WebLogic Server. The information provided is based on JNDI 1.2/Java 2 and is equally applicable to versions 5.1, 6.0, and 6.1 of WebLogic Server.

Client JNDI Access
If you've done any J2EE programming, the following code should be familiar to you.

import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;

// ...

final Hashtable properties = new Hashtable();
properties.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
final Context context = new InitialContext(properties);

This is the minimal J2EE code required for a Java client to establish a connection to the WebLogic Server JNDI tree. You must provide the fully qualified class name of an initial context factory that will be used to make the connection. For the WebLogic Server JNDI implementation, use the class weblogic.jndi.WLInitialContextFactory.

If you're not interested in J2EE compatibility, you can use the weblogic.jndi.Environment class, which provides type-safe methods for building the properties used to create initial context objects. Everything you can do with the Environment class you can do by setting properties directly, so I won't discuss it further.

The initial context factory class is loaded dynamically, so it must be in the run-time classpath but needn't be in the compilation classpath. If you consider compile-time type checking to be a good idea, you might prefer this modification.

// ...
final Hashtable properties = new Hashtable();

properties.put(Context.INITIAL_CONTEXT_FACTORY,
weblogic.jndi.WLInitialContextFactory.class.getName());

final Context context = new InitialContext(properties);

By default, WLInitialContextFactory attempts to connect to a WebLogic Server instance at the URL t3://localhost:7001. If you run this code snippet without an instance of WebLogic Server running on the local machine, a javax.naming.CommunicationException will be thrown. To connect to a server running on a different machine or port you need to specify a provider URL.

// ...
properties.put(Context.INITIAL_CONTEXT_FACTORY,
weblogic.jndi.WLInitialContextFactory.class.getName());

properties.put(Context.PROVIDER_URL,
"t3://server:9999");

final Context context = new InitialContext(properties);

The provider URL specifies the server host name and port and the protocol to use. If you're bridging a firewall, you might wish the connection to be made using an HTTP tunnelled connection. (You should ensure that the server has HTTP tunnelling enabled.)

// ...
properties.put(Context.PROVIDER_URL,
"http://server:9999");
// ...

If the connection to the remote server takes an inordinately long time, say several seconds, there is usually a problem with the client's DNS configuration. Try replacing the host name with the server's IP address. If this cures the problem, investigate further: using host names rather than IP addresses is preferable from a network administrator's viewpoint. Context.INITIAL_CONTEXT_ FACTORY and Context.PROVIDER_URL are examples of JNDI environment properties.

Server JNDI Access
Creating an initial context from server-side code is trivial.

final Context context = new InitialContext();

This provides a connection to the local WebLogic Server JNDI tree. Other than Context.SECURITY_ PRINCIPAL and Context.SECURITY_CREDENTIALS (discussed below) you rarely need to pass additional JNDI environment properties. If you want to, you can safely specify Context.PROVIDER_ URL. WebLogic Server detects attempts to connect to the local JNDI tree and doesn't create a new socket connection to the local listen port.

Alternative Ways to Set JNDI Environment Properties
What if you don't want to hard-code JNDI environment properties? You might not know the location of the servers in your deployment environment, you might want the option of switching to use another JNDI provider without recompiling or you might want to write library code that will be deployed on both client and server machines. There are a couple of standard JNDI features that allow you to do this without writing code.

First, you can set default values using Java system properties. Standard Java Virtual Machines have a -D option that allows system properties to be set. To make WLInitialContextFactory the default initial context factory, you could start your client JVM as follows:

$ java -Djava.naming.factory.initial= weblogic.jndi.WLInitialContextFactory com.bea.paston.jndi.client.MyJNDIClient

The string "java.naming.factory.initial" is the value of Context.INITIAL_CONTEXT_FACTORY. Other common values are given in Table 1.

Second, you can set default values by creating a Java properties file (see java.util.Properties) called jndi.properties and placing it in the classpath. The file should contain lines of the form property name=value, where property name is taken from the table. The file can also be placed in the current working directory or in the lib directory of the Java Virtual Machine ($JAVA_HOME/lib).

You can mix and match these methods and use multiple jndi.properties files. If a property is specified using more than one method, the value to use is determined according to the following list (highest precedence first):

  • Explicitly coded in creation of an InitialContext
  • System property
  • jndi.properties file in classpath
  • jndi.properties file later in classpath
  • jndi.properties file in current working directory
  • jndi.properties file in JVM lib directory
Applets and JNDI Environment Properties
JNDI provides a convenient way to set properties for applets. If you code your initial context look-up within your applet as follows, you can use applet parameters to specify JNDI environment properties.
// ...
final Hashtable properties = new Hashtable();
properties.put(Context.APPLET, this);
final Context context = new InitialContext(properties);

A typical applet tag is shown below.

<applet codebase="/classes"
code="com.bea.paston.jndi.client.TestApplet">
<param name="java.naming.factory.initial"
value="weblogic.jndi.WLInitialContextFactory">
<param name="java.naming.provider.url"
value="http://server:7001">
</applet>

Applet parameters are not read unless you set the Context.APPLET property.

Applets don't normally have the necessary security rights to read the system properties and don't have the concept of a current working directory, so JNDI environment properties can't be set using these methods. The order of resolution for applets is as follows:

  • Explicitly specified in creation of an InitialContext
  • Applet parameter
  • jndi.properties file in classpath
  • jndi.properties file later in classpath
  • jndi.properties file in JVM lib directory

JNDI and WebLogic Server Security
From version 6.0, WebLogic Server has an implementation of the Java Authentication and Authorization Service (JAAS). JAAS is the J2EE standard mechanism for establishing security contexts and is the BEA recommended approach for new developments.

Each thread within a WebLogic Server instance or WebLogic RMI client has an associated stack of WebLogic Server security contexts. When you create a new initial context object using the WLInitialContextFactory with the JNDI environment properties Context.SECURITY_PRINCIPAL and Context.SECURITY_CREDENTIALS set to valid authentication details, a new security context is pushed onto the stack. This security context is used for every access control check against actions performed by that thread, whether the action involves local or remote services. When you invoke close on the initial context object, the security context is popped off the thread stack and the previous security context takes effect.

Within WebLogic Server, each request, whether it is a servlet call, JMS message, or RMI invocation, is processed by a single execute thread. The initial security context is determined by the authentication associated with the request. The creation of an initial context can be used to associate a new security context with the request. When the execute thread has finished processing the request, the security context stack is discarded.

If you have some code that needs to access a component, say an EJB, under a specific identity you can simply set up an initial context appropriately before looking up the EJB's home interface, use the EJB, and then close the initial context. However, while the association of security context with JNDI is convenient in some circumstances, it is very clumsy in others. The security context is associated with the current request, not the object obtained from JNDI, so you have to create a new initial context every time you need to access the EJB. This is where JAAS can help; it provides an independent way to alter the security context.

You should not attempt to share initial context objects created using Context.SECURITY_PRINCIPAL and Context.SECURITY_CREDENTIALS properties between threads.

Closing Contexts
To be a good J2EE citizen, you should ideally ensure that close is invoked on an initial context object after use. This lets the JNDI implementation free up any associated resources. Don't worry too much about this with WebLogic Server, there are no costly associated resources and the current implementation of close just affects the security context.

Should I Cache JNDI Look-Ups?
Client-side code can save unnecessary network calls by reusing the references returned from JNDI look-ups where possible. Where the client is retrying a failed call to a remote component it can make sense to perform the JNDI look-up again; this allows the client to be more robust when components are redeployed, the server is rebooted and so on.

Creating an initial context object and performing a local JNDI look-up from server-side code both take about a hundred nanoseconds on typical server hardware. It is usually convenient and frugal to cache the results of the look-up. This is commonly done in servlet init and session EJB setSessionContext methods.

There are two reasons you might not want to cache the reference resulting from server-side JNDI look-ups. First, you may wish to detect dynamic changes to the JNDI tree. Second, you may wish to use the InitialContext creation to set the appropriate security context. (You can cache references and create independent initial context objects to alter the security context but I hope, after reading the previous section, you are searching for the JAAS documentation.)

Next Steps
I've covered the details of establishing an initial context to the WebLogic Server JNDI tree. This only scratches the surface of the JNDI API but is a key first step for most J2EE programs.

In future articles I will delve into more involved use of the JNDI, examining topics such as JNDI federation and the role of JNDI in WebLogic clusters.

BEA WEBLOGIC LATEST STORIES
Since its emergence, Web Service technology has gone a long way towards perfecting itself and finding its right application in the real world. With the maturity of the specifications, Web Service technology, with its power of interoperability, is now the major enabling technology of SO...
Join Scott Guthrie as he discusses Microsoft’s commitment to web standards development, Rich Internet Applications and how Microsoft is contributing to help move the web forward. Join Adobe’s Kevin Lynch as he demonstrates how Flash and HTML come together to make the most engaging,...
Virtualization has become a critical part of Enterprise IT strategy. Why and how has it become one of the most important change agents in our industry? To answer these questions I had the good fortune recently to be able to speak to a select group of top IT industry executives who join...
Watching VMware stock and its market cap spike since it IPO'd must have had Red Hat positively pea green with envyWatching VMware stock and its market cap spike since it IPO'd must have had Red Hat positively pea green with envy - so green in fact that it's gonna try taking VMware on b...
A standard from OASIS called Web Services for Remote Portlets (WSRP) is used so portlets can be decoupled from a portal. In part one (JDJ, Volume. 13, issue 3) of this article, we introduced the relevant standards and specifications and then demonstrated WSRP's capabilities by consumin...
SYS-CON's upcoming '3rd International Virtualization Conference & Expo' faculty includes such distinguished speakers as: Al Aghili (Managed Methods), Alan Chhabra (Egenera), Andi Mann (Enterprise Management Associates), Andrew Conte (APC), Andy Astor (EnterpriseDB), Ariel Cohen (Xsigo ...
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE
BREAKING NEWS FROM THE WIRES

Autodesk, Inc. (NASDAQ:ADSK) today announced that its Autodesk LocationLogic platfo...