Pramati Technologies

Sample EJB 2.0 Application

New innovations in Studio 3.0 have made it surprisingly easier for power users to write the new EJB 2.0 family of beans, which has made writing and assembling enterprise beans more complex while modelling real-world business functions more closely.

A new Container Managed Persistence (CMP) model is at the core of EJB 2.0, and hinges on Container Managed Relationships. This sample routine takes you on a straight-line path to construct two entity beans, give them a relationship, and deploy them on the in-built Pramati Server. A simple JSP acts as the client that looks up the beans.

The sample can be developed and run using other development servers. For instructions, see the relevant chapters on working with other servers in this guide.

The sample is a small banking application that takes a "Customer ID" as input and generates the detailed account information for that customer.

Lets create our first CMP 2.0 application, aptly named PiggyBank.

In the instructions that follow, we assume the user is working on Windows and that Studio is installed in the directory c:\pramati_studio on Windows.

Create the Desk

The Desk is necessary to begin organizing application sources. Create a Desk from the main menu by selecting Desk > New to bring up a New Desk.

  1. Enter name of the Desk as PiggyBank.
  2. Select location as Studio installation directory, c:\pramati_studio.
  3. Every Desk maps to an underlying directory structure in the file system. Creating a new Desk creates a corresponding directory with the same name in the file system.
  4. The template for the Desk is selected as Default. Keep this.
  5. Every Desk is based on a template provided by Studio. The default template for the Desk contains the following folders - EJB 2.0 Module, Web Module, JAR, WAR, RAR and EAR.
  6. Choosing the template, in this case Default, automatically creates the following source roots for EJB and Web Module: c:\pramati_studio\PiggyBank\PiggyBankEJB and c:\pramati_studio\PiggyBank\PiggyBankWeb
  7. The template also creates c:\pramati_studio\PiggyBank\classes as the directory where compiled classes will be stored.
  8. Click OK.

The Desk is created and displayed in the Explore Panel. See the chapter, "Overview of Pramati Studio", for a quick tour of Studio UI.

Prepare a Data Resource

Adding JDBC Drivers

To add JDBC Drivers in Studio, click on Tools > Configure JDBC Drivers from the main menu. This brings up the Configure Drivers dialog, where new drivers can be added, modified and deleted. Cloudscape driver is configured in Studio, by default.

Follow the given instructions to add an Oracle driver in Studio:

Follow a similar procedure to configure other drivers.

Create the tables on a target database

PiggyBank application requires customer and account tables. Studio ships with database script files that create these tables on Oracle, IBM Informix and MS SQL Server:

To use another database, you may study these scripts and modify or write a suitable script. To execute the scripts and prepare the tables for the application, choose your database and follow these steps:

Oracle

  1. Open SQL*PLUS editor.
  2. Enter the username and password for accessing the database. (Oracle provides scott and tiger as an universal username-password for evaluators of its database product.)
  3. Run the following command from the SQL prompt:
    @c:/pramati_studio/samples/oracle_ejb.sql

IBM Informix

  1. Start the SQL Editor.
  2. Connect to the database and run
    @c:\pramati_studio\samples\informix_ejb.sql

MS SQL Server

  1. Create database protondemo using SQL Server Enterprise Manager.
  2. Open Query Analyser on SQL Server 7.0 or iSQL on SQL Server 6.5.
  3. Select protondemo as database and run
    @c:\pramati_studio\samples\mssql_ejb.sql
  4. Create an ODBC32 data source, protondemo, that connects to protondemo database.

MS Access Server

  1. Create a database protondemo.mdb with protonaccount and protonledger tables.
  2. Create an ODBC32 data source called protondemo and map it to protondemo.mdb.

Define data resource on the server

Entity beans require data resources defined on the application server where they are being deployed. Resources can be defined on the in-built server with Studio, for entity beans to obtain connections.

Resources are defined in Studio using the Resource Tool and are always local to the Desk.

To start Resource Tool, select Tools > Resources. Define a resource connection under the Data Source tab as follows:

Ensure that Cloudscape is running when the resource is to be added to the database - Informix Cloudscape. To do this on a Windows platform, run cloudscape.bat available under <install_dir>. Run cloudscape.sh available under <install_dir> on a Unix platform.

Note: A sample Cloudscape database with pre-defined tables is shipped with Studio, on which the user can test his application.

Follow the given steps if the database is Informix Cloudscape:

  1. Enter custres as the JNDI Name of the resource
  2. Select COM.cloudscape.core.RmiJdbcDriver as the Driver.
  3. Select the URL of the database as [Non-XA] cloudscape jdbc:rmi:jdbc:cloudscape:samples/sample_db from the list in the combo box.
  4. Select Container as the authorization mode.
  5. Click on Test to verify the resource connection. If the connection is valid, click on Add to add the resource on the server.

If the database used is Oracle, follow the given steps.

  1. Create the required tables using the scripts provided.
  2. Enter custres as the JNDI Name of the resource.
  3. Select [Non-XA] Oracle oracle.jdbc.driver.OracleDriver as the Driver.
  4. Select the correct URL of the database from the list in the combo box. For example, jdbc:oracle:thin:@127.0.0.1:1521:ORCL.
  5. Select Container as the authorization mode.
  6. The username and password is user-defined and is required to access the database tables. Oracle database ships with a default username/password, scott/tiger.
  7. Click on Test to verify the resource connection. If the connection is valid, click on Add to add the resource on the server.

Clicking directly on Add will test and, if successful, add the data resource to the server. If you are modifying a resource, click on Modify after making the changes.

Generate Account Bean with CMP 2.0

To create a CMP 2.0 bean, first start the Bean Wizard from the main menu by selecting Tools > Bean Wizard.

Select the Bean Type

  1. Select PiggyBankEJB as the module.
  2. Select Entity Container Managed 2.0 as the bean type.
  3. The option Use Database is checked by default. Keep this. This bean is required to use the sample database to build relationship with another bean.
  4. Enter com.sample.cmr.Account as the bean class name. The name should be fully qualified. This automatically names the EJB as Account with JNDI name as Account_PiggyBankEJB_PiggyBank
  5. Leave the option Expert mode unchecked, and click Next.

Expert mode takes user on an exhaustive twelve-step path to writing a customized bean. Quick mode takes the user on a simpler four-step path to creating a bean with standard interfaces, and does not include creating ejbHome, ejbSelect, and the business method skeletons.It creates interfaces with default values in the Quick mode. It also does not include steps where the methods to be published in Home, Local Home, Remote and Local interfaces are added.

Create Container Managed Fields

Container Managed Fields of the entity bean may be created using an existing table in the database as follows:

  1. Select custres as the name of the resource.
  2. Enter the Table Filter as ACC* and click on Get. This filters in all tables starting with letters ACC and displays them in the Tables field. Note that the filter is case sensitive.
  3. Select Account as the table from under the Tables field. This displays the table details such as field name, type of field, primary key and primary key defined in the bean.
  4. Uncheck the field, CMP Fields for Customerid.
  5. Click Next.
  6. The next panel that comes up is Define Container Managed Relations. As no self relationships are to be defined, click Next.

Define Create Methods

This panel assists you in generating ejbCreate methods for the bean.

  1. Select all rows from the Choose CMFs field and click on the > icon. This moves all the fields to the Selected CMFs field.
  2. Clicking on + generates an ejbCreate method with CMF fields as the parameters.
  3. Click Next.

Define Finder Methods

Finder methods are not required for the Account bean. Click Finish to proceed.

Components generated

The wizard creates the bean Account, the bean class file, its remote and local interfaces. It stores all these files under the EJB Module, PiggyBankEJB on the Desk, PiggyBank.

Generate Customer Bean with CMR

The second bean to be created for the application is Customer. It has a container-managed relationship with Account bean that was just created.

You can create a new bean under a module by simply right clicking on the module name on the Desk and choosing New File.

Right click on the EJB Module PiggyBankEJB and select New File. Select EJB and click OK. This starts the now familiar Bean Wizard.

Select the Bean Type

The Module is already selected as PiggyBankEJB.

  1. Select Entity Container Managed 2.0 as the Bean Type.
  2. The option Use Database is checked by default. Keep this.
  3. Enter com.sample.cmr.Customer as the name of the bean class. This name should always be fully qualified.
  4. Entering the Bean Class Name automatically fills in the EJB Name as Customer, with JNDI Name as Customer_PiggyBankEJB_PiggyBank
  5. Leave the option Expert Mode unchecked.
  6. Click Next.

Create Container Managed Fields

  1. Select custres as the Resource Name.
  2. Select Table Filter as CUST* and click Get. This filters in all tables starting with CUST and displays them in the Tables field.
  3. Select CUSTOMER table.
  4. Click Next.

Create Container Managed Relationships

The Container Managed Relationship panel is used for creating relationships among beans. In this sample, Account and Customer bean are related as follows:

  1. Under Role 1, enter accountcmr as the CMR field name.
  2. Select 1-1 as the Relation. This means Customer has a unidirectional relationship with Account. The multiplicity of this relationship is one to one.
  3. Check option Cascade Delete. This automatically checks Role 2.

Cascade Delete implies deleting Customer will delete Account too.

  1. Under Role 2, select Account as the EJB Name.
  2. Click on Add to create the relationship between Account and Customer.

Add the JOIN Condition

Now the relationship is added, add the Join condition to it as follows:

  1. Click on the icon, in the Join field to open the Join Condition dialog box.
  2. On the left, select CUSTOMER table and CUSTOMERID field.
  3. On the right, select ACCOUNT table and CUSTOMERID field.
  4. Click Add to add the Join condition to the relationship.
  5. Click OK to return to the Container Managed Relationship screen.
  6. Click Next.

Define Create Methods

This panel assists you in generating ejbCreate methods for the bean.

  1. Select all rows from the Choose CMFs field and click on the > icon. This moves all the fields to the Selected CMFs field.
  2. Clicking on + generates an ejbCreate method with CMF fields as the parameters.
  3. Click Next.

Finder Methods

Since no finder methods are required in Customer bean, click Finish.

What is generated

The wizard generates the code for Customer bean and stores it under the EJB Module, PiggyBankEJB on the Desk, PiggyBank.

Compile the beans

When the beans and their interfaces are generated, they are compiled automatically. However, to force compile Account and Customer beans, right click on the EJB Module PiggyBankEJB and select Clean Build.

Write the JSP

JSP technology enables the generation of dynamic content for a Web client. The sample JSP looks up Account and Customer beans, and displays customer details given an account ID. JSP is created in Studio through standard templates.

  1. Right click on Web Module on the Desk and choose New File.
  2. Choose file type as JSP and click OK.

The JSP template panel requires the following information:

  1. Enter the filename as /index.jsp. The prefix / ensures the JSP is created under the context root of the application.
  2. The PiggyBankWeb is selected by default as the Web Module.
  3. Choose LookupJsp as the template. The JSP template includes a standard skeleton for looking up beans.
  4. Click OK. This creates a JSP Page under the Web Module.

Modify the JSP code to look up the beans

The JSP skeleton that is generated has standard place holders for business logic code. For the JSP to look up the bean and display details, the skeleton is modified as shown below:

Modification 1

Replace the line

<%@  
page import="javax.ejb.*,javax.nam-
ing.*,java.rmi.*,java.util.*" 
%> 

with the following code

<%@  
page import="javax.ejb.*,javax.naming.*,java.rmi.*, 
java.util.*,com.sample.cmr.*" 
%> 

Modification 2

Enter the following line of code

<% out.println("CMR Sample Demonstration");  

before the line

InitialContext ic = null; 

Modification 3

Replace the section

// replace the DemoBean with the actual bean name 
// DemoHome demoHome = 
// (DemoHome)ic.lookup("java:comp/env/ejb/DemoBean"); 
// Demo demo = (Demo)demoHome.create(); 

with the following lines

CustomerLocalHome custlocalHome = (CustomerLocalHome)ic.lookup("java:comp/env/ejb/CustomerLocal");

String customerId = request.getParameter("customerid");

if(customerId!=null)

{

CustomerLocal custlocal = CustomerLocal)custlocalHome.findByPrimaryKey(customerId);

AccountLocal acclocal = AccountLocal)custlocal.getAccountcmr();

Modification 4

Add the following lines of code in the JSP page immediately after the above section. These lines are executed after the look up succeeds.

%>  
<h2><%  
out.println("CMR Sample Demonstration");  
if(!lookupFailed){  
%><table border=0 cellspacing=5>  
<tr><td><%out.println("Customer ID : " );%></td><td><% 
out.println(custlocal.getCustomerid());%></td></tr>  
<tr><td><%out.println("Customer Name : "); %></td><td><% 
out.println(custlocal.getName());%></td></tr>  
<tr><td><%out.println("Account No : " );%></td><td><% 
out.println(acclocal.getAccountno());%></td></tr>  
<tr><td><%out.println("Account Balance : "); %></
td><td><% out.println(acclocal.getBalance());%></td></tr>  
</table>  
<%} 
} 

Since the above lines should be included in the try block, ensure they are followed by the closing parenthesis of the try statement.

Modification 5

Replace the section

<FORM METHOD='POST'> 
<INPUT TYPE='SUBMIT' NAME='Submit' VALUE='Submit'> 
</FORM>  

with the lines

<FORM METHOD="GET" > 
<h3>Enter Customer ID</h3> 
<INPUT TYPE="TEXT" NAME="customerid" SIZE="25"> 
<INPUT TYPE="SUBMIT" VALUE="SUBMIT"> 
<INPUT TYPE="HIDDEN" NAME="first" VALUE ="YES"> 
</FORM> 

Modify the user classpath

For the JSP file to look up the bean, the /classes directory should be added to the user classpath. Do this as follows:

  1. Right click on PiggyBankWeb and select Properties.
  2. Choose the Build tab in Properties.
  3. Click on + to start a file browser. Select directories along the following classpath: c:/pramati_studio/PiggyBank/classes/PiggyBankEJB
  4. Click OK to add the classpath to the user classpath field in Properties.
  5. Click OK.

Compile the JSP

Compile the JSP by right clicking on it on the Desk and selecting Compile. Compiling checks the JSP for syntactical errors.

Deploy the Application

To run the application, both EJB and Web Modules have to be deployed.

Deploy EJB Module

This is as easy as right clicking on PiggyBankEJB on the Desk and selecting Deploy. This directly deploys the EJB Module on the server configured as the development server. By default, this is in-built Pramati Server.

Add EJB Reference to the Web Module

  1. Right click on PiggyBankWeb on the Desk and select web.xml to start editing properties of the Web Module.
  2. In the Web Module properties tree, select the References node.
  3. Under EJB References tab, add a reference to PiggyBankBean with ejb/CustomerLocal as the name.
  4. Select Entity as the bean type.
  5. Select the Local Reference tab.
  6. Select com.sample.CustomerLocalHome as the Local Home Class name. This automatically fills com.sample.CustomerLocal as the Local Class name with JNDI name as Customer_PiggyBankEJB_PiggyBank.
  7. Click on Add to add the bean reference to the Web Module.

Deploy Web Module

Right clicking on PiggyBankWeb on the Desk and selecting Deploy brings up the Deploy tool. Follow the given steps before deploying the Web Module.

  1. Click on the Green arrow on the bottom right corner of the panel.
  2. In the EJb Ref panel that comes up, select the Link Name as Customer_PiggyBankEJB_PiggyBank. The module is now ready to be deployed.
  3. Click on Archive > Deploy from the Deploy tool menu. This deploys the Web Module.
  4. Click Exit.

Once both modules have been deployed, your first CMP 2.0 application PiggyBank is ready to be accessed by the JSP client.

Run the JSP

To run the JSP, right click on it on the Desk and select Run. This starts the browser that is configured for the IDE and runs the JSP in it.

Alternatively, run the JSP from a browser by keying in the following URL:

http://127.0.0.1:8181/PiggyBankWeb/index.jsp  
Note that, in the URL, the Web Module PiggyBankWeb is the context 
root of the application. 

Access the Application

The application prompts the user for the Customer ID. On entering the ID (example: 100), the application displays the related details from the Account and Customer tables in the database.


Pramati Technologies  © Copyright   TOCPREVNEXTINDEX