Enterprise JavaBeans Fundamentals
Agenda
Enterprise JavaBeans defined EJB and Distributed Computing
EJB Architecture
Entity beans Session bean Deployment EJB Clients
Enterprise JavaBeans: Defined
What is Enterprise JavaBeans
component architecture for the development and deployment of object-oriented distributed enterprise-level applications
Scalable
transactional multi-user secure
collection of Java classes and XML file, bundled into a single
unit. The Java classes must follow certain rules and provide certain callback methods.
4
In English Please!
Enterprise JavaBeans is a specification
(a piece of paper) not a product As is XML, CORBA, TCP/IP
Enterprise JavaBeans is Java based
Defined by Sun Microsystems Applications are written in Java
Enterprise JavaBeans is distributed objects
Similar to CORBA | Java RMI (JRMP) | Microsoft MTS
Enterprise JavaBeans is components
Similar to regular JavaBeans (similar but not the same) Similar to COM/DCOM/COM+
Enterprise JavaBeans products are Transactional
Monitors
Similar to CICS | TUXEDO A complete environment for a distributed object
5
Enterprise JavaBeans
Simple Programming Model
Attribute based programming
Focus on Business Logic
Simple API Well defined Lifecycle
Portable
Specification ensures basic services
Component Packaging (JARs and XML DD) Java
WORA
Write-Once, Run Anywhere within Middleware Middleware provides all services
Instance management, transactions, concurrency,
persistence
Beans stay simple!
EJB Advantages
With EJB, you can write a business object and
easily make it
Persistent
Distributed Transactional Secure
Multithreaded
Persistent
Beans need to load and store data You can let the server do it
(Container-Managed Persistence)
You can do it yourself
(Bean-Managed Persistence)
Transactional
Support for distributed transactions You can let the Server manage all transactions
You will if you know whats good for you
You can give it hints in deployment descriptor
10
Secure
SSL/RMI protects transmitted data Client-Server architecture protects
proprietary code
backend database
SSL authenicates client, server ACLs provide fine-grained control of access to
objects, methods, services
11
Multithreaded
Programmer delegates all responsibility for
multithreading to server
Programmer literally cant spawn a thread
Program designer and/or sysadmin establishes
multithreading policies Server enforces them invisibly
12
Naming Services
JNDI Wrapper for many naming services
CORBA, RMI, etc.
13
CORBA and EJB
Transport
EJB uses RMI interface, RMI uses IIOP
CORBA 3.0 promises object compatibility with
EJB
Not quite sure what that means
Some EJB Servers contain an ORB
All EJB Objects are also CORBA objects
14
EJB Architecture
EJB Roles
Bean developer: creates JAR with:
Remote interface with business functions
Home for accessing instances of bean
Bean itself Properties and descriptor
Assembler: one who combine the EJB
components with other software to make a complete application Deployer: modifies and deploys beans in EJB server
Organization-specifics, ie security
16
EJB Roles (cont.)
Server provider provides Server run-time Container provider: provides tools and containers
Creates container classes that wrap bean
Manage installed beans
System administrator - one who manages the
application after it has been deployed into a target environment.
17
The EJB Container
Think of the container as the server, holding your
objects Containers host enterprise beans Containers isolate beans from clients
Intercept client requests Set up transactions, security, persistence, etc.
before and after calling EJB methods Beans can also call methods of the container interface to get services
Containers provide JNDI services too
18
EJB Provider
Application Assembler
Deployer
App Server/ EJB Container Provider
System Administrator
19
Session Beans
Not persistent, but can access database Model tasks, process or agents
Charge a credit card Process a stock purchase Perform hotel reservations
Manage interactions of other beans
20
Stateless Session Beans
Perform transitive tasks Independent business methods
Act on method arguments, not bean state
Similar to procedures in traditional TPM systems
Most performant bean type Not dedicated to one client
21
Stateful Session Beans
Act on behalf of one client
Extension of the client
Agent that performs work for the client
Interdependent business methods
Bean has conversational state Method depend on conversational state
Dedicated to exactly one client
22
EJB Conversation
Finding the Bean Getting access to a bean
Calling the beans methods
Getting rid of the bean
23
Finding the bean
Use naming service (associates a symbolic name
with an object) Use JNDI to provide a uniform interface to all naming services or CORBAs COS Naming Services
DNS UNIX /etc/hosts file system
24
Getting access to bean
Naming lookup returns reference to home
interface object
Client uses the home interface to find existing EJB
instances or create new one.
Look up returns reference to remote Interface
object
Client uses remote interface to interact with EJB
objects
25
Calling the bean and getting rid of it
Invoke the public methods of bean Destroying by remove()
Stateful session container discard it and use the
space for other bean Stateless session returns the instance to a pool Entity remove the underlying object from persistent storage ie. database
26
27
Building and deploying EJBs
Writing the EJB EJB implementation class Home interface Remote interface Deployment descriptor Properties file containing any environment properties that a bean
expects
Create a manifest file for creating the ejb-jar file (medium to
distribute EJBs)
Deploying EJB Ejb container reads the ejb-jar file Create implementations for the home & remote interfaces Read the deployment descriptor Add the beans property settings to the environment
Connecting to the EJB Either RMI or CORBA to connect to the EJB
28
Function of a Deployment Descriptor
Describe bean(s) to the container
interfaces and class type of bean (entity or session) identify primary key & container-managed fields
Declare runtime behavior
transaction attributes of methods authorization access to method persistence type (BMP vs. CMP)
Written in XML
29
Deployment Descriptor
Name of the EJB class Name of the EJB home interface
Name of the EJB remote interface
ACLs of entities authorized to use each class or
method For Entity beans, a list of container-managed fields For session beans, a value denoting stateful or stateless
30
Programming: Interfaces and Classes
Home Interface (1) Extends [Link] Provides remote access to create, find, remove beans Remote Interface (2) Extends [Link] Provides remote access to business methods Bean Class EJB Implementation class (3) Extends a [Link] type Implements business logic and other functionality
31
EJB Architecture
Naming Service Server
RMI Client RMI
You write this Implements Invokes
32
Home Interface (Factory)
Container
Remote Interface
EJB Object (Wrapper)
Enterprise Java Bean (Biz Logic)
Creates / uses
Bean provider: What to write? Eg. Stateless Session Bean
Remote Interface
extend EJBObject interface Define business method signatures
Home Interface
extend EJBHome interface Define create signatures May define findBy signatures for entities
33
Remote Interface
import [Link]; import [Link];
public interface Customer extends EJBObject {
public String getName(String n) throws RemoteException;
34
Functionality of remote interface
Container generates a class implementing
Customer interface during deployment time The class passes method invocations to the EJB implementation class Allows the client to do:
Get a reference to the beans home interface (thru
getEJBHome() method) Get a reference that can be saved and then restored (thru getHandle() method) Get rid of the objet (thru remove() method) Test whether two remote objects are identical (isIdentical())
35
Home Interface
import [Link]; import [Link]; import [Link]; import [Link]; public interface CustomerHome extends EJBHome { public Customer create()throws RemoteException, CreateException;
36
Functionality of Home interface
Create()
Atleast one create method should be there
replace constructors in EJB for initializing an object
Initialize the internal state of the object where
container maintain a cache of already instantiated objects Stateless only one create() with no arguments Must be public Return type must be the type of the remote interface Throws clause must include RemoteException and CreateException
37
Other method signature of Home interface
remove() allow a client to delete EJB instances by
its handle or its primary key
getEJBMetaData returns an object the
implements the EJBMetaData
38
Bean implementation:What to write (cont.)?
Enterprise Bean Class
implement EntityBean or SessionBean Implement business method signatures Does not need to implement Remote Interface not abstract Implement ejbCreate methods matching Home
create
One ejbCreate for every [Link] N.B.: create in home interface, ejbCreate in Bean
39
Bean Class
import [Link].*;
public class CustomerBean implements SessionBean { SessionContext ctx; public void ejbCreate() { } public Name getName(String n) { return How are you, + n; } public public public public }
40
void ejbRemove() { } void ejbPassivate() { } void ejbActivate() { } void setSessionContext(SessionContext ctx) { [Link] = ctx;}
Session bean method signatures
ejbActivate() -called by container after session
beans state has been restored from semipersistent storage ejbPassivate() called by container before swapping the object out to semi persistent storage ejbRemove() invoked as result of client calling the remove() setSessionContext()
Container passes context object to session bean at
41
the very beginning of beans life Bean stores this object in an object variable Use this to interact with container provided services like security & transaction management
Session bean method signatures
ejbCreate()
Public
Void return type Number and type of arguments of ejbCreate() must
same as the number and type of arguments in the create() method No need of throwing exceptions bcos exceptions are thrown from create() method
42
Compile (4) Remote Interface Home Interface Implementation class
43
Create a session descriptor (5)
SessionDescriptor class Specifies the deployment environment
Deployer deserializes the instance of Session
descriptor and uses the information it contains to deploy the bean
44
import [Link].*;; import [Link].*; import [Link]; Public class DDWrite { public static void main(String argv[]) { SessionDescriptor sd = new SessionDescriptor(); [Link](Customer); [Link](CustomerHome); [Link](CustomerRemote); Properties p = new Properties(); [Link](myprop1, myval0; [Link](p); [Link](0); contd
45
[Link]([Link] ESS_SESSION) try { FileOutputStream fos = new FileOutputStream ([Link]); ObjectOutputStream oos = new ObjectOutputStream (fos); [Link](sd); [Link](); } catch (IOException ioe) { }
}} [Link] serialized deployment descriptor WriteOBject () performs actual serialization
46
Create a manifest (6)&ejb-jar(7) &Deployment (8)
Contains information about the contents of a jar
file
Name:directory/ [Link]
Enterprise-Bean: True
Create an ejb-jar file with
jar cmf (manifest file name) (name of the jar)(the
directory to include in the jar file
Deployment with deployment tool
47
Writing a client(9)
import project directory; import [Link].*; import [Link].*; Public class HelloClient { public static void main(String argv[]) { try { InitialContext ic = new InitialContext(); CustomerHome home= (CustomerHome) [Link](CustomerHome); Customer cust = [Link](); String name = [Link](Suriya); S.O.P. (returned + name); [Link](); } catch ([Link] e) { } catch ([Link] e) {} catch ([Link] e) {} catch ([Link] e) {}} }
48
Run the client according to the webserver launched
Home Interface
Defined by Bean developer Implemented by server tools (autogenerated)
Must extend interface EJBHome
EJBMetaData getEJBMetaData() void remove(Handle ejbHandle) void remove(Object primaryKey)
Must provide your own create() methods
Foo create() Foo create(Bar b, Baz z)
49
Home Interface: Entity Beans
Entity Beans are persistent, therefore they need
more than a create method Need findXXX methods
public Foo findByPrimaryKey(Object key); public Foo findByBar(Bar bar); public Enumeration findOverdrawnAccounts();
Implement ejbFindXXX methods in bean
N.B.: find in home interface, ejbFind in Bean
50
Remote Interface
Written by developer Defines methods accessible by client
Your business methods go here
extends [Link]
standard methods provided by all EJBs getEJBHome(), getPrimaryKey(), getHandle(),
remove(), isIdentical(EJBObject obj)
51
Interfaces and Implementations
Remote Interface deposit() getBalance() EJBObject getEJBHome() getPrimaryKey() getHandle() isIdentical() remove() deposit() getBalance()
52
Home Interface create() remove()
EJB ejbCreate() ejbRemove() ejbActivate() ejbPassivate() deposit() getBalance()
Beans and Persistence
Persistence
Container-Managed
Persistence
Server reads values from your bean
Server stores/loads data for you
Very easy to write - just define data and server
magically takes care of persistence
54
Container-Managed Persistence (CMP)
Persistence is automatic
inserts, updates, and deletes are automatic
transactions managed automatically
server reads/writes your bean instance variables Server also informs you before/after it's done
something
you implement callback methods
55
Container-Managed Persistence (CMP) cont.
Easier to write beans
Focus on business logic, not persistence
But, requires sophisticated, vendor-specific data
mapping tools
Components more portable
not backend-specific
shrink-wrapped components
56
Bean-Managed Persistence
Bean-Managed Persistence
You code access database directly Callback methods dictate when to insert, update,
delete
More control over persistence, performance Much harder to write
Dont need sophisticated data mapping tools
57
Entity Beans
Model entities in a system represent their data and associated behavior
one or many relational database tables an object in an object database an entity in a legacy system
Nouns: People, Places or Things Customer, Employee, Student City, Building, Hotel Room Order, Organization, Health Benefit
58
Online Resources
jGuru EJB FAQ
[Link]
Sun EJB Page
[Link]
EJBNow
[Link]
59
Remote Interface
import [Link]; import [Link];
public interface Customer extends EJBObject {
public String getName() throws RemoteException; public void setName(Name name) throws RemoteException;
public Address getAddress() throws RemoteException;
public void setAddress(Address address) }
throws RemoteException;
60
Home Interface
import import import import [Link]; [Link]; [Link]; [Link];
public interface CustomerHome extends EJBHome { // required in session bean also public Customer create(Integer customerNumber) throws RemoteException, CreateException; //not required in session bean public Customer findByPrimaryKey(Integer customerNumber) throws RemoteException, FinderException;
public Enumeration findByZipCode(int zipCode) throws RemoteException, FinderException;
}
61
Bean Class
import [Link];
public class CustomerBean implements EntityBean { Address myAddress; Name myName; CreditCard myCreditCard; public Name getName() { return myName; } public void setName(Name name) { myName = name; } public Address getAddress() { return myAddress; } public void setAddress(Address address) { myAddress = address; } ... }
62