Distributed Object Systems
– 9 –
Javabeans/EJB
Piet van OostrumOct 9, 2008
DOS-9
JavaBeans
I Java Component technology:
“Components are self-contained, reusable software units that can be visually composed into composite components, applets, applications, and servlets using visual application builder tools”
I Standard API to communicate with the Bean I Bean must be configurable
I Bean must reveal information about itself I will be used by IDE
I Graphical and non-graphical I Comparable to ActiveX components
Piet van Oostrum DOS-9 1
DOS-9
JavaBeans model
I Javabeans often use events to communicate with each other I Events are sent when Bean state changes
I Others can register to be notified
I Persistence can be used to store Bean state
Piet van Oostrum DOS-9 2
DOS-9
Parts of a Bean
I Runtime Interface I Configuration I Design Time Interface I Instantiation and Activation I Serialization/Persistence I Reflection
Most are optional!
Piet van Oostrum DOS-9 3
Example: Thermostat Bean
Design Issues
Usually the following are highly preferred:
I Default Constructor
I Implementation of Serializable I Set/Get methods for properties I Add/remove methods for event listeners I JDK 1.1 Event model
I Thread safe I Security (Applets)
DOS-9
Example
Piet van Oostrum DOS-9 6
DOS-9
Custom Property Editor
Piet van Oostrum DOS-9 7
DOS-9
Event Model
I Same model as AWT in JDK 1.1 and beyond I AWT/Swing components are basic Beans I EventObjects and EventListeners
Examples of Events:
I GUI events (mouse/keyboard) I Database Changes
I Response to requests (asynchronous) I Property Changes in Bean
Piet van Oostrum DOS-9 8
DOS-9
Bean Properties
I A property xxx should have methods getXxx and setXxx I IDE can find out which properties are available by
introspection
I Property editor can often do conversion automatically I Some types cannot be handled nicely (e.g. enumerations) I Indexed properties (arrays) use specialized set/get methods,
e.g.
public void setColorTable(int index, Color value); public Color getColorTable(int index);
public void setColorTable(Color values[]); public Color[] getColorTable();
Piet van Oostrum DOS-9 9
DOS-9
Bound Properties
A bound property supports notification of changes In the bean:
private PropertyChangeSupport changes = new PropertyChangeSupport(this); public void addPropertyChangeListener(
PropertyChangeListener p) {
changes.addPropertyChangeListener(p); }
public void removePropertyChangeListener( PropertyChangeListener p) {
changes.removePropertyChangeListener(p); }
Clients can add and remove PropertyChangeListeners
DOS-9
Bound Properties
Set method must fire a notification public void setLevel(int level) {
int oldlv = this.level; this.level = level;
changes.firePropertyChange("level", new Integer(oldlv), new Integer(level)); }
DOS-9
Constrained properties
Additional Functionality above Bound properties:
notified listener can veto the property change
private VetoableChangeSupport vetoes = new VetoableChangeSupport(this); public void addVetoableChangeListener(
VetoableChangeListener v) { vetoes.addVetoableChangeListener(v); }
public void removeVetoableChangeListener( VetoableChangeListener v) {
vetoes.removeVetoableChangeListener(v); }
Piet van Oostrum DOS-9 12
DOS-9
Usage of Constrained Properties
public void setLevel(int level)throws PropertyVetoException {
vetoes.fireVetoableChange("level",
new Integer(this.level), new Integer(level));
int oldlv = this.level; this.level = level;
changes.firePropertyChange("level", new Integer(oldlv), new Integer(level)); }
Piet van Oostrum DOS-9 13
DOS-9
Usage of Constrained Properties
In the listener:public void vetoableChange
(PropertyChangeEvent e) throws PropertyVetoException {
// ... raise the PropertyVetoException // if it doesn’t agree with the change }
The exception is caught by the JavaBeans framework, not by the set method.
Piet van Oostrum DOS-9 14
DOS-9
Introspection
I Java providesreflection: You can find out information about
classes.
I This is used by IDE’s to get (a.o.) the names of properties I Introspector class gives higher-level support for info about
a Bean (properties, events, and methods).
I It uses implicit info from the MyBean class/superclasses, I and explicit info from a separate MyBeanBeanInfo class. I This information is used to build a BeanInfo object
Piet van Oostrum DOS-9 15
Example BeanInfo
For a Bean called ‘Hire’ with a bound property ‘salary’:
import java.beans.*; public class HireBeanInfo
extends SimpleBeanInfo { public PropertyDescriptor[] getPropertyDescriptors() { try { PropertyDescriptor pd1 = new PropertyDescriptor("salary", Hire.class); pd1.setBound(true);
return new PropertyDescriptor[] {pd1}; } catch (Exception e) { return null; } } }
Property Editors
DOS-9
Property Editors
Restricted by BeanInfo:
Piet van Oostrum DOS-9 18
DOS-9
Customized Property Editors
‘department’ can be choosen from a list of values (enumeration)’: it needs a customized property editor
Piet van Oostrum DOS-9 19
DOS-9
Customized Property Editors
public class HireBeanInfo
extends SimpleBeanInfo { public PropertyDescriptor[] getPropertyDescriptors() { try { PropertyDescriptor pd1 = new PropertyDescriptor("salary", Hire.class); PropertyDescriptor pd2 = new PropertyDescriptor("department", Hire.class); pd2.setPropertyEditorClass( DepartmentEditor.class);
return new PropertyDescriptor[] {pd1, pd2}; } catch (Exception e) { return null; } }
}
Piet van Oostrum DOS-9 20
DOS-9
Conclusion
I Javabeans are components to build applications I Similar to chips in hardware
I Usually to build client applications I Can be bought off the shelf I Not distributed objects
Piet van Oostrum DOS-9 21
DOS-9
Multi-tier applications
I Monolythic applications:
I The whole application is in one process
I This includes user interface, ‘business logic‘ and data handling
I Client-server applications
I Usually user-interface and business logic in client I Database in server
I Multi-tier applications:
I Client contains only user interface I Database server(s)
I Business logic in one or more intermediate tiers
DOS-9
Enterprise Javabeans (EJB)
I EJB is a framework for multi-tier applications in Java I Especially for the business logic tier
I This tier should concentrate on business objects
I customers I students I orders I etc.
I The framework is responsible for providing services
I security I transactions I etc.
DOS-9
EJB advantages
I Cross-platform components (Java)
I Developer concentrates on Business programming, not services I Scalable (business components can be divided over several
servers)
I Can use existing services
I Database services I Transaction services I Web servers I Security
I Multithreading, . . .
Piet van Oostrum DOS-9 24
DOS-9
EJB characteristics
I Some ideas from Javabeans I EJB areserver-sidebeans
I Communication through RMI or RMI-IIOP (hence Corba) I EJB’s work inside acontainer
I Containers run in a server
I Standards for communication between container and EJB I Dynamic configuration through properties (environment) I EJB’s can be dynamically added to a server
I Client uses proxy object (EJB Object)
Piet van Oostrum DOS-9 25
DOS-9
EJB model
I Servers e.g. JBoss, IBM Websphere, BEA WebLogic
Piet van Oostrum DOS-9 26
DOS-9
EJB model
Figure 1.6 A J2EE deployment.
■■Java API for XML RPC (JAX-RPC).JAX-RPC is the main technology that provides support for developing Web Services on the J2EE plat-form. It defines two Web Service endpoint models—one based on servlet technology and another based on EJB. It also specifies a lot of runtime requirements regarding the way Web Services should be sup-ported in a J2EE runtime. Another specification called Web Services for J2EE defines deployment requirements for Web Services and uses the JAX-RPC programming model. Chapter 5 discusses support of Web Services provided by both these specifications for EJB applications. ■■Java Remote Method Invocation (RMI) and RMI-IIOP.RMI is the Java
language’s native way to communicate between distributed objects, such as two different objects running on different machines. RMI-IIOP
Firewall EJBs Existing System Legacy System ERP System IIOP Client Tier J2EE Server Back-End Systems Business Partner or Other System Servlets Business Partner or Other System Applets, Applications, CORBA Clients IIOP Web services technologies
(SOAP, UDDI, WSDL, ebXML) HTTP
Databases
Proprietary ProtocolWeb Services Technologies(SOAP, UDDI, WSDL, ebXML) Connectors
SQL
JSPs Web Browser Wireless Device
HTTP
JMS
Overview 23
Piet van Oostrum DOS-9 27
EJB types (EJB version 2)
I Entity bean
I Corresponds to a (business) entity, e.g. customer, order,
student
I Persistent object
I Survives server shutdown or crash I Is loaded on demand (for scalability)
I Implements interface javax.ejb.EntityBean I Has primary key (e.g. order number, student number)
I Session bean
I Represents connection from a client I Usually not persistent
I Implements interface javax.ejb.SessionBean I Stateless or statefull
I Message-driven bean
I For messaging services (event driven)
EJB container
I Container contains all the infrastructure (transactions etc.) I EJB’s relate to the world through the container
I For each EJB the container contains aHomeobject
I This is the factory object to create EJB’s I Every EJB class has its Home interface
I The interface contains methods to create, find (for entity
beans), initialize,destroy beans
I Home interface extends javax.ejb.EJBHOME
I EJB’s are not directly called by clients I Proxy EJB object is called instead
I Allows the container do supply services (transactions,
DOS-9
Interceptors
technologies (EJB, CORBA Component Model, and Microsoft.NET) is that in this new world, you can harness complex middleware in your enterprise applications without writing to middleware APIs (see Figure 2.4).
In outline, follow these steps to harness the power of middleware: 1. Write your distributed object to contain only business logic. Do not write
to complex middleware APIs. For example, this is the code that would run inside the distributed object:
transfer(Account account1, Account account2, long amount) { // 1: Subtract the balance from one account, add to the other }
2. Declare the middleware services that your distributed object needs in a separate descriptor file, such as a plain text file. For example, you might declare that you need transactions, persistence, and a security check.
Figure 2.4 Implicit middleware (gained through declarations).
Stub Client Request Interceptor Skeleton Remote Interface Network
Remote Interface Transaction Service Security Service Database Driver Transaction API Security API Database API Distributed Object Remote Interface The request interceptor knows what to do because you describe your needs in a special descriptor file. 34 Chapter 2
Piet van Oostrum DOS-9 30
DOS-9
EJBObject and Bean
Figure 2.5 EJB objects.
Each EJB container ships with a suite of glue-code tools. These tools are meant to integrate beans into the EJB container’s environment. The tools generate helper Java code—stubs, skeletons, data access classes, and other classes that this specific container requires. Bean providers do not have to think about the specifics of how each EJB container works because the container’s tools gener-ate its own proprietary Java code automatically.
The container’s glue-code tools are responsible for transforming an enterprise bean into a fully managed, distributed server-side component. This involves logic to handle resource management, life cycle, state management, transac-tions, security, persistence, remote accessibility, and many other services. The generated code handles these services in the container’s proprietary way. The Remote Interface
As mentioned previously, bean clients invoke methods on EJB objects, rather than the beans themselves. Therefore, EJB objects must clone every business method that your bean classes expose. But how do the tools that autogenerate EJB objects know which methods to clone? The answer is in a special interface that a bean provider writes. This interface duplicates all the business logic methods that the corresponding bean class exposes. This interface is called the
remote interface.
Remote interfaces must comply with special rules that the EJB specification defines. For example, all remote interfaces must derive from a common inter-face supplied by Sun Microsystems. This interinter-face is called javax.ejb.EJBObject, and it is shown in Source 2.2.
EJB Container/Server
Enterprise Bean Client Code, such as
Servlets or Applets 1: Call a Method EJB Object Remote Interface 4: Method Returns 5: Return Result 3: Call a Bean Transaction Service, Security Service, Persistence Sevice, etc 2: Call Middleware APIs
EJB Fundamentals 39
Piet van Oostrum DOS-9 31
DOS-9
Transactions
I Each container must implement interface
javax.jts.UserTransaction
I JTS = Java Transaction Service I Some methods are:
I commit() I rollback()
I EJB must have a transactional attribute that tells whether the
bean supports and/or needs transactions
I Transaction can contain multiple EJB and/or Corba objects
on multiple servers
Piet van Oostrum DOS-9 32
DOS-9
Transactions 2
I Client that uses JNDI to locate beans use
javax.jts.UserTransaction
I Corba clients use Object Transaction Service (OTS) I JTS is the Java interface to Corba’s OTS
I RMI-IIOP is used to communicate with the OTS for JNDI
clients
Piet van Oostrum DOS-9 33
DOS-9
Client view
I Client has the Interface specification of the EJB I Interface must be RMI compatible:
I extends EJBObject (extends Remote) I methods must specify throws RemoteException I Object parameters must be remote or serializable
I Client finds the EJB Home interface through the JNDI. I It calls the Home interface with a create method to create a
bean
I Implementation of the EJBObject methods is in the container
DOS-9
Example Entity Bean
Our entity bean needs the following:
I component interface (maybe remote and local)
This is what clients need to know
I home interface (maybe remote/local)
This is used to find/create entities
I implementation
I appropriate finder methods I bean implementation class I deployment descriptor
DOS-9
Component interface (local)
We use an Employee entity as exampleimport javax.ejb.*; import java.util.*; import java.sql.*; import java.math.*;
public interface Employee extends javax.ejb.EJBLocalObject { public int getEmployeeID();
public void setEmployeeName(String name); public String getEmployeeName();
public void setEmployeeAddress(String address); public String getEmployeeAddress();
public void setSalary(BigDecimal salary); public BigDecimal getSalary();
... lots more ... }
get... and set... are for accessing instance variables (attributes)
Piet van Oostrum DOS-9 36
DOS-9
Remote Interface
The remote interfaces must specify the ’throws RemoteException’
import javax.ejb.EJBObject; import java.ejb.RemoteException;
public interface EmployeeRemote extends EJBObject {
public int getEmployeeID() throws RemoteException; public void setEmployeeName(String firstName)
throws RemoteException; public String getEmployeeName() throws RemoteException; public void setEmployeeAddress(String lastName)
throws RemoteException; public String getEmployeeAddress() throws RemoteException; ...
}
Piet van Oostrum DOS-9 37
DOS-9
Home Interface
I More than one create() method is possible (overloaded) I Only one findByPrimaryKey is possible (must always have one
parameter)
import javax.ejb.EJBHome; import java.ejb.* // Exceptions
public interface EmployeeHome extends EJBHome { public Employee create(int employeeID, String name,
String address)
throws CreateException, RemoteException; public Employee findByPrimaryKey(
EmployeePrimaryKey empKey) throws FinderException, RemoteException; }
public class EmployeePrimaryKey
implements Serializable { public int employeeId; }
Piet van Oostrum DOS-9 38
DOS-9
Entity Bean Persistence
Persistence for Entity bean can be provided by:
I Container (container-managed persistence)
I At deployment time the deployer must give the container a list
of fields that must be persisted
I Difficulities e.g. how do the fields map to database records?
e.g. SQL code must be supplied (container dependent). I Bean itself (bean-managed persistence)
I Bean must access database for persistence I Or use another component to do the work
Piet van Oostrum DOS-9 39
Entity Context
I The container keeps a datastructure called ’EntityContext’ to
keep info about the entity
I transaction, security, EJBObject, Primary key
I Important: the container can have more entities than
instances of the EJB!
I The cantainer can reuse EJB’s from a pool
I The EntityContext interface provides an instance with access
to the container-provided context
I The container passes the EntityContext interface to an
instance after the instance has been created.
I information that the instance obtains using the EntityContext
interface (e.g result of getPrimaryKey()) may change.
Example container-managed bean
import javax.ejb.EntityBean; import java.ejb.EntityContext; import java.ejb.CreateException;
public class EmployeeBean implements EntityBean {
private transient EntityContext entContext; public int employeeID;
public String employeeName; public String employeeAddress;
public void setEntityContext(EntityContext context) {
entContext = context; }
DOS-9
Example container-managed bean
public void unsetEntityContext() {
entContext = null; }
public EmployeePrimaryKey ejbCreate(int ID, String name, String address) throws CreateException { employeeID = ID; employeeName = name; employeeAddress = address; return null; }
Piet van Oostrum DOS-9 42
DOS-9
Example container-managed bean
public void ejbPostCreate(int ID, String name, String address) throws CreateException
{ // This method is called by the container // after the persistence has be loaded }
public int getEmployeeID() {
return this. employeeID; }
public void setEmployeeName(String empName) {
employeeName = empName; }
// etc ... }
Piet van Oostrum DOS-9 43
DOS-9
Container Callable Methods
I setEntityContext(EntityContext context): the entity
bean must save the state of the EntityContext interface in its instance variable.
I unsetEntityContext(): container invokes this method
before terminating the entity bean instance
I ejbCreate(): the signature of each one should map to the
create() methods in the entity bean Home interface.
I ejbPostCreate(): For each ejbCreate() method provide
matched ejbPostCreate() method. Called after the persistence has been loaded
Piet van Oostrum DOS-9 44
DOS-9
Sequence diagram Create
ClientEJBHome
Instance
database
EJBObject create new DB entry create()
ejbPostcreate() ejbCreate()
extract CMP fields
Piet van Oostrum DOS-9 45
DOS-9
Sequence diagrams Remove
Client EJBHome EJBObject Instance database
remove()
ejbRemove()
remove from database
DOS-9
Sequence diagrams Find
(Container Managed Bean)Client EJBHome Instance database
EJBObject
find<method>
new
DOS-9
Example client
public class EmployeeTestClient {
private EmployeeHome employeeHome = null; public EmployeeTestClient() {
try {
Context ctx = new InitialContext(); Object ref = ctx.lookup("EmployeeRemote");
employeeHome = (EmployeeHome) PortableRemoteObject.narrow (ref,EmployeeHome.class); EmployeePrimaryKey empNo = EmployeePrimaryKey(12345); EmployeeRemote employee = employeeHome.findByPrimaryKey
(empNo); System.out.println(employee.getEmployeeName()); System.out.println(employee.getEmployeeAddress()); } catch(Exception e) { e.printStackTrace(); } }
Piet van Oostrum DOS-9 48
DOS-9
EJB version 2 complexities
I several interfaces and unnecessary callback methods. I implementation of EJBObject or EJBLocalObject and many
exceptions.
I container-managed persistence is complex.
I not really object-oriented (restrictions on inheritance and
polymorphism).
I cannot test outside an EJB container. I looking up an EJB is complex (JNDI). I deployment descriptor is complex.
Piet van Oostrum DOS-9 49
DOS-9
EJB version 3 simplifications
I the bean class can be a plain java class (POJO) I the EJB interface may be a pure interface (POJI) I the EJB Home interface is no longer needed
I annotations can be used instead of a dedicated deployment
descriptor
annotations are metadata that are compiled into the class (can be obtained by the container with introspection)
I methods such as ejbPassivate, ejbActivate, ejbLoad, ejbStore
not necessary to implement for all @Remote
public interface EmployeeFacade {
Employee addEmployee(String name, double salary); Employee findEmployeeByEmpNo(Long empNo);
}
Piet van Oostrum DOS-9 50
DOS-9
Example EJB3 Entity Bean
@Entity@Table(name = "EMPLOYEES")
public class Employee implements Serializable {
private int empId; private String Name; private double salary; @Id
@Column(name="EMPNO", primaryKey=true) public int getEmpId()
{
return empId; }
...
Piet van Oostrum DOS-9 51
Example EJB3 Stateless Session Bean
@Stateless
public class EmployeeFacadeBean implements EmployeeFacade { @PersistenceContext
private EntityManager em;
public Employee addEmployee(String empName, double sal) { Employee emp = new Employee();
emp.setName(empName); emp.setSal(sal); em.persist(emp); return emp; }
public Employee findEmployeeByEmpNo(Long empNo){ return em.find(Employee.class,empNo); }