Date Created: Sat 20-Aug-2011

Related Document Categories:

Get my WebSphere Application Server course here >> http://www.themiddlewareshop.com/products/


How to create a stateful session bean using eclipse.

I did this article as I wanted to create an EJB using 2.1 specifications to test DXloclet configurations for different EJB containers in WebLogc, WebSphere an JBoss to understand the specific EJB descriptors and various container settings. As a JEE consultant I am often asked to solve customer issues with EJB's and on one particular occasion I needed to verify how to handle EJB stateful session bean timeouts.

We are going to create an EJB and package it in an EAR file. We will be using the EJB 2.1 spec, then we will change the code to be EJB 3.0 compliant.

I am using Eclipse 3.6 (Helios) for my Eclipse version


1. Create a new Eclipse workspace and EJB/EAR projects.

File-New-EJB Project



In the New EJB Project Page, Type CartEJB as the EJB project's name

Ensure that the EJB module version is set to 2.1

Check the EAR membership checkbox and type CartEJBEAR as the name of the EAR project. Eclipse will create this for you



Click the Modify button in the Configuration section and select you version of XDoclet as defined in the steps above. I have chosen to use EJBDoclet (XDoclet) 1.2.3



Click OK to return to the New EJB project wizard.

Click Next until you come to the Configure EJB module settings screen and uncheck the Create an EJB Client JAR module to hold the client interfaces and classes. We will be using a JSP as our client.



Click Finish to create the project.

One the project is created you will have an error




1. Setup XDoclet

To set up XDoc you need to download the appropriate version of XDoclet that you wish to use. In my mu case I have used XDoclet 1.2.3 which was downloaded from the following URL: http://xdoclet.sourceforge.net/xdoclet/install.html which takes you to Source Forge: http://sourceforge.net/projects/xdoclet/files/xdoclet/



One you have downloaded XDoclet to a location on your local workstation, you need to tell Eclipse where XDoclet is located. I decompressed XDoclet to d:\xdoclet-1.2.3 as seen below.



3. Updating your project to have the correct XDoclet runtime settings.

Click Project properties ie right-mouse click on the EJB Cart project and click properties. Navigate to the XDoclet section of the right-hand properties panel for the EJB Cart Project



Ensure that yo set the correct version to 1.2.3 or you will get a facet error.



Now we need to add a bean to the EJB project as there needs to be at least one bean.

Right-mouse click on the Cart EJB project and choose New-XDoclet Enterprise JavaBean




Select Session Bean, and click Next



Since I am using an Oracle Java tutorial as the basis of by JavaBean business logic, I am adding a new package called com.screv and a Class name for CartBean for by actual JavaBean.



Click Next.

On the Create an Enterprise JavaBean screen, I have selected Stateful as the State type. I am also leaving the Transaction type to be container. What this means is that this is a container managed bean for transactions.



Click Next, and then Finish.

One finished, the JavaBean is added to the CartEJB project and XDoclet is run the the internal Eclipse Ant task to generate all the required EJB interfaces. However as you can see below there is an error.

BUILD FAILED
D:\workspaces\sfsb\.metadata\.plugins\org.eclipse.jst.j2ee.ejb.annotations.xdoclet\tempAnt.xml:69: Unexpected error



Looking at the Markers tab of the bottom Eclipse panel, we can see a few errors





  • Build path specifies execution environment J2SE-1.4. There are no JREs installed in the workspace that are strictly compatible with this environment.System Library Problem
  • javax.ejb cannot be resolved to a type CartBean.java /CartEJB/ejbModule/com/screv line 25 Java Problem

OK, this is because we have JDK specified for the project which contains the EJB classes.

At this stage you can either download the appropriate JEE.

In my Example I have IBM Websphere installed locally, so I am going to do two things.

1. Add the IBM JDK that comes with WebSphere
2. Add specific WebSphere runtime libraries.

Note this process is similar for WebLogic and JBoss.

Go to Project Properties

1. Remove the Default J2SE 1.4 System Library and create and add a new WebSphere - IBM JDK library.



On the Java Build Path screen, click Add Library



Select JRE System Library form the Libraries types to add list.




Select Alternate JRE from the System Library group and click Installed JREs to add a new one.



Click Add..



In the Add JRE screen, choose Standard VM from the Installed JRE Type list.



In my example I have WAS8 installed, so I am using the Java supplied with WebSphere Application Server 8.

C:\Program Files (x86)\ibm\WebSphere\AppServer\java

I gave my new JRE the name of WebSphere 8 Java



Click After setting the JRE home

Select the newly added JRE as shown below




Click OK to return to the JRS System Library screen and ensure that the new WebSphere 8 Java system library is now added.



Click Finish

Now we need to add The WebSphere Runtimes to get the EJB classes (javax.ejb)

Add a User Library




Click Next to to go to the User Library scree



Click New






Click OK to add the User Library place holder

Click Add JARs to add the IBM WebSphere Application Server runtime jars



C:\Program Files (x86)\ibm\WebSphere\AppServer\runtimes



I choose to add only three of the run time classes



Click OK, then Finish

Then click OK

Clean the project and XDoclet will run and generate the ejb-jar.xml and appropriate classes

Congratulations, you have now built the basis of the Stateful Session Bean

What we will do not is add some business logic and a Web Application to test it.

Replace the automatic generated code for the CartBean

/**
*
*/
package com.screv;

import java.util.Vector;

import javax.ejb.CreateException;
import javax.ejb.SessionContext;

import com.screv.helpers.BookException;
import com.screv.helpers.IdVerifier;

/**
*
* <!-- begin-user-doc -->
* A generated session bean
* <!-- end-user-doc -->
* *
* <!-- begin-xdoclet-definition -->
* @ejb.bean name="Cart"
* description="An EJB named Cart"
* display-name="Cart"
* jndi-name="Cart"
* type="Stateful"
* transaction-type="Container"
*
* <!-- end-xdoclet-definition -->
* @generated
*/

public abstract class CartBean implements javax.ejb.SessionBean {

private static final long serialVersionUID = 1L;
String customerName;
String customerId;
Vector contents;

/**
*
* @ejb.create-method view-type="both"
*
*/
public void ejbCreate(String person) throws CreateException {

if (person == null) {
throw new CreateException("Null person not allowed.");
}
else {
customerName = person;
}

customerId = "0";
contents = new Vector();
}

/**
*
* @ejb.create-method view-type="both"
*
*/
public void ejbCreate(String person, String id)
throws CreateException {

if (person == null) {
throw new CreateException("Null person not allowed.");
}
else {
customerName = person;
}

IdVerifier idChecker = new IdVerifier();
if (idChecker.validate(id)) {
customerId = id;
}
else {
throw new CreateException("Invalid id: "+ id);
}

contents = new Vector();
}
/**
* Adds a book.
*
* @param title String "Book title"
*
* @ejb.interface-method
*/
public void addBook(String title) {
contents.addElement(title);
}

/**
* Removes a book.
*
* @param title String "Book title"
* @ejb.interface-method
*/
public void removeBook(String title) throws BookException {

boolean result = contents.removeElement(title);
if (result == false) {
throw new BookException(title + "not in cart.");
}
}
/**
* Returns books.
*
* @return contents Vector "Book title"
* @ejb.interface-method
*/
public Vector getContents() {
return contents;
}


public CartBean() {}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext sc) {}
}


public CartBean() {}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext sc) {}
}

When the EJB project is next re-built all the appropriate EJB interfaces will be re-built.

We can now export the EAR file and deploy to WebSphere.

What we need to do now is create a Client application that can be used to access the EJB. We will also need to generate the RMI stubs for the client application.

package com.screv.client;

import java.util.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

import com.screv.Cart;
import com.screv.CartHome;
import com.screv.helpers.BookException;

public class CartClientWAS {

public static void main(String[] args) {
Object obj = null;
try {
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial", "com.ibm.websphere.naming.WsnInitialContextFactory");
env.put("java.naming.provider.url", "corbaloc:iiop:localhost:2809");
try {
Context ctx = new InitialContext(env);
obj = ctx.lookup("cart");
}
catch (NamingException e) { // Error getting the home interface
e.printStackTrace();
}


CartHome home = (CartHome)PortableRemoteObject.narrow(obj, CartHome.class);

Cart shoppingCart = home.create("Duke DeEarl","123");

shoppingCart.addBook("The Martian Chronicles");
shoppingCart.addBook("2001 A Space Odyssey");
shoppingCart.addBook("The Left Hand of Darkness");

Vector bookList = new Vector();
bookList = shoppingCart.getContents();

Enumeration enumer = bookList.elements();
while (enumer.hasMoreElements()) {
String title = (String) enumer.nextElement();
System.out.println(title);
}

shoppingCart.removeBook("Alice in Wonderland");
shoppingCart.remove();

} catch (BookException ex) {
System.err.println("Caught a BookException: " + ex.getMessage());
} catch (Exception ex) {
System.err.println("Caught an unexpected exception!");
ex.printStackTrace();
}
}
}

You will need to reference the WebSphere 8 Java (JRE)and the user library WAS8_Runtimes user library we created earlier.



The Cart Client also has all the same classes as the CartEJB, this is so the client application can reference appropriate libraries. It is recommended that the Client Cart project should reference a utility JAR file containing these classes.





This example uses the default WAS BOOTSTRAP_ADDRESS port of 2809.


References
http://www.comptechdoc.org/docs/kanti/ejb/statefuldeployment1.html
http://www.myeclipseide.com/documentation/quickstarts/firstejb/
http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Session2.html#62902
http://rmi-eclipse.sourceforge.net/net.shotwave.eclipse.rmic.site/site.xml

Get my WebSphere Application Server course here >> http://www.themiddlewareshop.com/products/

Steve Robinson - IBM Champion 2013

About Me

Steve Robinson has been working in IT for over 20 years and has provided solutions for many leading brands around the world. Steve specialises in JEE, DevOps and Thought Leadership.

In January 2013, I was awarded the prestigous 'IBM Champion' accolade.


  • Linked In
  • Twitter
  • About Me
  • Contact Me

Read my books?

IBM WebSphere Application Server 8.0 Administration Guide

IBM WebSphere Application Server 8.0 Administration Guide

WebSphere Application Server 7.0 Administration Guide

WebSphere Application Server 7.0 Administration Guide

Courses

  • WebSphere Courses

Articles

WebSphere Categories

Other Categories