Home > Articles > Programming > Java

This chapter is from the book

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:

  1. To bind distributed objects such as EJBs, JDBC datasources, URLs, JMS resources, and so on.

  2. 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.2Figure 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.3Figure 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:

  1. Obtain a JNDI InitialContext object.

  2. 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:

  • EJBs—on 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 JavaBeans—discussed primarily on Day 5, "Session EJBs," and Day 6, "Entity EJBs."

  • Environment Entries—discussed on Day 5.

  • Message Destination References—discussed on Day 10.

  • Resource References—discussed today (DataSource) and on Day 10 (ConnectionFactory).

  • Web Service References—discussed 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).

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020