7/31/2019 Ejb Overview
1/62
Enterprise JavaBeansFundamentals
7/31/2019 Ejb Overview
2/62
Agenda
2
Enterprise JavaBeans defined
EJB and Distributed Computing
EJB Architecture
Entity beans Session bean
Deployment
EJB Clients
7/31/2019 Ejb Overview
3/62
Enterprise JavaBeans: Defined
7/31/2019 Ejb Overview
4/62
What is Enterprise JavaBeans
4
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.
7/31/2019 Ejb Overview
5/62
In English Please!
5
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 TransactionalMonitors Similar to CICS | TUXEDO
A complete environment for a distributed object
7/31/2019 Ejb Overview
6/62
Enterprise JavaBeans
6
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
7/31/2019 Ejb Overview
7/62
WORA
7
Write-Once, Run Anywhere within Middleware
Middleware provides all services
Instance management, transactions, concurrency,persistence
Beans stay simple!
7/31/2019 Ejb Overview
8/62
EJB Advantages
8
With EJB, you can write a business object andeasily make it
Persistent
Distributed
Transactional
Secure
Multithreaded
7/31/2019 Ejb Overview
9/62
Persistent
9
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)
7/31/2019 Ejb Overview
10/62
Transactional
10
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
7/31/2019 Ejb Overview
11/62
Secure
11
SSL/RMI protects transmitted data
Client-Server architecture protects
proprietary code
backend database
SSL authenicates client, server
ACLs provide fine-grained control of access toobjects, methods, services
7/31/2019 Ejb Overview
12/62
Multithreaded
12
Programmer delegates all responsibility formultithreading to server
Programmer literally cant spawn a thread
Program designer and/or sysadmin establishesmultithreading policies
Server enforces them invisibly
7/31/2019 Ejb Overview
13/62
Naming Services
13
JNDI
Wrapper for many naming services
CORBA, RMI, etc.
7/31/2019 Ejb Overview
14/62
CORBA and EJB
14
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
7/31/2019 Ejb Overview
15/62
EJB Architecture
7/31/2019 Ejb Overview
16/62
EJB Roles
16
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 EJBcomponents with other software to make acomplete application
Deployer:modifies and deploys beans in EJBserver
Organization-specifics, ie security
7/31/2019 Ejb Overview
17/62
EJB Roles (cont.)
17
Server providerprovides Server run-time Container provider:provides tools and containers
Creates container classes that wrap bean
Manage installed beans
System administrator- one who manages theapplication after it has been deployed into a targetenvironment.
7/31/2019 Ejb Overview
18/62
The EJB Container
18
Think of the container as the server, holding yourobjects
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 containerinterface to get services
Containers provide JNDI services too
7/31/2019 Ejb Overview
19/62
19
EJBProvider
ApplicationAssembler
App Server/EJB Container
Provider
Deployer
System
Administrator
7/31/2019 Ejb Overview
20/62
Session Beans
20
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
7/31/2019 Ejb Overview
21/62
Stateless Session Beans
21
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
7/31/2019 Ejb Overview
22/62
Stateful Session Beans
22
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
7/31/2019 Ejb Overview
23/62
EJB Conversation
23
Finding the Bean Getting access to a bean
Calling the beans methods
Getting rid of the bean
7/31/2019 Ejb Overview
24/62
Finding the bean
24
Use naming service (associates a symbolic namewith an object)
Use JNDI to provide a uniform interface to allnaming services or CORBAs COS
Naming Services
DNS
UNIX /etc/hosts file system
7/31/2019 Ejb Overview
25/62
Getting access to bean
25
Naming lookup returns reference to homeinterface object
Client uses the home interface to find existing EJBinstances or create new one.
Look up returns reference to remote Interface
object
Client uses remote interface to interact with EJBobjects
7/31/2019 Ejb Overview
26/62
Calling the bean and getting rid of it
26
Invoke the public methods of bean Destroying by remove()
Stateful session container discard it and use thespace for other bean
Stateless session returns the instance to a pool Entity remove the underlying object from
persistent storage ie. database
7/31/2019 Ejb Overview
27/62
27
Building and deploying EJBs
7/31/2019 Ejb Overview
28/62
Building and deploying EJBs
28
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
Function of a Deployment
7/31/2019 Ejb Overview
29/62
Function of a DeploymentDescriptor
29
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
7/31/2019 Ejb Overview
30/62
Deployment Descriptor
30
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 ormethod
For Entity beans, a list of container-managedfields
For session beans, a value denoting stateful orstateless
Programming: Interfaces and
7/31/2019 Ejb Overview
31/62
g gClasses
31
Home Interface (1) Extends javax.ejb.EJBHome
Provides remote access to create, find, remove beans
Remote Interface (2)
Extends javax.ejb.EJBObject Provides remote access to business methods
Bean Class EJB Implementation class (3) Extends a javax.ejb.EnterpriseBean type
Implements business logic and other functionality
EJB Architecture
7/31/2019 Ejb Overview
32/62
EJB Architecture
32
Implements
Invokes
Creates / uses
Client
Server
Home Interface(Factory)
EJB Object
(Wrapper) Enterprise
Java Bean
(Biz Logic)
Remote
Interface
Container
RMIRMI
Naming Service
You write this
Bean provider: What to write?
7/31/2019 Ejb Overview
33/62
Bean provider: What to write?Eg. Stateless Session Bean
33
Remote Interface
extend EJBObject interface
Define business method signatures
Home Interface extend EJBHome interface
Define create signatures
May define findBy signatures for entities
7/31/2019 Ejb Overview
34/62
Remote Interface
import javax.ejb.EJBObject;
import java.rmi.RemoteException;
public interface Customerextends EJBObject {
public String getName(String n) throws RemoteException;
}
34
7/31/2019 Ejb Overview
35/62
Functionality of remote interface
35
Container generates a class implementingCustomer interface during deployment time
The class passes method invocations to the EJBimplementation 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())
Home Interface
7/31/2019 Ejb Overview
36/62
Home Interface
36
import javax.ejb.EJBHome;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import java.rmi.RemoteException;
public interface CustomerHome extends EJBHome {
public Customercreate()throws RemoteException,CreateException;
}
7/31/2019 Ejb Overview
37/62
Functionality of Home interface
37
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 instantiatedobjects
Stateless only one create() with no arguments
Must be public
Return type must be the type of the remoteinterface
Throws clause must include RemoteException andCreateException
7/31/2019 Ejb Overview
38/62
Other method signature of Home interface
38
remove() allow a client to delete EJB instances byits handle or its primary key
getEJBMetaData returns an object the
implements the EJBMetaData
Bean implementation:What to write
7/31/2019 Ejb Overview
39/62
Bean implementation:What to write(cont.)?
39
Enterprise Bean Class
implement EntityBean or SessionBean
Implement business method signatures
Does not need to implement Remote Interface
not abstract
Implement ejbCreate methods matching Homecreate One ejbCreate for every Home.create
N.B.: create in home interface, ejbCreate in Bean
Bean Class
7/31/2019 Ejb Overview
40/62
40
import javax.ejb.*;
public class CustomerBean implements SessionBean
{
SessionContext ctx;
public void ejbCreate() { }
public Name getName(String n)
{return How are you, + n;
}
public void ejbRemove() { }
public void ejbPassivate() { }public void ejbActivate() { }
public void setSessionContext(SessionContext ctx)
{ this.ctx = ctx;}
}
Session bean method signatures
7/31/2019 Ejb Overview
41/62
Session bean method signatures
41
ejbActivate() -called by container after sessionbeans state has been restored from semi-persistent storage
ejbPassivate() called by container beforeswapping the object out to semi persistent storage
ejbRemove() invoked as result of client callingthe remove()
setSessionContext()
Container passes context object to session bean atthe 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
7/31/2019 Ejb Overview
42/62
42
ejbCreate()
Public
Void return type
Number and type of arguments of ejbCreate() mustsame as the number and type of arguments in thecreate() method
No need of throwing exceptions bcos exceptions
are thrown from create() method
g
7/31/2019 Ejb Overview
43/62
43
Compile (4)Remote Interface
Home InterfaceImplementation class
7/31/2019 Ejb Overview
44/62
Create a session descriptor (5)
44
SessionDescriptor class Specifies the deployment environment
Deployer deserializes the instance of Sessiondescriptor and uses the information it contains to
deploy the bean
7/31/2019 Ejb Overview
45/62
45
import javax.ejb.deployment.*;;
import java.io.*;
import java.util.Properties;Public class DDWrite
{
public static void main(String argv[])
{
SessionDescriptor sd = new SessionDescriptor();sd.setEnterpriseBeanClassName(Customer);
sd.setHomeInterfaceClassName(CustomerHome);
sd.setRemoteInterfaceClassName(CustomerRemote);
Properties p = new Properties();
p.put(myprop1, myval0;sd.setEnvironmentProperties(p);
sd.setSessionTimeout(0);
contd
sd setStateManagementType(SessionDescriptor STATEL
7/31/2019 Ejb Overview
46/62
46
sd.setStateManagementType(SessionDescriptor.STATELESS_SESSION)
try {
FileOutputStream fos = new FileOutputStream(foo.ser);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(sd);
oos.close();}
catch (IOException ioe)
{
}
}}
Foo.ser serialized deployment descriptor
WriteOBject () performs actual serialization
Create a manifest (6)&ejb-jar(7)
7/31/2019 Ejb Overview
47/62
&Deployment (8)
47
Contains information about the contents of a jarfile
Name:directory/ CustomerBeanDD.ser
Enterprise-Bean: True
Create an ejb-jar file with
jar cmf (manifest file name) (name of the jar)(thedirectory to include in the jar file
Deployment with deployment tool
Writing a client(9)Run the client according
7/31/2019 Ejb Overview
48/62
48
import project directory;
import java.rmi.*;
import javax.naming.*;Public class HelloClient
{ public static void main(String argv[])
{ try {
InitialContext ic = new InitialContext();
CustomerHome home= (CustomerHome) ic.lookup(CustomerHome);Customer cust = home.create();
String name = cust.getName(Suriya);
S.O.P. (returned + name);
cust.remove();
} catch (java.rmi.RemoteException e) { }catch (javax.ejb.CreateException e) {}
catch (javax.ejb.RemoveException e) {}
catch (javax.naming.NamingException e) {}} }
Run the client according
to the webserver
launched
Home Interface
7/31/2019 Ejb Overview
49/62
o e te ace
49
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)
Home Interface: Entity Beans
7/31/2019 Ejb Overview
50/62
y
50
Entity Beans are persistent, therefore they needmore 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
Remote Interface
7/31/2019 Ejb Overview
51/62
51
Written by developer Defines methods accessible by client
Your business methods go here
extends javax.ejb.EJBObject
standard methods provided by all EJBs
getEJBHome(), getPrimaryKey(), getHandle(),remove(), isIdentical(EJBObject obj)
Interfaces and Implementations
7/31/2019 Ejb Overview
52/62
p
52
EJBObjectgetEJBHome()getPrimaryKey()
getHandle()isIdentical()
remove()deposit()
getBalance()
Remote Interface
deposit()getBalance()
EJBejbCreate()
ejbRemove()ejbActivate()
ejbPassivate()deposit()getBalance()
Home Interface
create()remove()
7/31/2019 Ejb Overview
53/62
Beans and Persistence
P i t
7/31/2019 Ejb Overview
54/62
Persistence
54
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
Container-Managed Persistence(CMP)
7/31/2019 Ejb Overview
55/62
(CMP)
55
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 donesomething you implement callback methods
Container-Managed Persistence(CMP) t
7/31/2019 Ejb Overview
56/62
(CMP) cont.
56
Easier to write beans Focus on business logic, not persistence
But, requires sophisticated, vendor-specific datamapping tools
Components more portable not backend-specific
shrink-wrapped components
Bean Managed Persistence
7/31/2019 Ejb Overview
57/62
Bean-Managed Persistence
57
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
Entity Beans
7/31/2019 Ejb Overview
58/62
Entity Beans
58
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
Online Resources
7/31/2019 Ejb Overview
59/62
Online Resources
59
jGuru EJB FAQ http://www.jguru.com/faq/EJB
Sun EJB Page
http://java.sun.com/products/EJB
EJBNow http://www.ejbnow.com/
Remote Interface
7/31/2019 Ejb Overview
60/62
import javax.ejb.EJBObject;
import java.rmi.RemoteException;
public interface Customerextends 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
7/31/2019 Ejb Overview
61/62
61
import javax.ejb.EJBHome;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import java.rmi.RemoteException;
public interface CustomerHome extends EJBHome {
// required in session bean also
public Customercreate(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;
}
Bean Classimport javax.ejb.EntityBean;
7/31/2019 Ejb Overview
62/62
62
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;
} ...
}