Using JNDI with J2EE RI
As far as this book is concerned the role of JNDI is to support access to the different components of your application. Your J2EE vendor will provide a name service that you can use with each component technology (EJBs, servlets, JSPs and application clients).
This section will concentrate on registering and using named objects within a J2EE application. Later sections will discuss using JNDI as a Java technology outside of a J2EE server.
In simple terms JNDI has two roles within a J2EE server:
To bind distributed objects such as EJBs, JDBC datasources, URLs, JMS resources, and so on.
To look up and use bound objects.
The following sections provide a simple introduction to these two roles.
Binding J2EE Components
The binding of J2EE components is done by the J2EE container either as part of the process of deploying a component or as a separate operation. You will not normally use the JNDI API to bind any objects.
Tomorrow you will look at the deployment process for registering an EJB against a JNDI name. Today you will consider the Agency case study database you created as part of yesterday's exercise (Day 2, "The J2EE Platform and Roles"). On Day 2 you used a simple Java program to define and populate the database schema. At the same time you also used the J2EE RI asadmin command to bind a javax.sql.DataSource to a JNDI name for accessing the database from within the applications you will develop in subsequent days of this book. You either used the supplied asant build files and entered the command
asant create-jdbc
or you entered the asadmin command yourself. Either way the executed command was:
asadmin create-jdbc-resource --connectionpoolid PointBasePool --enabled=true jdbc/Agency
What you did with this command was bind a DataSource object against the JNDI name jdbc/Agency.
The asadmin command is specific to the J2EE RI server but other J2EE servers will have similar utilities for registering JDBC datasources. The J2EE RI also provides a Web-based interface for administration as discussed on Day 2. You can verify that your jdbc/Agency object is bound correctly by starting up the J2EE RI server and then browsing to http://localhost:4848/asadmin/ (MS Windows users can use the Start, Sun Microsystems, J2EE 1.4 SDK, Admin Console menu item). You will need to provide your administrative username and password, which will be admin and password if you followed the instructions on Day 2.
In the Admin Console Web Application select JDBC Resources and then jdbc/Agency in the left hand window and you will see the view shown in Figure 3.2.
Figure 3.2 Case Study jdbc/Agency DataSource.
J2EE RI implements a datasource by associating it with a connection pool object, and it is this object that contains the connection information for the database. Other J2EE servers may encode the database connection information with the datasource itself.
In the J2EE RI Admin Console select the jdbc/PointBasePool entry in the left window and scroll the right window down to the Properties section at the bottom of the page as shown in Figure 3.3.
From the Connection Pool properties you can see the Connection URL for the PointBase database used for the case study tables (jdbc:pointbase:server://localhost:9092/sun-appserv-samples) and the username and password used to access the database (pbPublic in both cases). You don't need to be aware of the details of the database connection information as this is now encapsulated behind a DataSource object.
All you have to do to use the database is know the name the datasource has been registered against, and then look up the DataSource object.
Figure 3.3 J2EE RI Point Base Pool Connection.
Lookup of J2EE Components
Using JNDI to look up a J2EE component is a simple two-step process:
Obtain a JNDI InitialContext object.
Use this context to look up the required object.
The first step in using the JNDI name service is to get a context in which to add or find names. The context that represents the entire namespace is called the Initial Context This Initial Context is represented by a class called javax.naming.InitialContext, which is a sub-class of the javax.naming.Context class.
A Context object represents a context that you can use to look up objects or add new objects to the namespace. You can also interrogate the context to get a list of objects bound to that context.
The following code creates a context using the default name service within the J2EE container:
Context ctx = new InitialContext();
If something goes wrong when creating the context, a NamingException is thrown. You are unlikely to come across problems creating the InitialContext within a J2EE server (other possible problems are discussed later in the section "Initial Context Naming Exceptions").
Once you have a Context object you can use the lookup() method to obtain your required component. The following code obtains the jdbc/Agency DataSource:
DataSource dataSource = (DataSource)ctx.lookup("jdbc/Agency");
Note that lookup() returns a java.lang.Object and this must be cast into a javax.sql.DataSource.
There are two common problems at this stage:
You mistyped the name, or the object isn't bound to the name service, in which case a javax.naming.NameNotFound exception is thrown.
The object you retrieved was not what you expected and a ClassCastException will be thrown.
That's it. You can now use the DataSource to access the database. Listing 3.1 shows a simple application that will list the contents of the database tables passed as command line parameters.
Listing 3.1 Full Text of AgencyTable.java
import javax.naming.* ; import java.sql.*; import javax.sql.*; public class AgencyTable { public static void main(String args[]) { try { AgencyTable at = new AgencyTable(); for (int i=0; i<args.length; i++) at.printTable(args[i]); } catch (NamingException ex) { System.out.println ("Error connecting to jdbc/Agency: "+ex); } catch (SQLException ex) { System.out.println ("Error getting table rows: "+ex); } } private DataSource dataSource; public AgencyTable () throws NamingException { InitialContext ic = new InitialContext(); dataSource = (DataSource)ic.lookup("jdbc/Agency"); } public void printTable(String table) throws SQLException { Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; try { con = dataSource.getConnection(); stmt = con.prepareStatement("SELECT * FROM "+table); rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int numCols = rsmd.getColumnCount(); // get column header info for (int i=1; i <= numCols; i++) { System.out.print (rsmd.getColumnLabel(i)); if (i > 1) System.out.print (','); } System.out.println (); while (rs.next()) { for (int i=1; i <= numCols; i++) { System.out.print (rs.getString(i)); if (i > 1) System.out.print (','); } System.out.println (); } } finally { try {rs.close();} catch (Exception ex) {} try {stmt.close();} catch (Exception ex) {} try {con.close();} catch (Exception ex) {} } } }
Before you can run this example you must have started the J2EE RI default domain and be running the PointBase database server as discussed on Day 2.
Run this application using the supplied asant build files entering the following command from within the Day03/examples directory:
asant AgencyTable
You will be prompted to provide a space-separated list of tables to examine; choose any of the tables shown in yesterdays ERD (such as Applicant, Customer, Location).
NOTE
You must use the supplied asant build files to run today's examples. The name service provided with the J2EE RI must be used by a J2EE component such as a Client Application and cannot be used by a normal command line program. The asant build files wrap up the program as a J2EE Application Client and set up the correct CLASSPATH before running the program. Application Clients are discussed in detail tomorrow and in the section "Using JNDI Functionality" later today.
Hopefully you can see the benefits of using both JNDI and DataSource objects within your enterprise application. Compare the code in Listing 3.1 with the code used to connect to the database in CreateAgency.java program used yesterday (Day02/exercise/src/CreateAgency.java), shown in the following excerpt:
Class.forName("com.pointbase.jdbc.jdbcUniversalDriver"); Connection con = DriverManager.getConnection( "jdbc:pointbase:server://localhost/sun-appserv-samples,new", "pbPublic","pbPublic");
In this excerpt the database details are hard coded into the application making it awkward to migrate the application to a new database. If you look at the code for the CreateAgency.java program on the Web site, you will see commented out definitions for the database connection details for the Cloudscape database that was shipped with J2EE RI 1.3. The example in Listing 3.1 has not changed between J2EE RI 1.3 and J2EE RI 1.4 despite the change of database provider.
Other Distributed J2EE Components
Throughout many of the days of this course you will use JNDI to look up many different types of objects:
EJBson most days from 4 through to 14
The javax.transaction.UserTransaction object on Day 8, "Transactions and Persistence"
JMS resources on Day 9, "Java Message Service" and Day 10, "Message-Driven Beans"
Resource Adapters and RMI-IIOP servants on Day 19, "Integrating with External Resources"
For each of these objects, except EJBs, you will use the J2EE RI asadmin command to define the required resources. For EJBs you will use the deploytool application (discussed tomorrow) to define the JNDI name as part of the deployment process for the EJB.
There is one minor twist to using EJBs and RMI-IIOP objects with JNDI and this is the type of object that is stored in the name service.
EJBs use RMI-IIOP and when a JNDI lookup is used to obtain an EJB (or any RMI-IIOP object) you obtain an RMI-IIOP remote object stub and not the actual object you expect. You must downcast the CORBA object into the actual object you require using the PortableRemoteObject.narrow() method.
Looking ahead momentarily to tomorrow's work on EJBs, the following code fragment shows how to look up an EJB:
InitialContext ctx = new InitialContext(); Object lookup = ctx.lookup("ejb/Agency"); AgencyHome home = (AgencyHome)PortableRemoteObject.narrow( lookup, AgencyHome.class);
In this case the EJB is bound against the name ejb/Agency and is of type agency.AgencyHome. This example has been slightly simplified from the real code which is shown in the next section, "J2EE Java Component Environment."
The narrow() method takes as parameters the RMI-IIOP remote stub object and the Class object representing the target class for the downcast. This method will throw a ClassCastException if the remote stub does not represent the correct class.
J2EE Java Component Environment
One extra issue concerning J2EE components that should be considered now, while you are looking at JNDI within the J2EE server framework, is that of the Java Component Environment.
To explain this concept consider the case where two developers independently design and develop EJBs both of whom use the name jdbc/Database as the name of the DataSource object used to access the database. An application assembler wants to use both EJBs in a single application but each EJB was designed to use a different database schema. Such a situation may arise if the assembler is "buying in" EJBs developed by external organizations.
The Java Component Environment is designed to resolve the possibility of JNDI resource name conflicts by providing each component with its own private namespace. Every J2EE component has a context within its namespace called java:comp/env that is used to store references to resources required by that component. The component's deployment descriptor defines the resources referenced by the component that will need to be defined within the Java Component Environment.
Resources that can be referenced by a J2EE component include:
Enterprise JavaBeansdiscussed primarily on Day 5, "Session EJBs," and Day 6, "Entity EJBs."
Environment Entriesdiscussed on Day 5.
Message Destination Referencesdiscussed on Day 10.
Resource Referencesdiscussed today (DataSource) and on Day 10 (ConnectionFactory).
Web Service Referencesdiscussed on Day 20, "Using RPC-Style Web Services with J2EE."
Returning to the example from the previous section, where the sample code for an EJB lookup was shown without the complication of the Java Component Environment, the actual EJB lookup code is
InitialContext ctx = new InitialContext(); Object lookup = ctx.lookup("java:comp/env/ejb/Agency"); AgencyHome home = (AgencyHome)PortableRemoteObject.narrow( lookup, AgencyHome.class);
The ejb/Agency name is defined as an EJB Reference within the Java Component Environment. As part of the deployment process the EJB Reference will be mapped onto the actual JNDI name used by the EJB (if you are a little lost at this point, don't worry, all will be made clear on Days 4 and 5).