Enterprise JavaBeans
Peter Komisar © Conestoga College  version 1.0  Fall / 2008

Reference:  Third Draft Document for Review, Sept. 17,2007, SG24-7501-00
'Rational Application Developer V7 Programming Guide'. Ueli Wahli et.al.,
IBM, 'EJB 3.0 in a Nutshell An overview and critical analysis of the latest
EJB specification, Anil Sharma, JavaWorld.com, 08/09/04, The JNDI
Tutorial, http://java.sun.com/products/jndi/tutorial/index.html,
Abridged Version of 'EJB Fundamentals' Richard Monson-Haefel  
reference:http://developer.java.sun.com/developer/onlineTraining/EJBIntro
The J2EE™ 1.4 Tutorial For Sun Java System Application Server Platform
Edition 8.2, Eric Armstrong et.al



Overview

Enterprise JavaBeans are now in their third rendition in
JavaBeans 3.0.
Introduced in late 1999, the EJB technology
has gained momentum primarily because EJBs simplify
developing robust business components.

Of course the view that "EJB's simplify developing robust
business components' is forwarded by zealous supporters
at Sun and IBM.  Consider the following quotes.

"The EJB architecture is probably the only J2EE component
that has failed so miserably in delivering J2EE's promise of
increased developer productivity thorough ease of development.

EJB 3.0 makes another attempt at delivering that promise by
reducing EJB's complexity for developers. EJB 3.0 decreases
the number of programming artifacts for developers to provide,
eliminates or minimizes callback methods required to be
implemented, and reduces the complexity of the entity bean
programming model and O/R mapping model."
                                                          - Anil Sharma, JavaWorld.com

So the world of EJBs has not been a bed of roses!
Still developers all over the world have doggedly pursued
improving both the Bean Development Model and the
containers that are available to run them.


EJB Roots in CORBA and RMI

EJBs are based on Java's RMI API. It is more complex
than regular RMI as it adds a layer of isolation to the
remote components.

Just as RMI and CORBA have come together in 'RMI over
IIOP', Enterprise JavaBeans make use of the CORBA
architecture. This is evident in some of the components
used in the Java code as well as in the error reports which
may be generated showing Orb related exceptions.



Following are listed some of the strengths of EJBs.

EJB Strengths

EJBs provide 'method-level security', where users or groups
can be granted or denied execution rights to any bean or
method.

EJBs provide distribution capabilities to your application
allowing for scaling at the enterprise level. System modules
can be deployed to many different physical machines and
many separate OS processes optimizing performance,
scalability, and availability.

Persistence is preserving state, the values of its non-transient
variables even after the system that created that object has
stopped. Usually state is stored in a relational database.
 
However, the object-oriented (OO) and relational paradigms
differ a lot.
 
Relational models do not provide a way to represent behavior,
encapsulation, or complex relationships like inheritance. As well,
SQL data types do not exactly match Java data types, leading to
conversion problems. This 'impedance mismatch' is solved 'behind
the scenes' when using EJBs.


"Enterprise beans support multiple concurrent transactions with
commit and rollback capabilities across multiple data sources in
a full two-phase commit-capable environment for distributed
transactions."
The "24-7" nature of the Web has also made uptime crucial.
However, not every system needs to be designed for 24x7
operation handling millions of concurrent users.

Scalability should be achievable without sacrificing ease of
development, or standardization.

A perceived business advantage is platform and vendor independence.
Because EJB architecture is an industry standard portability is achievable.
with J2EE applications being deployable on any J2EE compliant application
server.

A Down Side

Mentioned in class, EJB suffer from a  performance overhead
associated with making a network call. The ability to make a
local call on EJBs, a facility added in EJB 2.0, has provided a
way of escaping this performance hit.

EJB 2.0 adds Local Calls

"One of the most common complaints about EJB architectures
is that they are too resource-intensive, both in terms of memory
consumption and response time. . . . The EJB 2.0 spec . . .
does . .  provide a means of reducing the response time for a
request that involves interaction between multiple beans within
the same container.
The 1.0 and 1.1 specifications defined only one way to reference
one enterprise bean from another—through the bean's remote
interface. If both beans are in the same container, then this
network round-trip is unnecessary. The 2.0 specification defines
a new type of enterprise bean reference to avoid this problem—
the local reference."

-
Kyle Gabhart, How to Utilize EJB 2.0 Local References

http://www.devx.com/getHelpOn/10MinuteSolution/16677/1954?pf=true




EJB Architecture


EJB architecture reduces the complexity of developing business
components by providing support system level services, allowing
developers to concentrate developing business logic.


EJB Architectural Components
// the line between the server and the container is blurred

EJB Server

An EJB server is the part of an application server that hosts
EJB containers. It is also known as an EJS or Enterprise
Java Server. WebSphere Application Server is an example
of an EJS. Glassfish is a newer open source server.

The EJB server provides the common services available
to all EJBs. The EJB server hides the complexities associated
with these services from the component requiring them. The
EJB specification outlines eight services that the EJB server
must provide:


J2EE Specified EJS Services
Because J2EE doesn't specify which of the Server or the
Container takes on these responsibilities, they are restated
below with detail in the context of the EJB container.



The EJB Container

"
The container hosts and manages an enterprise bean in
the same manner that the Java Web Server hosts a servlet
or an HTML browser hosts a Java applet."  

     - Monson-Haefel, jGuru: Enterprise JavaBeans Fundamentals

The container isolates the enterprise bean from direct client
access.  The container intercepts client method invocations
in order to apply  persistence, transactions, and security
management operations a client calls on a bean.

// this delay is the source of the criticism of lost performance

The EJB container
"Containers are transparent to the client in that there is
no client API to manipulate the container." A client doesn't
know in which container an enterprise bean is deployed.

The container supplies remote accessibility enabling remote
invocation of a native component over a network. EJB containers
use the Java RMI interfaces to allow clients to access EJBs.


Container /Server Responsibilities In Detail
// these are 'musts' to be J2EE compliant



EJB Components

EJB components are the Enterprise JavaBeans.They are
collectively made up from classes, interfaces and instances.
The IBM Redbook breaks EJBs down to include the following
sub-elements.

The relationships are an extension of the modeling world that
Rational majors in. The EJB query language has followed to
make bean querying easier.

We include these elements in the note as part of the
survey.


EJB Principle Sub-Components
IBM Rational Added Features

EJB Types

There are three types of enterprise beans: entity,
session, and message-driven beans. The Message
Driven Beans are relatively 'new on the block'.

The primary Bean Types
A further breakdown we can do hear just for the
sake of the overall picture is how these types
subdivide.

The primary Bean Types

Overview of EJB  Types


Entity beans
// the nouns of the system, customer, account etc
// hold data

Entity beans represent the active objects of the system.
IBM calls them 'business or domain specific concepts').
Common examples are customer and account. Entity
beans are persistent and maintain state from call to call
and across server restarts.

Entity beans usually represent data stored in a database.
The container determines when an entity bean is stored.

CMP vs BMP

How the bean is stored can be through container-managed
persistence (CMP), or through bean-managed persistence
(BMP). Container-managed persistence is maps entity
bean fields to columns in a relational database accessed
by the EJB server.

Session Beans  // task oriented

A session bean encapsulate system tasks, and is often
used to implement facades for EJB modules. Usually
session beans are not persistent. (The Redbook calls
them 'conversational').


Stateless or Stateful

Session beans may be stateless or stateful. Stateless beans
have no 'conversational state', and are pooled for reuse.
Stateful beans track state on specific clients thus are not
sharable among clients.

Message-driven Beans (MDB)

 Message-driven beans may also be modeled to
perform tasks, however, they are invoked asynchronously
The bean either listens for or subscribes to messages
that are sent to it.

Entity and session beans are accessed synchronously
either through a remote or local EJB interface method
call. // synchronous invocation

An EJB client may make a remote call via a servlet,
or a local call such as when one EJB calls on another
EJB in same Java Virtual Machine.


Message Beans Have A Unique Call System

Message-driven beans have their own call mechanism
and are not accessed through remote or a local interfaces.
MDBs are accessed solely through a JMS message. The
JMS architecture intercepts the message. The container
then delegates the message to a suitable MDB instance.


XDoclet Enterprise JavaBean


You will see in Eclipse menu items for XDoclet EJBs. The
following table has some information regarding this new
approach to creating EJBs.


<ejbdoclet/> Task

reference: http://xdoclet.sourceforge.net/olddocs/ejbdoclet.html

"This (Ant*) task allows you to generate various EJB-related files using nested subtasks and template files."

"You no longer view EJBeans as a bunch of interfaces and deployment descriptor files. You simply program your component and ejbdoclet does the rest, from generating component and home interfaces to deployment descriptor.

The point is that you program your component and specify its meta-data in a per component fashion, you don't have to deal with monolithic ejb-jar.xml files, you set the deployment meta-data per component. You don't have to worry about outdating deployment meta-data whenever you touch the code. The deployment meta-data
is continuously integrated. And the whole process is, in its nature, round-trip."

*" Ant is an [Apache] build tool for putting together the pieces of a program"          - Whatis.com

// popularized I think in the Apache, JBoss World of J2EE.




EJB interfaces and Classes


An EJB component consists of the following:
// depending on the bean type
// "Beans willing to be notified of timer events must implement the
// javax.ejb.TimedObject,
so that the container may call the
bean back when a timer expires."
 

EJB Client View


A client  needs a view to message an EJB component. A
view is a client interface to the bean, and may be local or
remote.
"Remote calls are more expensive than local calls."

"An EJB client may be a remote client, such as a servlet running
on another process, or may be a local client, such as another EJB
in the same container."

Generally a component exposes a local or a remote view but
not both. "EJBs that act as facades usually offer only a remote
interface while the rest of the components generally expose
only a local interface."

RMI Characteristics // RMI is at the heart of EJBS

"In remote invocation, method arguments and return values
are passed by value. This means that the complete objects,
including their non-transient reference graphs, have to be
serialized and sent over the network to the remote party,
which reconstructs them as new objects."  -Rad 7 PDF, IBM

Object serialization and network overhead can be costly in
terms of response time.  However remote interfaces are
location independent so their methods may be called by a
client that is in or outside of the container.

 // remotes are available locally or remotely


Relationships in Relation to CMPs

This characterization is part of Rational's Modeling View
of the Universe and can be found in UML or Unified Modeling
Language, which the founders of Rational formulated.


Relations are a key aspect of object-oriented programming.
Complex networks can be created using these relationships.

CMP entity beans, whose state is managed by the container
are exampled in the various possible relationships.
There are three different types of relationships: // described in UML


Relationship Types

//  aggregation - a set of components instantiated outside another
// component then added to it via the latter components
constructor.

// composition -  A set of components instantiated inside another
// component, and assuming no instances of the components exist
// in some other object.

// a strict composition is defined if the internal components are all inner classes

"It is the developer’s task to implement the differences
among the three kinds of relationships. These differences
may require considerations of characteristics, such as the
navigation of the relationship and the encapsulation of the
related objects."

 // build to suit the relationship specified

EJB query language (EJB QL)

The EJB query language is similar to SQL but designed
for querying  CMP entity beans. It is used to utilize EJB
custom finder or EJB select methods in a portable way.
EJB QL bases it queries on entity bean schema types
and so is able to an object-oriented rather than relational
based query.


EJB QL Query Clauses

The bean provider defines the EJB QL queries in the
deployment descriptor.  "The SQL statements for the
actual database access is generated automatically by
the deployment tooling."


Example
// IBM Redbook

// a query that retrieves customers with large balance accounts

select object(c) from Customer c, in(c.accounts) a where a.balance > ?1

// Finder and select methods specified using EJB QL are
// portable to
any EJB 2.1 environment.


EJB Containers, add GlassFish

We have seen a number of web servers such as Apache
Tomcat. Support for Enterprise JavaBeans is not guaranteed
in a Web Server.  That is the domain of a true Enterprise Java
server.


While we are surveying the general area, we might mention
various Enterprise JavaBean containers. Earliest to support
EJBs was BEA and Sun's iPlanet. IBM Websphere was soon
to follow. Oracle now has a strong EJB container support.

Early CORBA supporters found it convenient to extend support
to Enterprise JavaBeans.

More recently, open source efforts have been added to the fray.
Probably the most popular is JBoss.

Recently a new open source effort has materialized in the creation
of GlassFish. It seems to be garnering a lot of support and is
included with the Netbeans IDE.

Following are links which will get you into the neighbourhood.


Sun Community Link

http://java.sun.com/javaee/community/glassfish/


A visit to the home site shows this effort is largely sponsored
by Sun.

GlassFish Homesite


https://glassfish.dev.java.net/


EJBContext

Every bean holds an EJBContext object, which supplies
a reference back to the container.The EJBContext interface
provides methods for interacting with the container. A bean
can request information about its environment. Information
that is available includes the identity of a client and the status
of a transaction.

Java Naming and Directory Interface

When we start to look at the coding involved in Enterprise
Java Beans we bump into JNDI or Java Naming Directory
Interface. Recall in RMI this function was handled by the
rmiregistry. In CORBA there was a tnameservice.

Java Naming and Directory Interface (JNDI) is the naming service
that Java Enterprise uses. It supports naming systems such as
LDAP and NetWare file systems.

Every bean has automatic access to the ENC or Environment
Naming Context. The ENC is managed by the container and
accessed by beans using JNDI. The JNDI ENC allows a bean
to access resources like JDBC connections, other enterprise
beans, and properties specific to that bean.


Inner Workings of Enterprise Beans

A bean is created to represent a business concept, like a
customer or a clerk  To create an EJB, a developer provides:

In version 1.0 the two interfaces were a home and remote
interface. In EJB 2.0 the concept of the Local interface was
added. In version 3.0 a whole a new notation is added.

Tip: If experimenting with building Enterprise JavaBeans
in the modern IDEs, be sure to select the correct version
support for the beans you are testing.


Remote and Home Interfaces

The home interface represents the life-cycle methods of the
component.

The remote interface represents the business method of the bean.

The remote and home interfaces extend the javax.ejb.EJBObject
and javax.ejb.EJBHome interfaces respectively. These EJB interface
types define a standard set of utility methods and provide common base
types for all remote and home interfaces.


The Remote interface hierarchy Used with EJBs  

                          java.rmi.Remote                                   // rmi interface level
                           |                       |
     javax.ejb.EJBObject         javax.ejb.EJBHome         // EJB specific interface level
                     |                                          |
         Bean's_Remote                 Bean's_Home       //  developer's defined extensions



How the Referencing Works


The home interface implementation is used to create
the bean. The methods of the remote interface execute
the business code.


Example
// from EJB Fundamentals  by R. Monson-Haefel

// ... obtain a reference that implements the home interface.
// Use the home interface to create a new instance of the Customer bean.
   Customer customer = home.create(customerID);
// using a business method on the Customer.
   customer.setName(someName);


The Remote Interface for the Above Example

import javax.ejb.EJBObject;
import java.rmi.RemoteException;  

public interface Customer extends EJBObject {

      public Name getName( ) throws RemoteException;
      public void setName(Name name) throws RemoteException;
      public Address getAddress( ) throws RemoteException;
      public void setAddress(Address address) throws RemoteException;
      } 
  //  Here the Customer remote interface is defined as extending javax.efb.EJBObject, 
 //  (which extends java.rmi.Remote) The interface defines bean's business methods

A Tour of a Classic EJB
// a stateless bean called ConverterBean


Following is an example of a Stateless Session bean
sampled in the J2EE Tutorial published by Sun and
referenced above. It would have been necessary to
go into the details of the different obligations that were
associated with implementing the different methods of
the interfaces.

However, as we shall see, EJB 3.0 promises to remove
a lot of the development work.  Let's assume that the
new way is the way to go, in which case we will provide
a classic example in a cursory fashion.

Top Level Interface 
// from the J2EE Tutorial, Sun  Microsystems


import javax.ejb.EJBObject;
import java.rmi.RemoteException;
import java.math.*;
public interface Converter extends EJBObject {
public BigDecimal dollarToYen(BigDecimal dollars)
throws RemoteException;
public BigDecimal yenToEuro(BigDecimal yen)
throws RemoteException;
}



The Home Interface
// from the J2EE Tutorial, Sun  Microsystems

import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;

public interface ConverterHome extends EJBHome {
Converter create() throws RemoteException, CreateException;
}


The Remote Interface
// from the J2EE Tutorial, Sun  Microsystems

import javax.ejb.EJBObject;
import java.rmi.RemoteException;
import java.math.*;
public interface Converter extends EJBObject {
public BigDecimal dollarToYen(BigDecimal dollars)
throws RemoteException;
public BigDecimal yenToEuro(BigDecimal yen)
throws RemoteException;
}

The Implementation Bean
// from the J2EE Tutorial, Sun  Microsystems

import java.rmi.RemoteException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import java.math.*;
public class ConverterBean implements SessionBean {
BigDecimal yenRate = new BigDecimal("121.6000");
BigDecimal euroRate = new BigDecimal("0.0077");
public BigDecimal dollarToYen(BigDecimal dollars) {
BigDecimal result = dollars.multiply(yenRate);
return result.setScale(2,BigDecimal.ROUND_UP);
}
public BigDecimal yenToEuro(BigDecimal yen) {
BigDecimal result = yen.multiply(euroRate);
return result.setScale(2,BigDecimal.ROUND_UP);
}
public ConverterBean() {}
public void ejbCreate() {}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext sc) {}
}


The Client

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import java.math.BigDecimal;
public class ConverterClient {
public static void main(String[] args) {
try {
Context initial = new InitialContext();
Context myEnv =
(Context)initial.lookup("java:comp/env");
Object objref = myEnv.lookup("ejb/SimpleConverter");
ConverterHome home =
(ConverterHome)PortableRemoteObject.narrow(objref,
ConverterHome.class);
Converter currencyConverter = home.create();
BigDecimal param = new BigDecimal ("100.00");
BigDecimal amount =
currencyConverter.dollarToYen(param);
System.out.println(amount);
amount = currencyConverter.yenToEuro(param);
System.out.println(amount);
System.exit(0);
} catch (Exception ex) {
System.err.println("Caught an unexpected exception!");
ex.printStackTrace();
}
}
}


EJB 3.0

"Java 5 (previously called J2SE 1.5, or Tiger) has introduced
a new program annotation facility to the language. With this
facility, you can define custom annotations and then annotate
fields, methods, classes, etc., with these annotations.

Annotations do not directly affect program semantics, but tools
(compile time or runtime) can inspect these annotations to generate
additional constructs (like a deployment descriptor) or enforce
desired runtime behavior (like an EJB component's stateful nature).
Annotations can be inspected through source parsing
(e.g., compilers or IDE tools) or by using the additional reflection
APIs added in Java 5. "
                                                              - Anil Sharma, JavaWorld.com

Stateless Beans Using  EJB 3.0

A Stateless session bean, written using the new EJB 3.0
syntax is a regular Java class with the @Stateless notation
added.

// you can implement SessionBean but it is ignored!

Following is an example that was developed in NetBeans.
With any luck it should transfer to Eclipse. This follows the
new form taken in EJB 3.0 which should prove to be quite
a bit simpler then the older versions of EJB.

I think it would be interesting to first try and execute the
following sample code in Netbeans. Then follow a similar
procedure in Eclipse3.

To Do

We start by creating an EJB Project.

Under the project create a new package called 'tools'.

Right Clicking on it we can create a new interface.


Example of the Top Level Interface


package tools;

public interface Keys {
    public String getSubject();

}

Next we right click on our project, click new and go to
Session Bean. We make it stateless. Notice the new
bean has a @Stateless annotation.

We can call this KeysBean.

We have to enhance it with an implementation of the
method we have defined in the Keys interface.


Stateless Session Bean Called KeysBean

package tools;

import javax.ejb.Stateless;

/**
 *
 * @author Peter
 */

@Stateless
public class KeysBean implements KeysRemote, KeysLocal {
   
  public String getSubject(){
       return "Town Meeting";
  }

 }

If we look around we should find that the KeysLocal
and KeysRemote class have also been created.

We will need to add the extension of the Keys interface
to them. Again note how they are using the annotation
to hide away a lot of the complexity of the EJB architecture.

The IDE environment has put this class into the beansession
package.


KeysLocal Class Generated by the IDE

package beansession;

import javax.ejb.Local;

/**
 *
 * @author Peter
 */
@Local
public interface KeysLocal{
   
}

To the KeysRemote class the extension of
the Keys interface was added as it was found
to be !  Again this system is
taking care of ties behind the scene.


KeysRemote Class Generated by the IDE

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tools;

import javax.ejb.Remote;

/**
 *
 * @author Peter
 */
@Remote
public interface KeysRemote extends Keys{
   
}

The Client

Finally a Client has to be developed to test the
bean. This became a time consuming effort due
to the difficulty determining how the IDE names
the bean in JNDI.

The net revealed many others had similar problems.


A Little Discovery


The following code snippet helped to reveal what
the NetBeans environment called the bean. The same
result was found in Eclipse so there is some uniformity
here.

Essentially, the Context object is used to list the names
that JNDI has used to store the bean.


Example

 Context i = new InitialContext();
     NamingEnumeration ne= i.list("");
          while(ne.hasMore()){
       System.out.println("Uno: " + ne.next());
          } 

You can comment in the code and comment out the method
call to see the following result.

OUTPUT // NetBeans 6.1

----> tools.KeysRemote: javax.naming.Reference
----> jdbc: com.sun.enterprise.naming.TransientContext
----> tools.KeysRemote__3_x_Internal_RemoteBusinessHome__: javax.naming.Reference
----> UserTransaction: com.sun.enterprise.distributedtx.UserTransactionImpl
----> ejb: com.sun.enterprise.naming.TransientContext
----> tools.KeysRemote#tools.KeysRemote: javax.naming.Reference
----> __SYSTEM: com.sun.enterprise.naming.TransientContext


It shows that the name in the context of the IDE is
tools.KeysRemote which is the name of the Remote
class qualified by it's package name.

If you were to fully deploy the app to a server, it would
take on a JNDI name qualified by a URL form.


Client Sample Code

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tools;
import javax.naming.*;
/**
 
 */

public class KeyUser {
    public static void main(String[] args){
    try{
     System.out.println("The client is a go.");
   /*     
    Context i = new InitialContext();
     NamingEnumeration ne= i.list("");
          while(ne.hasMore()){
       System.out.println("----> " + ne.next());
          }    
     */
   
     InitialContext i = new InitialContext();
      KeysRemote   k = (KeysRemote)i.lookup("tools.KeysRemote");
      System.out.println(k.getSubject());
  
    }
    catch(NamingException ne){
     System.out.println("Naming Exception\n" + ne.toString());
    }
     catch(Exception ne){
     System.out.println("General Exception\n" + ne.toString());
    }
  }
}


The OUTPUT was as follows. Hopefully we will arrive at the
same end in class. The key return value is the "Town Meeting"
string which was the contents of the method defined in our
Session bean.

OUTPUT  // NetBeans

init:
deps-jar:
compile-single:
run-main:
The client is a go.
Town Meeting
BUILD SUCCESSFUL (total time: 2 seconds)



Assignment


Run the Example EJB 3.0 Code in NetBeans
and capture screen shots of the code and the
output.

Optional

Attempt to run the above code in Eclipse and
make it work.

Attempt to set the IDEs to support the older version
of EJB, version 2.0 and run the Converter EJB in
either NetBeans Eclipse or both.