JNDI Lookup Code
One of the first steps in creating a JMS client is writing the code for looking up the client's administered objects in JNDI.
In the lookup code for this example, the variable factory is defined as an object of type ConnectionFactory, which signifies a "generic" connection factory. Although it is possible to specify connection factories as topic connection factories or queue connection factories, coding a connection factory in this manner provides a greater degree of flexibility, allowing you to determine the type of connection factory at run time rather than at design time.
The lookup code also defines a generic destination variable, which represents the text message to be sent and received. Consistent with usage of a generic ConnectionFactory, usage of a generic destination allows this object to be specified as a queue, topic, temporary queue, or temporary topic at run time.
Both the sender and receiver applications use the initialize() method containing the JNDI lookup code (shown following). Its parameters (the names of the connection factory and destination) are passed in at run time as command line arguments.
protected ConnectionFactory factory;
protected Destination destination;
protected SimpleApplication() {}
public boolean initialize(String factoryName, String destinationName)
{
factory = lookupFactory(factoryName);
destination = lookupDestination(destinationName);
return factory != null && destination != null;
}
public boolean initialize(String factoryName)
{
factory = lookupFactory(factoryName);
return factory != null;
}
The code for the two JNDI lookup methods is shown below. These methods get an initial context from the JNDI namespace (an initial context provides access to the JNDI provider and connects to the namespace in which the administered objects are stored). The methods then return the objects that correspond to the names passed in as parameters.
private Destination lookupDestination(String name)
{
try {
Context namingContext = new InitialContext();
Object destinationObject = namingContext.lookup(name);
namingContext.close();
if (destinationObject instanceof Destination) {
return (Destination) destinationObject; }
. . .
private ConnectionFactory lookupFactory(String name)
{
try {
Context namingContext = new InitialContext();
Object factoryObject = namingContext.lookup(name);
namingContext.close();
if (factoryObject instanceof ConnectionFactory) {
return (ConnectionFactory) factoryObject; }
. . .