The J2EETM Tutorial

Common Client Interface

This section describes how components use the Connector architecture Common Client Interface (CCI) API and a resource adapter to access data from an EIS.

Overview of the CCI

Defined by the J2EE Connector Architecture specification, the CCI defines a set of interfaces and classes whose methods allow a client to perform typical data access operations. Our example CoffeeEJB session bean includes methods that illustrate how to use the CCI, in particular, the following CCI interfaces and classes:

A client or application component that uses the CCI to interact with an underlying EIS does so in a prescribed manner. The component must establish a connection to the EIS's resource manager, and it does so using the ConnectionFactory. The Connection object represents the actual connection to the EIS and is used for subsequent interactions with the EIS.

The component performs its interactions with the EIS, such as accessing data from a specific table, using an Interaction object. The application component defines the Interaction object using an InteractionSpec object. When the application component reads data from the EIS (such as from database tables) or writes to those tables, it does so using a particular type of Record instance, either a MappedRecord, IndexedRecord, or ResultSet instance. Just as the ConnectionFactory creates Connection instances, a RecordFactory creates Record instances.

Our example shows how a session bean uses a resource adapter to add and read records in a relational database. The example shows how to invoke stored procedures, which are business logic functions stored in a database and specific to an enterprise's operation. Stored procedures consist of SQL code to perform operations related to the business needs of an organization. They are kept in the database and can be invoked when needed, just as you might invoke a Java method. In addition to showing how to use the CCI to invoke stored procedures, we'll also explain how to pass parameters to stored procedures and how to map the parameter data types from SQL to those of the Java programming language.

Programming with the CCI

The code for the following example is in the examples/src/connector/cci directory.

To illustrate how to use a CCI resource adapter, we've written a session bean and a client of that bean. These pieces of code illustrate how clients invoke the different CCI methods that resource adapters built on CCI might make available. Our example uses the two sample CCI-specific resource adapters: cciblackbox_tx.rar and cciblackbox_xa.rar.

The Coffee session bean is much like any other session bean. It has a home interface (CoffeeHome), a remote interface (Coffee), and an implementation class (CoffeeEJB). To keep things simple, we've called the client CoffeeClient.

Let's start with the session bean interfaces and classes. The home interface, CoffeeHome, is like any other session bean home interface. It extends EJBHome and defines a create method to return a reference to the Coffee remote interface.

The Coffee remote interface defines the bean's two methods that may be called by a client.

public void insertCoffee(String name, int quantity)	
throws RemoteException;	
public int getCoffeeCount() throws RemoteException;

Now let's examine the CoffeeEJB session bean implementation class to see how it uses the CCI. To begin with, notice that CoffeeEJB imports the javax.resource CCI interfaces and classes, along with the javax.resource.ResourceException and the sample cciblackbox classes.

import javax.resource.cci.*;	
import javax.resource.ResourceException;	
import com.sun.connector.cciblackbox.*;	
Obtaining a Database Connection

Prior to obtaining a database connection, the session bean does some set up work in its setSessionContext method. (See the following code example.) Specifically, the setSessionContext method sets the user and password values, and instantiates a ConnectionFactory. These values and objects remain available to the other session bean methods. (In this and subsequent code examples, the numbers in the left margin correspond to the explanation that follows the code.)

   public void setSessionContext(SessionContext sc) {	
        try {	
   = sc;	
1           Context ic = new InitialContext();	
2           user = (String) ic.lookup("java:comp/env/user");	
            password = (String) ic.lookup	
3           cf = (ConnectionFactory) ic.lookup	
        } catch (NamingException ex) {	
  1. Establish a JNDI InitialContext.
  2. Use the JNDI InitialContext.lookup method to find the user and password values.
  3. Use the lookup method to locate the ConnectionFactory for the CCI black box resource adapter and obtain a reference to it.

CoffeeEJB uses its private method getCCIConnection to establish a connection to the underlying resource manager or database. A client of the Coffee session bean cannot invoke this method directly. Rather, the session bean uses this method internally to establish a connection to the database. The following code uses the CCI to establish a database connection.

    private Connection getCCIConnection() {	
        Connection con = null;	
        try {	
1           ConnectionSpec spec = 	
                new CciConnectionSpec(user, password);	
2           con = cf.getConnection(spec);	
        } catch (ResourceException ex) {	
        return con;	
  1. Instantiate a new CciConnectionSpec object with the user and password values obtained by the setSessionContext method. The CciConnectionSpec class is the implementation of the ConnectionSpec interface.
  2. Call the ConnectionFactory.getConnection method to obtain a connection to the database. (The reference to the ConnectionFactory was obtained in the setSessionContext method.) Use the CciConnectionSpec object to pass the required properties to the ConnectionFactory. The getConnection method returns a Connection object.

The CoffeeEJB bean also includes a private method, closeCCIConnection, to close a connection. The method invokes the Connection object's close method from within a try/catch block. Like the getCCIConnection method, this is a private method intended to be called from within the session bean.

private void closeCCIConnection(Connection con) {	
    try {	
    } catch (ResourceException ex) {	

Database Stored Procedures

The sample CCI black box adapters call database stored procedures. It is important to understand stored procedures before delving into how to read or write data using the sample CCI black box adapters. The methods of these sample CCI adapters do not actually read data from a database or update database data. Instead, these sample CCI adapters enable you to invoke database stored procedures, and it is the stored procedures that actually read or write to the database.

A stored procedure is a business logic method or function that is stored in a database and is specific for the enterprise's business. Typically, stored procedures consist of SQL code, though in certain cases (such as with Cloudscape) they may consist of code written in the Java programming language. Stored procedures perform operations related to the business needs of an organization. They are kept in the database, and applications can invoke them when needed.

Stored procedures are typically SQL statements. Our example calls two stored procedures: COUNTCOFFEE and INSERTCOFFEE. The COUNTCOFFEE procedure merely counts the number of coffee records in the Coffee table, as follows:


The INSERTCOFFFEE procedure adds a record with two values, passed to the procedure as parameters, to the same Coffee table, as follows:


Mapping to Stored Procedure Parameters

When you invoke a stored procedure from your application component, you may have to pass argument values to the procedure. For example, when you invoke the INSERTCOFFEE procedure, you pass it two values for the Coffee record elements. Likewise, you must be prepared to receive values that a stored procedure returns.

The stored procedure, in turn, passes its set of parameters to the database management system (DBMS) to carry out its operation and may receive values back from the DBMS. Database stored procedures specify, for each of their parameters, the SQL type of the parameter value and the mode of the parameter. Mode can be input (IN), output (OUT), or both input and output (INOUT). An input parameter only passes data in to the DBMS, and an output parameter only receives data back from the DBMS. An INOUT parameter accepts both input and output data.

When you use the CCI execute method to invoke a database stored procedure you also create an instance of an InputRecord, provided that you're passing a parameter to the stored procedure and that the stored procedure you're executing returns data (possibly an OutputRecord instance). The InputRecord and OutputRecord are instances of the supported Record types: IndexedRecord, MappedRecord, or ResultSet. In our example, we instantiate an InputRecord and an OutputRecord that are both IndexedRecord instances.

Note: The CCI black box adapters only support IndexedRecord types.

The InputRecord maps the IN and INOUT parameters for the stored procedure, and the OutputRecord maps the OUT and INOUT parameters. Each element of an input or output record corresponds to a stored procedure parameter. That is, there is an entry in the InputRecord for each IN and INOUT parameter declared in the stored procedure. Not only does the InputRecord have the same number of elements as the procedure's input parameters, but they also are declared in the same order as in the procedure's parameter list. The same holds true for the OutputRecord, though its list of elements matches only the OUT and INOUT parameters. For example, suppose you have a stored procedure X that declares three parameters. The first parameter is an IN parameter, the second is an OUT parameter, and the third is an INOUT parameter. Figure 17-2 shows how the elements of an InputRecord and an OutputRecord map to this stored procedure.

Figure 17-2 Mapping Stored Procedure Parameters to CCI Record Elements

When you use the CCI black box adapter, you designate the parameter type and mode in the same way, though the underlying Oracle or Cloudscape DBMS declares the mode differently. Oracle designates the parameter's mode in the stored procedure declaration, along with the parameter's type declaration. For example, an Oracle INSERTCOFFEE procedure declares its two IN parameters as follows:


An Oracle COUNTCOFFEE procedure declares its parameter N as an OUT parameter:


Cloudscape, which declares a stored procedure as a method signature in the Java programming language, indicates an IN parameter using a single value, and an INOUT parameter using an array. The method's return value is the OUT parameter. For example, Cloudscape declares the IN parameters (name and qty) for insertCoffee and the OUT parameter (the method's return value) for countCoffee as follows:

public static void insertCoffee(String name, int qty)	
public int countCoffee()

If qty were an INOUT parameter, then Cloudscape would declares it as

public static void insertCoffee(String name, int[] qty)

Oracle would declare it as


You must also map the SQL type of each value to its corresponding Java type. Thus, if the SQL type is an integer, then the InputRecord or OutputRecord element must be defined as an Integer object. If the SQL type is a VARCHAR, then the Java type must be a String object. Thus, when you add the element to the Record, you declare it to be an object of the proper type. For example, add an integer and a string element to an InputRecord as follows:

iRec.add (new Integer (intval));	
iRec.add (new String ("Mocha Java"));

Note: The JDBC Specification defines the type mapping of SQL and the Java programming language.

Reading Database Records

The getCoffeeCount method of CoffeeEJB illustrates how to use the CCI to read records from a database table. This method does not directly read the database records itself; instead, it invokes a procedure stored in the database called COUNTCOFFEE. It is the stored procedure that actually reads the records in the database table.

The CCI provides interfaces for three types of records: IndexedRecord, MappedRecord, and ResultSet. These three record types inherit from the base interface, Record. They differ only in how they map the record elements within the record. Our example uses IndexedRecord, which is the only record type currently supported. IndexedRecord holds its record elements in an ordered, indexed collection based on java.util.List. As a result, we use an Iterator object to access the individual elements in the list.

Let's begin by looking at how the getCoffeeCount method uses the CCI to invoke a database stored procedure. Again, note that the numbers in the margin to the left of the code correspond to the explanation after the code example.

    public int getCoffeeCount() {	
        int count = -1;	
        try {	
1           Connection con = getCCIConnection();	
2           Interaction ix = con.createInteraction();	
3           CciInteractionSpec iSpec =	
               new CciInteractionSpec();	
4           iSpec.setSchema(user);	
5           RecordFactory rf = cf.getRecordFactory();	
6           IndexedRecord iRec =	
7           Record oRec = ix.execute(iSpec, iRec);	
8           Iterator iterator = 	
9           while(iterator.hasNext()) {   	
                Object obj =;	
                if(obj instanceof Integer) {	
                    count = ((Integer)obj).intValue();	
                else if(obj instanceof BigDecimal) {	
                    count = ((BigDecimal)obj).intValue();	
10          closeCCIConnection(con);	
        }catch(ResourceException ex) {	
        return count;	
  1. Obtain a connection to the database.
  2. Create a new Interaction instance. The getCoffeeCount method creates a new Interaction instance because it is this object that enables the session bean to execute EIS functions such as invoking stored procedures.
  3. Instantiate a CciInteractionSpec object. The session bean must pass certain properties to the Interaction object, such as schema name, catalog name, and the name of the stored procedure. It does this by instantiating a CciInteractionSpec object. The CciInteractionSpec is the implementation class for the InteractionSpec interface, and it holds properties required by the Interaction object to interact with an EIS instance. (Note that our example uses a Cloudscape database, which does not require a catalog name.)
  4. Set values for the CciInteractionSpec instance's fields. The session bean uses the CciInteractionSpec methods setSchema, setCatalog, and setFunctionName to set the required values into the instance's fields. Our example passes COUNTCOFFEE to setFunctionName because this is the name of the stored procedure it intends to invoke.
  5. The getCoffeeCount method uses the ConnectionFactory to obtain a reference to a RecordFactory so that it can create an IndexedRecord instance. We obtain an IndexedRecord (or a MappedRecord or a ResultSet) using a RecordFactory.
  6. Invoke the createIndexedRecord method of RecordFactory. This method creates a new IndexedRecord using the name InputRecord, which is passed to it as an argument.
  7. The getCoffeeCount method has completed the required set-up work and can invoke the stored procedure COUNTCOFFEE. It does this using the Interaction instance's execute method. Notice that it passes two objects to the execute method: the InteractionSpec object, whose properties reference the COUNTCOFFEE stored procedure, and the IndexedRecord object, which the method expects to be an input Record. The execute method returns an output Record object.
  8. The getCoffeeCount method uses an Iterator to retrieve the individual elements from the returned IndexedRecord. It casts the output Record object to an IndexedRecord. IndexedRecord contains an iterator method that it inherits from java.util.List.
  9. Retrieve each element in the returned record object using the iterator.hasNext method. Each extracted element is an Object, and the bean evaluates whether it is an integer or decimal value and processes it accordingly.
  10. Close the connection to the database.

Inserting Database Records

The CoffeeEJB session bean implements the insertCoffee method to add new records into the Coffee database table. This method invokes the INSERTCOFFEE stored procedure, which inserts a record with the values (name and qty) passed to it as arguments.

The insertCoffee method shown here illustrates how to use the CCI to invoke a stored procedure that expects to be passed argument values. This example shows the code for the insertCoffee method and is followed by an explanation.

    public void insertCoffee(String name, int qty) {	
        try {	
1           Connection con = getCCIConnection();	
2           Interaction ix = con.createInteraction();	
3           CciInteractionSpec iSpec = 	
               new CciInteractionSpec();	
4           iSpec.setFunctionName("INSERTCOFFEE");	
5           RecordFactory rf = cf.getRecordFactory();	
6           IndexedRecord iRec =	
7           boolean flag = iRec.add(name);	
            flag = iRec.add(new Integer(qty));	
8           ix.execute(iSpec, iRec);	
9           closeCCIConnection(con);	
        }catch(ResourceException ex) {	
  1. Establish a connection to the database.
  2. Create a new Interaction instance for the connection so that the bean can execute the database's stored procedures.
  3. Instantiate a CciInteractionSpec object so that the bean can pass the necessary properties--schema name, catalog name, and stored procedure name--to the Interaction object. The CciInteractionSpec class implements the InteractionSpec interface and holds properties that the Interaction object requires to communicate with the database instance.
  4. Set the required values into the new CciInteractionSpec instance's fields, using the instance's setSchema, setCatalog, and setFunctionName methods. Our example passes INSERTCOFFEE to setFunctionName, and user to setSchema.
  5. Obtain a reference to a RecordFactory using the ConnectionFactory object's getRecordFactory method.
  6. Invoke the RecordFactory object's createIndexedRecord method to create a new IndexedRecord with the name InputRecord.
  7. Use the IndexedRecord add method to set the values for the two elements in the new record. Call the add method once for each element. Our example sets the first record element to the name value and the second element to the qty value. Notice that qty is set to an Integer object when passed to the add method. The CoffeeEJB session bean is now ready to add the new record to the database.
  8. Call the Interaction instance's execute method to invoke the stored procedure INSERTCOFFEE. Just as we did when invoking the COUNTCOFFEE procedure, we pass two objects to the execute method: the InteractionSpec object with the correctly set properties for the INSERTCOFFEE stored procedure, and the IndexedRecord object representing an input Record. The execute method is not expected to return anything in this case.
  9. Close the connection to the database.

Writing a CCI Client

A client application that relies on a CCI resource adapter is very much like any other J2EE client that uses enterprise bean methods. Our CoffeeClient application uses the methods of the CoffeeEJB session bean to access the Coffee table in the underlying database. CoffeeClient invokes the Coffee.getCoffeeCount method to read the Coffee table records and invokes the Coffee.insertCoffee method to add records to the table.

CCI Tutorial

This tutorial shows how to deploy and test the sample CCI black box adapter with the code described in the preceding sections. This code has been packaged into a J2EE application EAR file named CoffeeApp.ear, which is located in the j2eetutorial/examples/ears directory. The source code is in j2eetutorial/examples/src/connector/cci. To compile the source code, go to the j2eetutorial/examples directory and type ant cci.

Deploying the Resource Adapter

  1. Use the deploytool utility to deploy the CCI black box resource adapter. Specify the name of the resource adapter's RAR file (cciblackbox-tx.rar), plus the name of the server (localhost).
       deploytool -deployConnector \	
       $J2EE_HOME/lib/connector/cciblackbox-tx.rar localhost
    Windows (Note that this command and all subsequent Windows commands must be entered on a single line.)
       deploytool -deployConnector	
       %J2EE_HOME%\lib\connector\cciblackbox-tx.rar localhost
  2. Next, add a connection factory for the deployed CCI adapter. The connection factory supplies a data source connection for the adapter. Use j2eeadmin to create the connection factory, specifying the adapter's JNDI name plus the server name. Here, we add a connection factory for our CCI adapter whose JNDI name is eis/CciBlackBoxTx on the server localhost.
       j2eeadmin -addConnectorFactory \	
       eis/CciBlackBoxTx cciblackbox-tx.rar
       j2eeadmin -addConnectorFactory 	
       eis/CciBlackBoxTx cciblackbox-tx.rar
  3. Verify that the resource adapter has been deployed.
       deploytool -listConnectors localhost
    The deploytool utility displays these lines:
       Installed connector(s):	
          Connector Name: cciblackbox-tx.rar	
       Installed connection factories:	
          Connection Factory JNDI name: eis/CciBlackBoxTx

Setting Up the Database

For Cloudscape, use the following procedure.

  1. Create the stored procedure.
    1. To compile the stored procedure, go to the j2eetutorial/examples directory and type ant procs. This command will put the Procs.class file in the j2eetutorial/examples/build/connector/procs directory.
    2. Locate the bin/ (UNIX) or bin\userconfig.bat (Windows) file in your J2EE SDK installation. Edit the file so that the J2EE_CLASSPATH variable points to the directory that contains the Procs.class file.
    3. Restart the Cloudscape server.
    4. Go to the j2eetutorial/examples directory and type ant create-procs-alias. This command creates aliases for the methods in Procs.class. Cloudscape uses method aliases to simulate stored procedures.
  2. To create the Coffee table, go to the j2eetutorial/examples directory and type ant create-coffee-table.

For Oracle, use the following procedure.

  1. Start the database server.
  2. Run the j2eetutorial/examples/sql/oracle.sql script, which creates both the stored procedures and the Coffee table.

Browsing the CoffeeApp Application

  1. In the GUI deploytool, open the j2eetutorial/examples/ears/CoffeeApp.ear file.
  2. Select the Resource Refs tab of the CoffeeBean component and note the following (Figure 17-3).
    • The Coded Name of CCIEIS corresponds to the following line in the source code:
         cf = (ConnectionFactory) ic.lookup("java:comp/env/CCIEIS");

Figure 17-3 Resource Refs Tab of the CoffeeApp Application

  1. Select the JNDI Names tab of CoffeeApp (Figure 17-4). Note that the CCIEIS value in the Reference Name field has been mapped to the eis/CciBlackBoxTx value in the JNDI Name field.

Figure 17-4 JNDI Tab of the CoffeeApp Application

Deploying and Running the CoffeeApp Application

  1. Deploy the application.
    1. In the GUI deploytool, select ToolsDeploy.
    2. In the Introduction dialog box, select Return Client Jar.
  2. In a terminal window, go to the j2eetutorial/examples/ears directory.
  3. Set the APPCPATH environment variable to the name of the stub client JAR file: CoffeeAppClient.jar.
  4. Run the client.
       runclient -client CoffeeApp.ear -name CoffeeClient 	
  5. At the login prompts, enter guest as the user name and guest123 as the password.
  6. The client should display the following lines:
       Coffee count = 0	
       Inserting 3 coffee entries...	
       Coffee count = 3