Академический Документы
Профессиональный Документы
Культура Документы
Session 1 : Introduction
Session 2 : Session Beans
Session 3 : Entity Beans
Session 4 : MDBeans and Services
Distributed Object
Continued...
Distributed Object
Enterprise Java
EJBs have stubs and skeletons that are generated for marshalling.
Types of EJB
Session Beans
--Stateless Beans
--Stateful Beans
Entity Beans
--Bean Managed Persistent Entity Beans
--Container Managed Persistent Entity Beans
Message Driven Beans
Constitutes of EJB
Local Interfaces The clients call Enterprise Beans through their local
objects rather than remote EJB Objects. These local objects
implement local interface rather than a remote interface.
Enterprise Bean class This is the class which contains all the logic.
This is a simple java class that confirms to a well-defined interface
and obeys certain rules.
Continued..
Primary Key The primary key is a very simple class that provides a
pointer into a database; Only entity beans need a primary key. This
class must implment java.io.Serializable (so the entity bean can
automatically be sent to persistent storage)
Constitutes of EJB
Vendor Specific Files Each EJB Server vendor may require that you
include additional files specific to that vendor, such as XML files, text
files or binary files.
EJB Jar File An EJB jar file is compressed file that contains everything
that we have described. It is the unit of deployment and is given to the
application server.
Session Beans
Stateful session beans are to be used to
Hold business logic specific to a single client
Represent non-persistent state
Use as a Facade, single point of entry
Representing workflow between business objects
Shopping cart bean example
Session Beans
Entity Beans
Entity Beans
Primary key class is not needed if primary key is a single field that could
be java class (for example, Integer).
EJB Architecture
EJB Server
EJB container
Home
Interface
Home
Object
Enterprise
Java Bean
EJB Client
Security
EJB
Object
Transaction
Service (JTE)
Remote
Interface
Naming Service
(JNDI)
Invoke Business
methods
of EJB
Messaging
Locate, Create
and Remote,
instance of EJB
Databases
Ejb home object is a lot like the Ejb object. Its another class thats
generated automatically when you install an enterprise bean in a
container.It implements all the methods defined by the home interfaces
and is responsible for locating,creating and removing enterprise beans.
Architectural Roles
Architectural Roles
Server & Container Provider In most of the times the server and
container would be provided by a single vendor. The EJB container
(Application Server) is the runtime environment in which the beans live.
The container supplies middleware services to the beans and manage
them.
EJB..contd
Session Beans
Stateless Beans
Does not
exist
ejbRemove
Method -ready
pool
Enterprise Java Beans
Stateful Beans
Does not
exist
create (args)
ejbRemove
timeout
1.
2.
3.
newInstance
setSessionContext
ejbCreate(args)
remove
or timeout
ejbPassivate
Passivate
Method ready
ejbActivate
EnterpriseBean Interface
package learningpatterns.ejb.calculator;
import javax.ejb.*;
public class CalculatorBean implements SessionBean {
private SessionContext m_ctx = null;
public void ejbActivate() {}
public void ejbPassivate() {}
public void ejbRemove() {}
public void setSessionContext(SessionContext ctx) {
m_ctx = ctx;
}
// More to follow
Enterprise Java Beans
The bean class must define all the methods in the remote interface
They must have the same signature
The one difference is that they do not need to throw a
RemoteException
These methods do the actual work of your bean
They will be invoked when someone invokes the corresponding
method through the EJBObject
ejbCreate() methods
The bean class must define all the create methods in the home
interface
The name of these methods must be ejbCreate
They must be public and have the same arguments as in the home
interface
They must return void
The arguments must be legal for Java RMI
They may, but do not need to throw a RemoteException
They may throw a CreateException
They may throw application specific exceptions
Deployment Overview
Continued..
Deployment Descriptor
Deployment Descriptor
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>calculator</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
<home>
The fully qualified class name of the home interface
<remote>
The fully qualified class name of the remote interface
<ejb-class>
The fully qualified class name of the bean class (that implements
the business methods).
<session-type>
For a session bean describes if it is stateless or stateful
<transaction-type>
Defines the transaction management type of a bean (Container or
Bean)
Continued ..
<assembly-descriptor>
Defines how a bean is used in an application. Describes the
security roles and transactional attributes of a bean
<container-transaction>
Defines which transactional attributes apply to which methods
Well cover transactions more later
<?xml version="1.0"?>
<!DOCTYPE weblogic-ejb-jar PUBLIC '-//BEA Systems, Inc.//DTD
WebLogic 5.1.0 EJB//EN'
'http://www.bea.com/servers/wls510/dtd/weblogic-ejb-jar.dtd'>
<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>calculator</ejb-name>
<caching-descriptor>
<max-beans-in-free-pool>100</max-beans-in-free-pool>
</caching-descriptor>
<jndi-name>JavaConference.CalculatorHome</jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
Use the lookup method of the Context interface to get a home interface
reference
public Object lookup(String name);
We have set up the following JNDI name in our Calculator bean jar
file
JavaConference.CalculatorHome
Cast the return value to the home interface type
To be compatible with RMI over IIOP you cant use direct
casting because IIOP (CORBA) stubs arent necessarily
created in an inheritance hierarchy
javax.rmi.PortableObject contains a method called narrow that
either returns an object that can be safely cast or throws a
ClassCastException
Continued..
The EJBs remote interface defines the methods that can be called from
a client
In the case of the calculator example, the interface contains an add and
a sub method:
public int add(int i1, int i2) throws
RemoteException;
public int sub(int i1, int i2) throws
RemoteException;
Sample Code fragment:
System.out.println(6 + 5 = + calc.add(6,5));
System.out.println(6 - 5 = + calc.sub(6,5));
EJB .contd
Entity Bean
Entity Beans are EJBs that present an object view of persistent data
and are
shared by multiple clients
transactional
long lived (i.e., they live as long as the data)
able to survive a server crash
Entity beans usually represent data in a relational database
The data could be stored in an object database
An entity bean can also be used to encapsulate the behavior of a
non-EJB application
Legacy applications
Connector API is being defined in EJB 2.0
The home interface is still the bean factory for entity beans
But now you also have to take into account that there is
underlying data
For entity beans, create methods in the home interface add a new row
to the underlying data
They return a reference (EJBObject) to the bean just like with
session beans
They will likely take data which is used to create the bean
Assume we need an account number and initial balance to create
an account. The account home might have the following create
method:
Remote Interface
Just like with session beans, the remote interface for an entity bean
defines the business methods that are available to the client
For example, the remote interface for an account object might look
like the following:
public interface Account extends EJBObject {
public void deposit(double amount) throws
RemoteException;
public void withdraw(double amount) throws
RemoteException,
ProcessingErrorException;
public double getBalance() throws
RemoteException;
public java.util.Date getOpenDate() throws
RemoteException;
public String getName() throws RemoteException;
}
Primary Key
- Continued..
-AccountBean
package learningpatterns.ejb.bank;
import javax.ejb.*;
public class AccountBean implements EntityBean {
public
public
public
public
int
m_id;
double
m_balance;
String
m_name;
java.sql.Date m_open_date;
-AccountPK
// Primary Key Class for AccountBean
package learningpatterns.ejb.bank;
public class AccountPK implements java.io.Serializable {
public int m_id;
public AccountPK() {
super();
}
public AccountPK(int id) {
super();
this.m_id = id;
}
public int hashCode() {
Integer i = new Integer(m_id);
return i.hashCode();
}
public boolean equals(Object obj) {
AccountPK compareTo = (AccountPK) obj;
return m_id == compareTo.m_id;
}
}
-Create Methods
For BMP
Should actually create row in database
Return value is the primary key
For CMP
Should initialize the instance variables from the passed in
arguments
Doesnt go to database
-Finder Methods
For BMP
There is a corresponding method in the bean class
This method starts with the prefix ejbFind and has the same suffix
part and arguments as in the home interface
The return value is a PrimaryKey or enumeration of
PrimaryKeys
The container constructs the EJBObjects from the primary key
and returns them to the client
public class AccountBean implements EntityBean {
//
public Enumeration ejbFindByMinBalance (double
minBalance)
throws RemoteException, FinderException {}
}
-Finder Methods
For CMP
The implementations are written by the container
There is no corresponding ejbFind in the bean
The vendor must have some way of specifying the semantics of
finders
-ejbRemove()
-Business Methods
ejbCreate()
insert
ejbfindByxxx()
select
ejbRemove()
delete
ejbStore()
update
ejbLoad()
select
-ejb-jar.xml - Part 1
<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD
Enterprise JavaBeans 1.1//EN'
'http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd'>
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>account</ejb-name>
<home>learningpatterns.ejb.bank.AccountHome</home>
<remote>learningpatterns.ejb.bank.Account</remote>
<ejbclass>learningpatterns.ejb.bank.AccountBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-keyclass>learningpatterns.ejb.bank.AccountPK</prim...>
<reentrant>False</reentrant>
<cmp-field>
<field-name>m_id</field-name>
</cmp-field>
-ejb-jar.xml - Part 2
<cmp-field>
<field-name>m_name</field-name>
</cmp-field>
<cmp-field>
<field-name>m_open_date</field-name>
</cmp-field>
<cmp-field>
<field-name>m_balance</field-name>
</cmp-field>
</entity>
</enterprise-beans>
<assembly-descriptor>
...
</assembly-descriptor>
</ejb-jar>
Enterprise Java Beans
-weblogic-ejb-jar - Part 1
<?xml version="1.0"?>
<!DOCTYPE weblogic-ejb-jar PUBLIC '-//BEA Systems, Inc.//DTD
WebLogic 5.1.0 EJB//EN'
'http://www.bea.com/servers/wls510/dtd/weblogic-ejbjar.dtd'>
<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>account</ejb-name>
<caching-descriptor>
<max-beans-in-cache>1000</max-beans-in-cache>
</caching-descriptor>
<persistence-descriptor>
<persistence-type>
<type-identifier>WebLogic_CMP_RDBMS</typeidentifier>
<type-version>5.1.0</type-version>
<type-storage>META-INF/weblogic-cmp-rdbmsjar.xml</type...>
</persistence-type>
Enterprise Java Beans
-weblogic-ejb-jar - Part 2
<persistence-use>
<type-identifier>WebLogic_CMP_RDBMS</typeidentifier>
<type-version>5.1.0</type-version>
</persistence-use>
</persistence-descriptor>
<jndi-name>JavaConference.AccountHome</jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
-weblogic-cmp-rdbms-jar.xml - Part 1
<!DOCTYPE weblogic-rdbms-bean PUBLIC
'-//BEA Systems, Inc.//DTD WebLogic 5.1.0 EJB RDBMS
Persistence//EN'
'http://www.bea.com/servers/wls510/dtd/weblogic-rdbmspersistence.dtd'>
<weblogic-rdbms-bean>
<pool-name>BankPool</pool-name>
<table-name>Account</table-name>
<attribute-map>
<object-link>
<bean-field>m_id</bean-field>
<dbms-column>ID</dbms-column>
</object-link>
<object-link>
<bean-field>m_name</bean-field>
<dbms-column>Name</dbms-column>
</object-link>
...
</attribute-map>
Enterprise Java Beans
-weblogic-cmp-rdbms-jar.xml - Part 2
<finder-list>
<finder>
<method-name>findByMinBalance</method-name>
<method-params>
<method-param>double</method-param>
</method-params>
<finder-query><![CDATA[(>= m_balance $0)]]></finderquery>
</finder>
</finder-list>
<options>
<use-quoted-names>false</use-quoted-names>
</options>
</weblogic-rdbms-bean>
-Connecting to Database
-Database Properties
weblogic.jdbc.connectionPool.BankPool=\
url=jdbc:cloudscape:Bank,\
driver=COM.cloudscape.core.JDBCDriver,\
initialCapacity=1,\
maxCapacity=2,\
capacityIncrement=1,\
props=user=none;password=none;server=none
# Add a Transactional DataSource for the connection pool:
# It creates a JNDI entry named weblogic.jdbc.jts.BankPool
weblogic.jdbc.TXDataSource.weblogic.jdbc.jts.BankPool=BankPool
# Add an ACL for the connection pool:
weblogic.allow.reserve.weblogic.jdbc.connectionPool.BankPool=ever
yone
-ejb-jar.xml
<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD
Enterprise JavaBeans 1.1//EN'
'http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd'>
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>account</ejb-name>
.
<persistence-type>Bean</persistence-type>
<resource-ref>
<res-ref-name>jdbc/BankPool</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
-weblogic-ejb-jar.xml
<?xml version="1.0"?>
<!DOCTYPE weblogic-ejb-jar PUBLIC '-//BEA Systems, Inc.//DTD
WebLogic 5.1.0 EJB//EN'
'http://www.bea.com/servers/wls510/dtd/weblogic-ejbjar.dtd'>
<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>account</ejb-name>
<caching-descriptor>
<max-beans-in-cache>1000</max-beans-in-cache>
</caching-descriptor>
-weblogic-ejb-jar.xml
<reference-descriptor>
<resource-description>
<res-ref-name>
jdbc/BankPool
</res-ref-name>
<jndi-name>
weblogic.jdbc.jts.BankPool
</jndi-name>
</resource-description>
</reference-descriptor>
<jndi-name>JavaConference.AccountHome</jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
-Weblogic DD Details
<reference-descriptor>
Sets up a resource reference
<resource-description>
Sets up a particular resource
<res-ref-name>
Name of resource being set up
<jndi-name>
JNDI name to map this resource to
I.e. - We set up a DataSource in the weblogic.properties file with
the name weblogic.jdbc.jts.BankPool
Here, we map the JNDI environment context name
jdbc/BankPool to the object referenced by
weblogic.jdbc.jts.BankPool
-Getting a Connection
-....Getting a Connection
catch(SQLException sqle) {
throw sqle;
}
catch(Exception e) {
throw new SQLException(e.getMessage());
}
return con;
}
-ejbFindByPrimaryKey
// Given a Primary Key, loads the bean from the persistent
store
public AccountPK ejbFindByPrimaryKey(AccountPK pk)
throws
FinderException, RemoteException {
if (pk == null)
throw new FinderException ("primary key cannot be
null");
// Load from the database
refresh(pk);
// Print out some debugging
System.out.println("ejbFindByPrimaryKey (" + pk.m_id +
"found");
// return the primary key
return pk;
}
-ejbLoad
EJB ..contd
JMS
does not
exist
ejbRemove()
onMessage(msg)
method -ready
pool
Enterprise Java Beans
MDB Features
A middle man sits between the client and the server. And the client
does not need to wait when performing a request.
There can be more than one message producers as well as message
consumers.
Message Driven Beans do not have return Values.
They can not send exceptions back to clients.
Application Client
import javax.naming.*;
import javax.jms.*;
public class Client{
public static void main(String args[]) throws Exception{
Context ctx = new InitialContext(System.getProperties());
queueConnectionFactory = (queueConnectionFactory) ctx.lookup
(javax.jms.MyQueueConnectionFactory");
queueConnection =
queueConnectionFactory.createQueueConnection();
queueSession = queueConnection.createQueueSession(false,
Session.AUTO_ACKNOWLEDGE);
queue = (queue)
jndiContext.lookup("java:comp/env/jms/QueueName");
queueSender = queueSession.createSender(queue);
message = queueSession.createTextMessage();
for (int i = 0; i < NUM_MSGS; i++) { message.setText("This is
message " + (i + 1)); System.out.println("Sending message: " +
message.getText()); queueSender.send(message);
}
}
}
Bean Class
import javax.ejb.*;
Import javax.kms.*;
public class SimpleMessage implements
MessageDrivenBean,MessageListener{
protected MessageDrivenContext ctx;
Public void setMessageDrivenContext(MessageDrivenContext ctx){
this.ctx=ctx;}
public void ejbCreate(){}
public void onMessage(Message inMessage) {
TextMessage msg = null;
try {
if (inMessage instanceof TextMessage)
{msg = (TextMessage) inMessage;
System.out.println(" Message received: " + msg.getText()); }
else {
System.out.println ("wrong type: " +
inMessage.getClass().getName()); }
}
Enterprise Java Beans
Bean Class
catch (JMSException e) {
e.printStackTrace();
mdc.setRollbackOnly(); }
catch (Throwable te) {
te.printStackTrace();
}
}
public void ejbRemove(){}
}
}
Deployment Descriptor
<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise
JavaBeans 1.1//EN' 'http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd'>
<ejb-jar>
<enterprise-beans>
<message-driven>
<ejb-name>SimpleBean</ejb-name>
<ejb-class>examples.SimpleBean,/ejb-class>
<transaction-type>container</transaction-type>
<message-driven-destination>
<destination-type>javax.jms.queue<destination-type>
</message-driven-destination>
</message-driven>
</enterprise-beans>
</ejb-jar>
Enterprise Java Beans
EJB ..contd
Session 5 : Services
Container Services
Database management
Database connection pooling
DataSource, offered by the J2EE server. Needed to access
connection pool of the server.
Database access is configured to the J2EE server -> easy to
change database / database driver
Transaction management
Distributed transactions
J2EE server offers transaction monitor which can be accessed by
the client.
Services
Security management
Authetication
Authorization
encryption
Authentication
Persistence
Naming
Concurrency
Load Balancing
Transaction Properties
Transaction Attributes
Not Supported: Upon entering the method, any current transaction is
suspended for the duration of the invocation.
Required:
If there is no transaction active, then one will be
started upon entering the method. The transaction will be committed
before leaving the method if the container started it.
If there is a transaction already running, no new transaction will
be started.
Supports:
If a transaction is active work is done in the context of
that transaction. No new transactions are started.
Requires New: A new transaction will be started upon entering the
method even if there is a transaction active.
Mandatory: Upon entering the method, an exception is thrown if there is
no transaction active.
Never: This bean can never be involved in a transaction, an exception will
be thrown if a transaction is active.
Bean Managed: The bean itself controls the transaction. This option is
not available for Entity Beans.
Enterprise Java Beans
Transactional Isolation
Transactional Isolation
Isolation Level:
READ UNCOMMITED - DOES NOT OFFER ANY ISOLATION
GUARANTEES
READ COMMITED
Security
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>SecureEJB</ejb-name>
...
<security-role-ref>
<role-name>InternalTrusted</role-name>
<role-link>TrustedUser</role-link>
</security-role-ref>
</entity>
</enterprise-beans>
<assembly-descriptor>
<security-role>
<role-name>TrustedUser</role-name>
</security-role>
<method-permission>
<role-name>TrustedUser</role-name>
<method>
<ejb-name>SecureEJB</ejb-name>
<method-name>doSecureStuff</method-name>
</method>
</assembly-descriptor>
</ejb-jar>
Persistence
Connection pools
Naming
Concurrency
Load Balancing
Maximizes the usage of the computing resources of all of your
server machines
Essential to ensuring that the application is scalable
Fail over
A request may be redirected from one server to another because of
a machine or network failure
Necessary for critical, enterprise applications
EJB client
JMS client
Deployment
descriptors
OC4J
EJB
EJB
home EJB container
home
interface
object
EJB
comp.
interface
EJB
Local/
remote
object
JMS
Listener
SB
bean
Entity
bean
MDB
bean
Enterprise Services
Naming, Transactions, Security
Enterprise Java Beans
Database
Or
External
Apps