iPlanet Application Server Third Party Integration Tools

Version 1.1

Container Managed Persistence Entity Enterprise Java Bean Tutorial

Integration with VisualCafé 4.1


Creating an iPlanet Web Application and a CMP Entity Bean

Before You Begin
Part 1: Creating a Container Managed Persistence Entity Bean
Part 2: Creating a Web Application that Calls the CMP EJB
Part 3: Creating a Web Application with Database Access


Before You Begin

  1. Follow the directions in the Installation Instructions to install the integration tool.
  2. If you plan on performing remote debugging, follow the directions in the Installation Instructions to install the remote debugging services on the target system.
  3. Install a database client (Oracle 8.1.6)
  4. Create a table named PRODUCT using the following script:

    	create table PRODUCT
    	(
    	description varchar(255);
    	price double precision not null,
    	productid varchar(255) constraint
    	pk_product Primary Key
    	);
    	

  5. To complete the tutorial, you must know:
    • The iPlanet Application Server Administrator user name and password.
    • The iPlanet Application Server Administrator Port Number for the iPlanet Application Server installed on your machine (the default admin port number is 10817).
    • The Oracle user name and password.
  6. Make sure <OracleHome>\jdbc\lib\classes111.zip is in the CLASSPATH in your <VisualCaféEE>\bin\sc.ini file.

This tutorial assumes some familiarity with the iPlanet Application Server and VisualCafé.


Part 1: Creating a Container Managed Persistence Entity Bean

  1. Launch VisualCafé Enterprise Edition.
  2. From the File menu, select New Project.

    The New Project window appears.

  3. Select the Enterprise Bean icon and select OK.

    The Create Enterprise Bean wizard appears to help you create the EJB component.

  4. Review the EJB Wizard Introduction window and select Next.

  5. In the Select Name window, enter the following data in each field:

    Field Data to enter
    Basename: Cmp
    Package: CmpPack
    Description: Whatever comment you wish to enter
    Location: Accept the default setting
    Enterprise Bean project name: Accept the default setting
    client project name: Accept the default setting

  6. Select Next.
  7. In the Choose Enterprise Bean type window, make sure Entity - container managed persistence is selected and select Next.

  8. Select Next to proceed through the Add create methods, Add finder methods, Add business methods, and Add environment properties windows.
  9. In the Map database fileds window, select Persistence Builder.

  10. In the Persistence Builder window Source field, select JDBC.
  11. In the Database field, enter jdbc:oracle:thin:@<hostname>:<portnumber>:<SID>.
  12. In the Driver field enter oracle.jdbc.driver.OracleDriver.
  13. Enter the username and password.
  14. Select Connect to connect to your database.

    Once you are connected, you should see a "connect" message in the Status window and the Tables should display a list of the available tables in your database.

  15. In the Filter field, enter the letter P to display the tables starting with the letter P.
  16. Select the Product table you created earlier.
  17. Select Load to load the table into the Persistence Builder Select Table dialog.

  18. Select each item in the Product table Select field.

    Notice that when the PRODUCTID is select the Key button is checked indicating that this field is set as the key.

  19. Select Close to exit the Persistence Builder window.
  20. From the Map database fields window, select the Add All button to add all the table fields.
  21. Click to highlight the description Name field.

    Notice that the Get, Set, and In Key checkboxes become active.

  22. Select Get and Set.

  23. Click to highlight the price Name field.
  24. Doubleclick on the object Type field to display a scroll list of types.
  25. Select double Type.

  26. Select the Get and Set checkboxes once more.
  27. Click to highlight the productid field.

    Notice that the In Key checkbox becomes active and is checked.

  28. Select the Get and Set checkboxes.
  29. Select Next.

  30. Review the selections you have made and select Finish.

    After a few moments, the Create Enterprise Bean wizard creates the following files:

    Interface Filename
    Bean Home Interface CmpHome
    Bean Remote Interface Cmp
    Entity Bean CmpEJB

  31. Open the CmpHome.java file.
  32. After the import java.rmi.RemoteException; method, add the following:

    import javax.ejb.CreateException;
    

  33. After the throws FinderException, RemoteException; method, add the following:

    public Cmp create(String description, double price, String productid)
    	throws RemoteException, CreateException;
    

  34. Save the CmpHome.java file.
  35. Open the CmpEJB.java file.
  36. After the import javax.ejb.EntityContext; method, add the following:

    import javax.ejb.FinderException;
    

  37. Scroll down to the ejbCreate method and replace return null; with return productid;:

    public String ejbCreate(String description, double price, String productid) {
    	this.description = description;
    	this.price = price;
    	this.productid = productid;
    	return productid;
    

  38. Add the following method after the ejbRemove() method at the end of the file.

    public string ejbFindByPrimaryKey (String key)
    	throws FinderException {
    	return key;
    }
    

  39. Save the CmpEJB.java file.
  40. Make sure the iPlanet Application server is set as the deployment target by selecting Options from the Projects menu.
  41. Select the EJB tab.

  42. Select the iPlanet Application Server 6.0 from the Deployment Target field.
  43. Select the Manage Deployment Target.
  44. Select New.

    You can define servers by their name or IP address. Your local server is defined by its IP address. If you don't have a remote server you would like to work with, use localhost.

  45. In the Enter New Server window, enter the following data in each field:

    Field Data to enter
    Hostname: The name of the server you want to use
    Port: The admin port of your application server
    Username: The iPlanet Application Server administrator username
    Password: The administrator password
    Confirm Password: Reenter the administrator password
    URL: The base URL for your server. The default is http://hostname/NASApp
    Kind: IAS_AND_WEB

  46. Select OK.
  47. Make sure your new server is selected and select OK to commit your changes to the iPlanet Application Server deployment target window.

  48. Select the Data Sources tab.
  49. Select New to define a new datasource, or select a predefined datasource.

  50. Select OK to define the datasource.

  51. Make sure the datasource you just defined is selected in the Data Sources field by selecting the > button.

    The defined datasource should now appear in the Referenced Datasources panel.

  52. Enter your username and password and Select OK.
  53. Select OK to commit your changes to the Environment Options.

    The new server is now registered with VisualCafé and can be used by all projects. The same server can be used for both Web Applications and EJBs. The selected server is the default server used in new projects.

  54. Select the CmpEnterpriseBean to activate the window.

  55. From the Project menu, select Configure Deployment Descriptors.

  56. Select the Environment tab, then select the Resource tab.

  57. Select New and change the datasource name to cdx (your datasource).
  58. Select OK.
  59. From the Project menu, select Start EJB server.

    In the Messages window, Build tab, a message displays indicating the application server is running.

  60. Select the CmpEnterpriseBean to activate the window.
  61. From the Project menu, select Deploy.

    The Deliver Enterprise Bean to EJB Server progress panel displays, and the following messages appear in the Messages window:

    Deploying JAR.... Delivery complete.
    Cleaning up...Completed.
    

Congratulations, you have successfully created, edited, and deployed a CMP EnterpriseBean. Proceed to Part 2 to create a test servlet to call the CMP bean.


Part 2: Creating a Web Application that Calls the CMP EJB

  1. From the File menu, select New Project.

    The New Project window appears.

  2. Select the iPlanet Web Application icon and select OK.

  3. Enter Caller as the VEP (project) name and select Save.

    The project name appears as untitled. This is a known bug.

  4. Update the project name by closing the project and reopening it, or by selecting Save from the File menu.

    You are now ready to create a servlet in the project.

  5. From the Insert menu, select Servlet.

    The Servlet wizard launches.

  6. Read the description of what the Servlet wizard does and select Next.
  7. In the Servlet window, enter the following data in each field:

    Field Data to Enter
    Name: CallerServlet
    Package: Caller

  8. Select simple HTTP servlets with the default methods.
  9. Select Next.
  10. Select HTTP-specific, then select Next.
  11. Select Yes: Implementation should be thread-safe.
  12. Select Next.
  13. Select doPost() method
  14. Select Finish.
  15. Modify your CallerServlet.java code as follows:

    package Caller;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.naming.*;
    import javax.ejb.*;
    public class CallerServlet extends HttpServlet
    {
    	public void doGet(HttpServletRequest req, HttpServletResponse resp)
    	throws ServletException, IOException
    	{
    		resp.setContentType("text/html");
    		PrintWriter out = new PrintWriter(resp.getOutputStream());
    		try
    		{
    			// to do: code goes here.
    			out.println("<HTML>");
    			out.println("<HEAD><TITLE>callerservlet Output</TITLE></HEAD>");
    			out.println("<BODY>");
                doPost(req, resp);
    			// to do: your HTML goes here.
    			out.println("</BODY>");
    			out.println("</HTML>");
    		}
    		finally
    		{
    			out.flush();
    		}
    	}
    	public void doPost(HttpServletRequest req, HttpServletResponse resp)
    	throws ServletException, IOException
    	{
    		resp.setContentType("text/html");
    		PrintWriter out = new PrintWriter(resp.getOutputStream());
    		try
    		{
    			// to do: code goes here.
    			out.println("<HTML>");
    			out.println("<HEAD><TITLE>callerservlet Output</TITLE></HEAD>");
    			out.println("<BODY>");
                String JNDI_NAME = "java:comp/env/Cmp";
                Object beanObject = null;
                try
                {
                    Context initContext = new InitialContext();
                    beanObject = initContext.lookup(JNDI_NAME);
                    CmpPack.CmpHome home = (CmpPack.CmpHome)beanObject;
    		CmpPack.Cmp duke = (CmpPack.Cmp)home.create( "Ceramics",11.11, "123");
    		out.println("<B><P> The Output : </B></P>");
                    out.println("<BR><B>" + duke.getDescription() + ": " + duke.getPrice()+"</B></BR>");
                    out.println("<B>" + "Setting the price to 55.55" + "</B>");
                    duke.setPrice(55.55);
                    out.println("<BR><B>" + duke.getDescription() + ":" + duke.getPrice());
                    duke = (CmpPack.Cmp)home.create( "Wooden Duck", 13.00,"11");
                    duke = (CmpPack.Cmp)home.create( "Ivory Cat", 19.00,"22");
                    duke = (CmpPack.Cmp)home.create( "Ivory Cat", 33.00,"33");
                    duke = (CmpPack.Cmp)home.create( "Chrome Fish", 22.00,"44");
                    CmpPack.Cmp earl = home.findByPrimaryKey("11");
                    System.out.println("EARL: "+ earl.toString()+"\n");
                    out.println("<BR><B>" + earl.getDescription() + ":"+ earl.getPrice() + "</B></BR>" );
                }catch(Exception e)
                {
                    e.printStackTrace();
                }
    	// to do: your HTML goes here.
    	    out.println("</BODY>");
    	    out.println("</HTML>");
    	    }
    	   finally
    	   {
    	       out.flush();
    	   }
        }
    }
    

    You are now ready to build your servlet.

  16. From the Project menu, select Options.
  17. Select the Directories tab.
  18. Select the New button, then select the File button.
  19. Add the directory which has the EJB classes and add as the first entry.

    For example: d:\VisualCafeEE\Projects\Cmp

  20. From the Project menu, select Configure iPlanet Web Application.
  21. Select the Refs tab.
  22. Select Add in the References to EJBs defined elsewhere section of the window to add the CMP.

    Field Data to Enter
    Reference Cmp
    Bean Type Entity
    Linked to Bean Cmp
    Bean Home Interface CmpHome
    Bean Remote Interface Cmp
    JNDI Name ejb/CmpEnterpriseBean/Cmp

  23. Select OK.
  24. From the Project menu, select Execute in iPlanet Server.
  25. Save the file.

Part 3: Creating a Web Application with Database Access

To create a web application with a data source connection, you must register the datasource with the application.
  1. Open a project that includes a servlet (such as the project you created in Part 2).
  2. From the Tools menu, select Environment Options.
  3. Select the UML/EJB tab.
  4. Select iPlanet Application Server 6.0 as the Deployment Target.
  5. Select the Manage Deployment Target.

    The Manage Deployment Target window appears.

  6. Select the Data Sources tab.
  7. Select New.
  8. Define the data source as follows:

    Field Data to Enter
    Database Name: The name of your database
    Datasource: Identifier you want to use to refer to the data source.
    Database URL: The JDBC URL for the third party driver. This field is not required for the iPlanet Application Server database access engine.
    Username: The username for the database.
    Password: The password for the database username specified.
    Confirm Password: Repeat the password previously specified.
    Driver: The name of the third party driver specified above in the Database URL. In this example ORACLE_OCI is used.

    The iPlanet Application Server provides built-in JDBC drivers, as well as providing support for third party JDBC drivers.

  9. Select OK.

    Congratulations, you have successfully globally defined the data source.

    To verify your global data source settings, select the Deployment Target Data Source panel. The data source should appear in the Referenced Datasources list.

    When you add a data source to a project and deploy that project, the associated data source is globally registered in the iPlanet Application Server. All applications subsequently deployed to that instance of the application server can also access that data source.

    You are now ready to configure the servlet for database access.

  10. Select the desired datasource from the Referenced Datasources list.
  11. Select the Servers tab.
  12. Select the Server you wish to deploy to.
  13. Select OK.
  14. Replace your servlet code with the following code that performs the JNDI lookup of your datasource:

    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import javax.naming.NamingException;
    import javax.sql.*;
    import javax.servlet.*;
    import javax.servlet.jsp.JspException;
    import javax.servlet.http.*;
    public class webservlet extends HttpServlet
    {
    	static private Connection con;
    	static private String dbName = "java:comp/env/cdx";
    	public void doGet(HttpServletRequest req, HttpServletResponse resp)
    		throws ServletException, IOException
            {
    		resp.setContentType("text/html");
    		PrintWriter out = new PrintWriter(resp.getOutputStream());
    // to do: code goes here.
    	    try {
    		makeConnection();
    		insertRow("Test Product", 10.0, "B");
    		}
    		catch(Exception e){
    		e.printStackTrace();
    		}
    		out.println("");
    out.println("<HEAD><TITLE>webservletOutput</TITLE></HEAD>");
    		out.println("<BODY>");
    // to do: your HTML goes here.
    		out.println("</BODY>");
    		out.println("</HTML>");
    		out.close();
            }
    private void makeConnection() 
    		throws NamingException, SQLException 
    		{InitialContext ic = new InitialContext();
    			DataSource ds = (DataSource) ic.lookup(dbName);
    				con =  ds.getConnection();
    		}
    private void insertRow (String desc, double price, String id ) 
    		throws SQLException 
            	{
    String insertStatement ="insert into product values ( ? , ? , ?)";
    			PreparedStatement prepStmt = 
    				con.prepareStatement(insertStatement);
    			prepStmt.setString(1, desc);
    			prepStmt.setDouble(2, price);
    			prepStmt.setString(3, id);
    			prepStmt.executeUpdate();
    			prepStmt.close();
    			}
    private void deleteRow(String id) throws SQLException {
    		String deleteStatement ="delete from product where id = ? ";
    			PreparedStatement prepStmt =
    			con.prepareStatement(deleteStatement);
    			prepStmt.setString(1, id);
    			prepStmt.executeUpdate();
    			prepStmt.close();
          } }
    

If you are calling an EJB to another EJB you must register both EJBs so each can call the other. With the iPlanet Application Server Integration tool this is performed by entering the name of the EJB you wish to register into the references list of the bean you want to communicate with.

To register an EJB:

  1. Select the Objects tab from the Project window, and select the CallerEJB.
  2. From the Project menu, select Configure Deployment Descriptor.
  3. Select the Environment tab, then select the EJB Rerefences tab.
  4. Select New to register the EJB.

  5. Replace the Name with the name of the EJB you want to register.

    In this example, the name of the EJB to register is TestBase.

  6. Replace the Type with Session.
  7. In the Home Interface field, select testpkg.TestBase from the drop-down menu.
  8. In the Remote Interface field, select testpkg.TestBase from the drop-down menu.
  9. Select the Tart Options tab, then the EJB Reference tab.
  10. In the EJB Reference Name field, enter TestBase.
  11. In the JNDI Name field, enter ejb/TestBaseEnterpriseBean/TestBase
  12. Select OK.

    Congratulations, you have just registered your EJB.



Copyright © 2000, Sun Microsystems Inc. All rights reserved.
Copyright © 2000, Netscape Communications Corporation. All rights reserved.

Sun, Sun Microsystems, the Sun logo, Java, iPlanet, and the Sun, Java, and iPlanet-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.

Netscape and the Netscape N logo are registered trademarks of Netscape Communications Corporation in the U.S. and other countries. Other Netscape logos, product names, and service names are also trademarks of Netscape Communications Corporation, which may be registered to other countries.