210
Introduction to EJB O’Reilly Conference on Java Westin Hotel - Santa Clara, California March 27, 2001 David Lewis [email protected] LearningPatterns.com Inc. 55 Broad Street, 18th Floor New York, NY 10004-2501 Tel: 212-487-9064 Toll free: 888-298-2677 Web: http://www.LearningPatterns.com Email: [email protected] E may, vao day coi co con nho nay ngon lam http://nhatquanglan.xlphp.net/

Lewis 2001 SLD Introduction EJB

Embed Size (px)

Citation preview

Page 1: Lewis 2001 SLD Introduction EJB

Introduction to EJB

O’Reilly Conference on Java

Westin Hotel - Santa Clara, CaliforniaMarch 27, 2001

David [email protected]

LearningPatterns.com Inc.55 Broad Street, 18th Floor New York, NY 10004-2501

Tel: 212-487-9064Toll free: 888-298-2677

Web: http://www.LearningPatterns.comEmail:

[email protected]

E may, vao day coi co con nho nay ngon lam http://nhatquanglan.xlphp.net/

Page 2: Lewis 2001 SLD Introduction EJB

2

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

C:\WINNT\hinhem.scr FC:\WINNT\hinhem.scr

Page 3: Lewis 2001 SLD Introduction EJB

3

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Tutorial Outline -• In this tutorial, we will cover the following topics:In this tutorial, we will cover the following topics:

Overview of J2EE Environment PropertiesOverview of EJB SecurityHigh-level EJB architecture EJB Programming Restrictions Remote & Home Interface API EJB 2.0 PreviewSession Bean Architecture and API TipsDeploymentClient View of a Session BeanStateless Session Bean LifecycleStateful Session BeansEntity Bean OverviewEntity Bean InterfacesEntity Bean ImplementationBean Managed PersistenceEntity Bean LifecycleTransactions and EJB

Page 4: Lewis 2001 SLD Introduction EJB

4

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Overview of J2EE -• J2EE’s Place within JavaJ2EE’s Place within Java• DefinitionDefinition• APIsAPIs• ArchitectureArchitecture• Commercial ProductsCommercial Products

Page 5: Lewis 2001 SLD Introduction EJB

5

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

J2EE’s Place within Java• Java consists of three separate platformsJava consists of three separate platforms

– Java 2 Micro Edition (J2ME)• Used on small devices such as PDAs (e.g., Palm Pilots) and Cell Phones• Sub-divided into profiles

– Java 2 Standard Edition (J2SE)• Used on PCs• Contains some APIs that are essential to enterprise applications (e.g., JDBC and

RMI)– Java 2 Enterprise Edition (J2EE)

• Used to build large scale three-tier enterprise applications• Depends upon J2SE• Contains enterprise-specific APIs such as EJB

Page 6: Lewis 2001 SLD Introduction EJB

6

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Definition• J2EE is a platform for building enterprise applications J2EE is a platform for building enterprise applications

that are portable, scalable, reliable, and securethat are portable, scalable, reliable, and secure• J2EE consists of several partsJ2EE consists of several parts

– J2EE Specification defines the APIs and how they interact– J2EE Compatibility Test Suite consists of standard tests to determine if a

particular product conforms to the standard– The J2EE Reference Implementation is Sun’s free implementation of J2EE

• Used to run the Compatibility Test Suite• Not optimized or supported for production applications• Good for training, prototyping, and understanding the specification

– J2EE Blueprint is a document from Sun that describes design guidelines for J2EE applications

• Model, view, controller (MVC) architecture• Sample application (Java Pet Store)

Page 7: Lewis 2001 SLD Introduction EJB

7

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

J2EE APIs• J2EE 1.2 uses the following APIsJ2EE 1.2 uses the following APIs

– Important APIs from J2SE• RMI Remote Method Invocation• JDBC Java Database Connectivity

– Enterprise APIs• JSP 1.1 Java Server Pages • Servlets 2.2 Servlet API• EJB 1.1 Enterprise JavaBeans• JNDI 1.2 Java Naming and Directory Interface• JDBC 2.0 Extensions Java Database Connectivity Extensions• RMI-IIOP 1.0 Remote Method Invocation over Internet Inter-

Orb Protocol• JMS 1.0 Java Message Service (implementation not

required for J2EE 1.2)• Java Mail 1.1 Java Mail• JTA 1.0 Java Transaction API• JAF 1.0 JavaBeans Activation Framework (email

attachments)

Page 8: Lewis 2001 SLD Introduction EJB

8

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

J2EE Architecture

BrowserJSP

EJB Database

J2EE Server

HTTP

RMI

JDBC

First Tier Second Tier Third Tier

Servlet

Page 9: Lewis 2001 SLD Introduction EJB

9

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Commercial Products• Since J2EE is an open standard, vendors compete on the Since J2EE is an open standard, vendors compete on the

quality of their implementationquality of their implementation– Price for performance– Support– Reliability– Scalability– Proprietary functionality– Vendor reputation and stability

• The products currently on the market support different The products currently on the market support different levels of the J2EE APIslevels of the J2EE APIs

• Most products are sold in a variety of editions (e.g. Most products are sold in a variety of editions (e.g. Weblogic Server and Weblogic Enterprise)Weblogic Server and Weblogic Enterprise)

Page 10: Lewis 2001 SLD Introduction EJB

10

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Overview of EJB -• What is EJBWhat is EJB• JavaBeans vs. EJBJavaBeans vs. EJB• EJB GoalsEJB Goals• Importance of EJBImportance of EJB

Page 11: Lewis 2001 SLD Introduction EJB

11

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

What is EJB• EJB is a server-side architecture for distributed, EJB is a server-side architecture for distributed,

transactional componentstransactional components– Enterprise Java Beans are:– Server side components– Transactional– Distributed

• EJB defines a server side framework for providing a EJB defines a server side framework for providing a core set of system services to Java componentscore set of system services to Java components– e.g., transaction, naming, persistence services

• EJB simplifies the building of multitier distributed EJB simplifies the building of multitier distributed object architecturesobject architectures– Where much of a system’s business logic is on the server – EJB shields the application programmer from many of the complex

system level issues of building these applications

Page 12: Lewis 2001 SLD Introduction EJB

12

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

EJB and Distributed Object Architectures• Distributed object architectures provide a network Distributed object architectures provide a network

communications layer communications layer – They allow invoking on objects outside the process they are in– RMI– CORBA– DCOM

• They do not necessarily provide other services in an They do not necessarily provide other services in an integrated wayintegrated way– They are often available– But you have to code them in yourself

• EJB is built on existing distributed object architecturesEJB is built on existing distributed object architectures– IN general, over RMI and/or CORBA

• It provides many additional integrated servicesIt provides many additional integrated services– Which makes the developers task easier

Page 13: Lewis 2001 SLD Introduction EJB

13

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

JavaBeans vs. EJB• JavaBeans - framework to create components suitable JavaBeans - framework to create components suitable

for manipulation in visual builder toolsfor manipulation in visual builder tools– Defines how to deal with properties, events, methods– Defines ways to customize JavaBeans– Defines a simple persistence mechanism (serialization)

• EJB - framework for building server side componentsEJB - framework for building server side components– Defines how to provide services– Defines how to create EJBs– Supports the building of multitier distributed object applications

Page 14: Lewis 2001 SLD Introduction EJB

14

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

EJB Goal• Framework for easily creating business objectsFramework for easily creating business objects

– That are distributed, transactional, and persistent

• Relieve developers from managingRelieve developers from managing– Low-level transaction and state management– Multi-threading and resource pooling– Security – Persistence and other complex APIs– However, there is still access to the low-level APIs for expert

level programmers

Page 15: Lewis 2001 SLD Introduction EJB

15

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

EJB Goal • Provide standard Java component architecture Provide standard Java component architecture

for building enterprise systemsfor building enterprise systems– Allow combining components developed using tools from

different vendors– Be compatible with existing server platforms, existing Java

APIs, and CORBA– Write once, run anywhere

Page 16: Lewis 2001 SLD Introduction EJB

16

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- High Level EJB Architecture -• RMI OverviewRMI Overview• How EJB WorksHow EJB Works• EJB ArchitectureEJB Architecture• The EJB ServerThe EJB Server• The EJB ContainerThe EJB Container• The Enterprise JavaBeanThe Enterprise JavaBean• The Deployment DescriptorThe Deployment Descriptor

Page 17: Lewis 2001 SLD Introduction EJB

17

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Remote Method Invocation (RMI)• Lets you invoke methods on remote objectsLets you invoke methods on remote objects

– Done through a local stub (proxy) object

• Supports seamless method invocation on objects in Supports seamless method invocation on objects in different virtual machinesdifferent virtual machines

• Supports callbacksSupports callbacks– Server-to-client method invocation

• Preserves Java’s safety and security mechanismsPreserves Java’s safety and security mechanisms

Page 18: Lewis 2001 SLD Introduction EJB

18

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

The RMI System Architecture

RMIMechanism

Application-Level

Transport

Remote Reference Layer

Stubs Skeletons

Client Server

Page 19: Lewis 2001 SLD Introduction EJB

19

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

How EJB Works• It’s All In The EJB Server/Container It’s All In The EJB Server/Container

– Enterprise Beans live in an EJB server/container which provides high level services

– Security, scalability, transactions, persistence, transport

• EJB developers only need deal with the application logic EJB developers only need deal with the application logic – The server & container:

• Take care of the high level services• Provide the interface to clients of enterprise Beans

• EJB can be thought of as RMI with container-provided EJB can be thought of as RMI with container-provided servicesservices

Page 20: Lewis 2001 SLD Introduction EJB

20

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

High Level EJB Architecture

• The EJB server provides low level services to the containerThe EJB server provides low level services to the container • The container provides services to the Enterprise Bean according The container provides services to the Enterprise Bean according

to the EJB spec, and mediates between the client and the Enterprise to the EJB spec, and mediates between the client and the Enterprise BeanBean

EJB Server

EJB Container

Enterprise BeanClient

Page 21: Lewis 2001 SLD Introduction EJB

21

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

The EJB Server• Manages EJB containers Manages EJB containers • Provides access to system level services Provides access to system level services

– As required by the EJB specification

• May also provide vendor specific servicesMay also provide vendor specific services– Generally part of some larger application environment– Some examples of EJB servers may be database servers & application

servers (e.g. Weblogic)– The interface between the server and container is not defined, so they

generally come bundled together– This interface may be defined in the future, enabling the creation of

containers runnable in any EJB server

Page 22: Lewis 2001 SLD Introduction EJB

22

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

The EJB Container• Provides services to enterprise beans as defined in the Provides services to enterprise beans as defined in the

EJB specEJB spec– Calls on the EJB server for these services – May also provide additional services– Manages enterprise beans and exposes their functionality to clients

• Third party vendors may write containers to an EJB Third party vendors may write containers to an EJB serverserver– Versant and TOPLINK for BEA/Weblogic– Not a large market for this currently

• No clear line between server and containerNo clear line between server and container– The container is a logical entity. It represents a set of services which may be

provided by a number of different classes or tools

Page 23: Lewis 2001 SLD Introduction EJB

23

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Container Provided Services• TransactionTransaction

– Container implements the desired transactional behavior based upon information provided by the bean developer and/or deployer

• ConcurrencyConcurrency– Container manages concurrent access to an EJB instance– Bean developer does not manage threads

• SecuritySecurity– Role-based application level security is integrated into the EJB programming

model– Declarative and programmatic security models are supported– Container authenticates access

• PersistencePersistence– Connection pools– CMP entity beans

Page 24: Lewis 2001 SLD Introduction EJB

24

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Container Provided Services• NamingNaming

– An EJB gets access to other EJBs and other resources (e.g., a resource factory) by looking it up in the naming services

– Eliminates hard-coding of names, makes the application more flexible

• Remote accessRemote access– Enables the distribution of an application across the network

• Fail overFail over– A request may be redirected from one server to another because of a machine

or network failure– Necessary for critical, enterprise applications

• Load BalancingLoad Balancing– Maximizes the usage of the computing resources of all of your server

machines– Essential to ensuring that the application is scalable

Page 25: Lewis 2001 SLD Introduction EJB

25

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Role of the Enterprise JavaBean• Provides application functionalityProvides application functionality

– Business logic

• Depends on the container for system level services Depends on the container for system level services – Instances are also created & managed by the container– Client access is also mediated by the container

• If a bean uses only standard container services, as If a bean uses only standard container services, as defined in the EJB spec, it can be deployed in any defined in the EJB spec, it can be deployed in any compliant EJB containercompliant EJB container

• Two main types of beans, session and entity Two main types of beans, session and entity

Page 26: Lewis 2001 SLD Introduction EJB

26

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Session Bean• Executes on behalf of a single clientExecutes on behalf of a single client• Relatively short livedRelatively short lived• Doesn’t represent shared data in a database, Doesn’t represent shared data in a database,

though it may update such datathough it may update such data• Does not generally survive EJB server crashesDoes not generally survive EJB server crashes• Can be transaction awareCan be transaction aware• Required by EJB 1.0 specRequired by EJB 1.0 spec

Page 27: Lewis 2001 SLD Introduction EJB

27

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Entity Bean• Represents shared, persistent data, usually in a databaseRepresents shared, persistent data, usually in a database• Is transactionalIs transactional• Allows shared access from multiple usersAllows shared access from multiple users• Can be long livedCan be long lived• Survives EJB server crashesSurvives EJB server crashes• Mandatory in EJB 1.1 specMandatory in EJB 1.1 spec

– Was optional in 1.0

Page 28: Lewis 2001 SLD Introduction EJB

28

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

What’s Not in a Bean• The following are provided by the container, and are not The following are provided by the container, and are not

programmed into the enterprise beanprogrammed into the enterprise bean– Transaction modes

• Although the bean writer may choose to manage transactions explicitly, this is almost always unnecessary

– Basic security• Programmatic security requires some code in the bean

– Remote invocation code– Persistence management (CMP)

• There is also information provided in a Deployment There is also information provided in a Deployment Descriptor (DD)Descriptor (DD)– The DD contains declarative information that is not coded into the bean

Page 29: Lewis 2001 SLD Introduction EJB

29

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Deployment Descriptor (DD)• Separates the creation of a bean into two partsSeparates the creation of a bean into two parts

– Coding and deployment– Allows postponing until deployment decisions that might not be known when

bean is coded– Allows you to specify attributes and allow container to generate code

• Not very well defined in EJB 1.0Not very well defined in EJB 1.0– The format is clumsy– A serialized instance of a class that implements a specific EJB interface– Not enough structure and detail in the DD specification– All information is jumbled together– Use vendor tools to create it

• EJB 1.1 DD specification is much clearerEJB 1.1 DD specification is much clearer– XML format– Separates DD into two sections– Structural information and application assembly information sections

Page 30: Lewis 2001 SLD Introduction EJB

30

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Deployment Descriptor Information• Structural informationStructural information

– Class names for the various parts of a bean– Specification information as to the type of bean (e.g. entity, session, etc.)– High level transaction information– Persistence management information– High level security information (security roles in EJB 1.1)

• Application assembly informationApplication assembly information– Environment properties– Detailed security information in 1.1– Detailed transaction information

Page 31: Lewis 2001 SLD Introduction EJB

31

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Remote & Home Interface API -• Remote InterfaceRemote Interface• EJBObject InterfaceEJBObject Interface• EJB Remote Interface and Bean ClassEJB Remote Interface and Bean Class• EJBHome InterfaceEJBHome Interface• EJB Home Interface and Bean ClassEJB Home Interface and Bean Class

Page 32: Lewis 2001 SLD Introduction EJB

32

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Remote Interface for an Enterprise Bean

• Is defined by the EJB developerIs defined by the EJB developer• Defines the bean's business methodsDefines the bean's business methods

– Defines the functionality visible to the outside world. This is the only functionality visible to clients

– The EJB’s remote interface must extend the javax.ejb.EJBObject interface, which extends java.rmi.Remote

– EJB remote interfaces are RMI remote interfaces– An EJB can only have one remote interface– For each method defined in the remote interface, there must be a

corresponding method defined in the bean class

• This remote interface is also called the EJBObject in This remote interface is also called the EJBObject in EJB-speakEJB-speak– Which is not a great name– It’s confusing

Page 33: Lewis 2001 SLD Introduction EJB

33

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

The Adapter Pattern• Converts the interface of a class into another interface Converts the interface of a class into another interface

clients expectclients expect– If we want to expose an objects functionality remotely, we can do it with a

remote adapter

ObjectClient

Ad

apte

r

Page 34: Lewis 2001 SLD Introduction EJB

34

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

The EJBObject• Clients interact with EJB Objects, and not with the Clients interact with EJB Objects, and not with the

enterprise bean itself.enterprise bean itself.– The EJBObject functions as a remote adapter, in addition to providing other

functionality– Think adapter when you see EJBObject

EJB Server

EJB Container

Enterprise BeanClientE

JB O

bje

ct

Page 35: Lewis 2001 SLD Introduction EJB

35

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Calculator Example• To illustrate the various concepts presented in this

section, we will use a calculator example• The calculator:

– Is a stateless session bean– Has a remote interface with two business methods:

• add accepts two integers and returns the sum• sub accepts two integers and returns the difference

Page 36: Lewis 2001 SLD Introduction EJB

36

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

The Calculator Remote Interfacepackage learningpatterns.ejb.calculator;

import javax.ejb.*;

import java.rmi.RemoteException;

public interface Calculator extends EJBObject

{

public int add(int i1, int i2) throws RemoteException;

public int sub(int i1, int i2) throws RemoteException;

}

Page 37: Lewis 2001 SLD Introduction EJB

37

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

EJBObject Interface• It is extended by all EJB remote interfacesIt is extended by all EJB remote interfacespublic interface javax.ejb.EJBObject extends java.rmi.Remote {

public EJBHome getEJBHome() throws java.rmi.RemoteException;

public Handle getHandle() throws java.rmi.RemoteException;

public Object getPrimaryKey() throws java.rmi.RemoteException;

public boolean isIdentical(EJBObject obj) throws java.rmi.RemoteException;

public void remove() throws java.rmi.RemoteException;

}

Page 38: Lewis 2001 SLD Introduction EJB

38

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

EJBObject Methods• EJBHome getEJBHome()

– Get the home interface associated with this EJBObject; the home interface can then be used to create additional EJBObjects

• Handle getHandle()– Get a handle on the EJBObject– Handles are serializable; therefore, their state can be written to a file or sent

across the network – Can be used to to later re-obtain a reference to the EJBObject

• Object getPrimaryKey()– For entity beans - we’ll cover this later

• boolean isIdentical(EJBObject obj)– Checks if given object is identical to the invoked object– Result depends upon the object instances and the type of bean. For example all

calculator EJBObjects are identical because calculator is stateless• void remove()

– Destroys the EJBObject

Page 39: Lewis 2001 SLD Introduction EJB

39

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Remote Interface Implementation• The container generates an implementation class for the The container generates an implementation class for the

remote interfaceremote interface– Bean writers don’t need to do this– It is done using an implementation specific tool provided by a container

vendor

• This remote implementation class is a remote (RMI) classThis remote implementation class is a remote (RMI) class– The application methods are invokeable via RMI– It is an adapter class with the work delegated to the bean

• The container tools generate the needed RMI classesThe container tools generate the needed RMI classes– The stub and skeleton files that are needed for RMI

• What is the actual EJBObject?What is the actual EJBObject?– An instance of the implementation class generated by the container

Page 40: Lewis 2001 SLD Introduction EJB

40

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Calculator Remote Interface

EJBObject getEJBHome() getHandle() getPrimaryKey() isIdentical(EJBOBject) remove()

“Bean class”CalculatorBean ejbCreate() ejbActivate() ejbPassivate() ejbRemove() setSessionContext(..)

add(int,int) sub(int,int)

Remote

“Remote interface”Calculator add(int,int) sub(int, int)

“EJBObject implementation”CalculatorImpl add(int,int) sub(int,int) getEJBHome() getHandle() getPrimaryKey() isIdentical(EJBObject) remove()

extends

extends

implements

delegates

API Interfaces

Bean Developer

Generated

Page 41: Lewis 2001 SLD Introduction EJB

41

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Client-Bean Communication

EJB Server

EJB Container

Enterprise BeanClient

EJB

Ob

ject

stu

b

skel

eto

n

Page 42: Lewis 2001 SLD Introduction EJB

42

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

The Home Interface• Defines life cycle methods for a beanDefines life cycle methods for a bean• Defined by the EJB developerDefined by the EJB developer• Clients gain access to an EJB through its home interfaceClients gain access to an EJB through its home interface

– There is a home interface for each bean– The home interface provides factory methods, named create methods, for the client– You can have multiple create methods with different signatures– For a session bean, at least one create method must be defined in the home interface– These factory methods return the remote interface type– Home interfaces extend the javax.ejb.EJBHome interface which extends

Remote– All create methods in the home interface must have a corresponding ejbCreate

method in the bean class

Page 43: Lewis 2001 SLD Introduction EJB

43

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

The Factory Method Pattern• Defines an interface for creating an object which is not Defines an interface for creating an object which is not

tied down to any implementation classtied down to any implementation class– This is necessary for EJB object creation– Client doesn’t know the exact type of the object it is getting– Client doesn’t know the exact type of the class creating the object

Page 44: Lewis 2001 SLD Introduction EJB

44

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Calculator Home Interfacepackage learningpatterns.ejb.calculator;

import javax.ejb.*;

import java.rmi.RemoteException;

public interface CalculatorHome extends EJBHome

{

// create method must throw a CreateException // and a RemoteExceptionpublic Calculator create()

throws CreateException, RemoteException;

}

Page 45: Lewis 2001 SLD Introduction EJB

45

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

EJBHome Interface• It is extended by all EJB home interfacesIt is extended by all EJB home interfacespackage javax.ejb;

import java.rmi.*;

public interface EJBHome extends Remote {

public EJBMetaData getEJBMetaData() throws RemoteException;public HomeHandle getHomeHandle() throws RemoteException;public remove(Handle handle) throws RemoteException;public remove(Object primaryKey) throws RemoteException;

}

Page 46: Lewis 2001 SLD Introduction EJB

46

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

EJBHome Methods• EJBMetaData getEJBMetaData()

– Get the EJBMetaData object for the EJB represented by this home• Metadata: class object for the home interface, class object for the remote

interface, bean type, etc.

• HomeHandle getHomeHandle()– Get a serializable reference to the home interface

• remove(Handle handle)– Remove the bean referenced by the given handle

• remove(Object primaryKey)– Remove the entity bean identified by the given primary key

Page 47: Lewis 2001 SLD Introduction EJB

47

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Home Interface Implementation• Implementation works exactly like the implementation of Implementation works exactly like the implementation of

the remote interfacethe remote interface– Class is generated by vendor tools– This home implementation class is a remote (RMI) class– The container tools generate the needed RMI classes– The actual Home object is an instance of the implementation class generated

by the container

Page 48: Lewis 2001 SLD Introduction EJB

48

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Stateless Session Bean & create• Only one create method allowedOnly one create method allowed

– For stateless session beans– It must take no arguments– Since the bean is stateless, it makes no sense to pass in arguments– How would the bean store or use them in a way that affected other calls– Container tools should check for this, and give an error message if you define

a create method with arguments for a stateless session bean

Page 49: Lewis 2001 SLD Introduction EJB

49

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Calculator Home Interface

EJBHome getEJBMetaData() getHomeHandle() remove(Handle) remove(Object)

“Bean class”CalculatorBean ejbCreate() ejbActivate() ejbPassivate() ejbRemove() setSessionContext(..)

add(int,int) sub(int,int)

Remote

“Home interface”CalculatorHome create()

“EJBHome implementation”CalculatorHomeImpl create() getEJBMetaData() getHomeHandle() remove(Handle) remove(Object)

extends

extends

implements

delegates

API Interfaces

Bean Developer

Generated

Page 50: Lewis 2001 SLD Introduction EJB

50

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Client-Home Communication

EJB Server

EJB Container

Enterprise Bean

Client

EJB

Ob

ject

stu

b

skel

eto

n

EJB

Ho

me

stu

b

skel

eto

n

EJB Server

Client

EJB

Ho

me

stu

b

skel

eto

n

EJB Container

create()

Page 51: Lewis 2001 SLD Introduction EJB

51

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Session Bean Architecture and API -• Defining Enterprise BeansDefining Enterprise Beans• Session BeansSession Beans• Stateful and Stateless BeansStateful and Stateless Beans• Passivation and ActivationPassivation and Activation• The SessionBean InterfaceThe SessionBean Interface• The Bean ClassThe Bean Class

Page 52: Lewis 2001 SLD Introduction EJB

52

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Defining Enterprise Beans• To define an enterprise bean, you must implement a To define an enterprise bean, you must implement a

specific API, and follow a number of rulesspecific API, and follow a number of rules– There are interfaces defined in the EJB spec which every enterprise bean

must implement– There are rules which define how the enterprise bean, the remote interface,

and the home interface are interrelated– We will cover session beans now, and cover entity beans later

Page 53: Lewis 2001 SLD Introduction EJB

53

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Session Beans• A Session Bean represents a conversation with a single A Session Bean represents a conversation with a single

clientclient– Its lifetime is typically the life of the client

• There are two types of session beans:There are two types of session beans:– stateful– stateless

• The type is declared at deployment timeThe type is declared at deployment time– The developer must be cognizant of the type when coding the bean

Page 54: Lewis 2001 SLD Introduction EJB

54

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Stateful Beans• Stateful beans save state between method invocationsStateful beans save state between method invocations

– For example a shopping cart bean might save a clients items as they add them to the cart

– Typically, the bean maintains state by storing it in instance variables in the bean itself

Page 55: Lewis 2001 SLD Introduction EJB

55

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Stateless Beans• Stateless Beans do not save any state between Stateless Beans do not save any state between

invocationsinvocations– They may perform a service for a client– Our calculator bean is a stateless bean– They are simpler to write and for containers to manage– They can be shared among clients

Page 56: Lewis 2001 SLD Introduction EJB

56

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

EnterpriseBean Interface• Base interface for all enterprise bean interfacesBase interface for all enterprise bean interfaces

public interface EnterpriseBean extends java.io.Serializable

{

}

• It is the common superinterface of SessionBean and It is the common superinterface of SessionBean and EntityBean interfacesEntityBean interfaces

• All enterprise beans are serializable because All enterprise beans are serializable because EnterpriseBean implements SerializableEnterpriseBean implements Serializable

Page 57: Lewis 2001 SLD Introduction EJB

57

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

The SessionBean Interface• All session beans must implement the SessionBean All session beans must implement the SessionBean

interface interface

public interface SessionBean extends EnterpiseBean {

public void ejbActivate();

public void ejbPassivate();

public void ejbRemove();

public void setSessionContext(SessionContext ctx);

}

Page 58: Lewis 2001 SLD Introduction EJB

58

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Activation and Passivation• A container vendor may implement a swapping A container vendor may implement a swapping

mechanism to move instances of beans from memory to mechanism to move instances of beans from memory to secondary storagesecondary storage– This allows the working set of beans to be larger– For example a container may swap beans out after some timeout passes– passivation is the process of swapping a bean to storage– activation is the process of retrieving a bean from storage– Serialization is commonly used as the storage mechanism

Page 59: Lewis 2001 SLD Introduction EJB

59

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

ejbPassivate() and ejbActivate() • ejbPassivate()allows the container to notify a bean allows the container to notify a bean

that it is about to be swapped outthat it is about to be swapped out– A bean should be ready to be serialized after this call

• ejbActivate()tells a bean that it has just been tells a bean that it has just been swapped inswapped in

• Beans can use these methods to release and acquire Beans can use these methods to release and acquire resourcesresources– For example open files, sockets and database connections– Very often these methods are left empty

Page 60: Lewis 2001 SLD Introduction EJB

60

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

ejbRemove & setSessionContext• ejbRemove()is called before a container removes a beanis called before a container removes a bean

– A bean can release resources here– This method is also often left empty

• setSessionContext()is called by the container to is called by the container to associate a session instance with the context maintained associate a session instance with the context maintained by the containerby the container– The bean can store this in an instance variable for future use

Page 61: Lewis 2001 SLD Introduction EJB

61

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Defining a Session Bean• Session bean definition illustrating code required by Session bean definition illustrating code required by

SessionBean interfaceSessionBean 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

Page 62: Lewis 2001 SLD Introduction EJB

62

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Bean’s Application Methods• The bean class must define all the methods in the remote The bean class must define all the methods in the remote

interfaceinterface– 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

Page 63: Lewis 2001 SLD Introduction EJB

63

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

CalculatorBean Application Methodspackage learningpatterns.ejb.calculator;import javax.ejb.*;

public class CalculatorBean implements SessionBean {// … SessionBean required methods as before

// Note - these methods DON’T throw RemoteExceptionpublic int add(int i1, int i2) {

return i1+i2;}

public int sub(int i1, int i2) { return i1-i2;

}}

Page 64: Lewis 2001 SLD Introduction EJB

64

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

ejbCreate Methods - Session Beans• The bean class must define all the create methods in the The bean class must define all the create methods in the

home interfacehome 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

Page 65: Lewis 2001 SLD Introduction EJB

65

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

CalculatorBean ejbCreate Methodspackage learningpatterns.ejb.calculator;import javax.ejb.*;

public class CalculatorBean implements SessionBean {// … SessionBean required methods as before// … Application methods as before

// Note - the name of the method is ejbCreate (not create)// and that the return type is voidpublic void ejbCreate() {

// Nothing for us to do }

}

Page 66: Lewis 2001 SLD Introduction EJB

66

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Calculator Bean Class

SessionBean ejbActivate() ejbPassivate() ejbRemove() setSessionContext(..)

extends

extends

implements

API Interfaces

Bean Developer

“Bean class”CalculatorBean ejbCreate() ejbActivate() ejbPassivate() ejbRemove() setSessionContext(SessionContext) add(int,int) sub(int,int)

Serializable

EnterpriseBean

Page 67: Lewis 2001 SLD Introduction EJB

67

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Deployment -• OverviewOverview• The standard EJB deployment descriptorThe standard EJB deployment descriptor• ejb-jar fileejb-jar file• Deploying the bean in the serverDeploying the bean in the server

Page 68: Lewis 2001 SLD Introduction EJB

68

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Deployment Overview• Deploying an enterprise bean is one of the primary steps Deploying an enterprise bean is one of the primary steps

in development of an EJBin development of an EJB• At a high-level, deployment can be viewed as having two At a high-level, deployment can be viewed as having two

phases:phases:– The first phase of deployment is creating a standard EJB jar file that contains

• A standard EJB deployment descriptor• The bean class, home interface class, and the remote interface class

– The second phase consists of deploying the standard EJB jar file to a specific EJB server. The details of this phase vary by server. However, in general:

• Vendor-specific deployment descriptors are used to specify vendor-specific information

• An implementation of the home interface is generated• An implementation of the remote interface is generated• Stubs and skeletons are created for the home and remote implementation classes

Page 69: Lewis 2001 SLD Introduction EJB

69

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Deployment Descriptor (DD)• There are many attributes which can’t be known by the There are many attributes which can’t be known by the

developer, such as database drivers or network location of developer, such as database drivers or network location of databasesdatabases

• There are other attributes, such as transaction and security There are other attributes, such as transaction and security information, that shouldn’t be coded into the beaninformation, that shouldn’t be coded into the bean

• The The deployment descriptor deployment descriptor is a standard mechanism is a standard mechanism provided by the EJB spec for describing these attributesprovided by the EJB spec for describing these attributes– Analogous to a property file for an EJB– Allow us to define some behavior of a bean without coding it into the bean itself– But there is much more structure and complexity than a simple property file– Can describe many runtime attributes of a bean such as security and

transactional behavior– Also describes structural aspects of a bean, which are used by the container

Page 70: Lewis 2001 SLD Introduction EJB

70

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

EJB 1.0 and EJB 1.1 DDs• The format of deployment descriptions changed between The format of deployment descriptions changed between

EJB 1.0 and EJB 1.1:EJB 1.0 and EJB 1.1:– In EJB 1.0, a serialized class instance is used– In EJB 1.1, the deployment descriptor is an XML file

• In this tutorial, we will concentrate on the EJB 1.1 formatIn this tutorial, we will concentrate on the EJB 1.1 format

Page 71: Lewis 2001 SLD Introduction EJB

71

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

XML Deployment Descriptor• EJB 1.1 uses XML as the deployment descriptor formatEJB 1.1 uses XML as the deployment descriptor format

– XML = Extensible Markup Language

• XML files are text files that include markup tags similar XML files are text files that include markup tags similar to HTML tagsto HTML tags– Tags are matched with an end tag, and look like this

<TAG> Content </TAG>– We will not go very deeply into the structure of XML, as it is fairly complex– We’ll cover enough to write deployment descriptors for EJB

• Deployment descriptor XML files follow a DTD Deployment descriptor XML files follow a DTD (Document Type Descriptor) specified in the EJB spec(Document Type Descriptor) specified in the EJB spec– DTDs basically specify the format and information required in an XML file

• We give you a complete deployment descriptor hereWe give you a complete deployment descriptor here– We then describe each part

• The DD must be in a file called The DD must be in a file called ejb-jar.xml

Page 72: Lewis 2001 SLD Introduction EJB

72

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Calculator 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>

<session>

<ejb-name>calculator</ejb-name>

<home>learningpatterns.ejb.calculator.CalculatorHome</home>

<remote>learningpatterns.ejb.calculator.Calculator</remote>

<ejb-class>

learningpatterns.ejb.calculator.CalculatorBean

</ejb-class>

<session-type>Stateless</session-type>

<transaction-type>Container</transaction-type>

</session>

</enterprise-beans>

Page 73: Lewis 2001 SLD Introduction EJB

73

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Calculator Deployment Descriptor<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>

Page 74: Lewis 2001 SLD Introduction EJB

74

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Deployment Descriptor Details<?xml version="1.0"?>

– Version of XML <!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise

JavaBeans 1.1//EN' 'http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd'>

– DTD describing this XML file– This might imply that you need an internet connection to use this– Weblogic has their own copy of the DTD that they cache locally

<ejb-jar>

– Root of the EJB Deployment Descriptor<enterprise-beans>

– Contains declarations for all beans described in this XML document<session>

– Describes a session bean<ejb-name>

– The name of the bean. The name we use to refer to the bean

Page 75: Lewis 2001 SLD Introduction EJB

75

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Deployment Descriptor Details<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)<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– We’ll cover transactions more later

Page 76: Lewis 2001 SLD Introduction EJB

76

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Manipulating Deployment Descriptors• Container vendors generally provide tools to create and Container vendors generally provide tools to create and

modify deployment descriptorsmodify deployment descriptors– These tools provide visual or text based ways of working with deployment

descriptors– What these tools are like and the internal representation that a container uses

for the attributes isn’t specified– The only requirement is that in creating a bean, they produce a deployment

descriptor that complies with the spec

• For EJB 1.1, it’s possible to create them by using a For EJB 1.1, it’s possible to create them by using a regular text editor, since XML is just textregular text editor, since XML is just text– You still may want to use a vendors tools if that is easier

Page 77: Lewis 2001 SLD Introduction EJB

77

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Standard EJB Jar File• EJBs are packaged in a jar fileEJBs are packaged in a jar file

– Based on the zip format– With some extra information like the deployment descriptor

• The jar file packages all the classes and files that make The jar file packages all the classes and files that make up a beanup a bean– The home, remote and bean file– The standard EJB deployment descriptor– Any auxiliary classes used

• The deployment descriptor has to be in a file called The deployment descriptor has to be in a file called ejb-jar.xmlejb-jar.xml– In a special location in the jar file - META-INF/ejb-jar.xml– This is what our META-INF directory is for

• The Java SDK comes with a jar program to create jar filesThe Java SDK comes with a jar program to create jar files

Page 78: Lewis 2001 SLD Introduction EJB

78

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Vendor-specific DD<?xml version="1.0"?><?xml version="1.0"?>

<!DOCTYPE weblogic-ejb-jar PUBLIC '-//BEA Systems, Inc.//DTD WebLogic <!DOCTYPE weblogic-ejb-jar PUBLIC '-//BEA Systems, Inc.//DTD WebLogic 5.1.0 EJB//EN' 'http://www.bea.com/servers/wls510/dtd/weblogic-ejb-5.1.0 EJB//EN' 'http://www.bea.com/servers/wls510/dtd/weblogic-ejb-jar.dtd'>jar.dtd'>

<weblogic-ejb-jar><weblogic-ejb-jar>

<weblogic-enterprise-bean><weblogic-enterprise-bean>

<ejb-name>calculator</ejb-name><ejb-name>calculator</ejb-name>

<caching-descriptor><caching-descriptor>

<max-beans-in-free-pool>100</max-beans-in-free-pool><max-beans-in-free-pool>100</max-beans-in-free-pool>

</caching-descriptor></caching-descriptor>

<jndi-name>JavaConference.CalculatorHome</jndi-name><jndi-name>JavaConference.CalculatorHome</jndi-name>

</weblogic-enterprise-bean></weblogic-enterprise-bean>

</weblogic-ejb-jar></weblogic-ejb-jar>

Page 79: Lewis 2001 SLD Introduction EJB

79

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Deploying the Standard EJB Jar File• The details vary by serverThe details vary by server• In Weblogic:In Weblogic:

– The Weblogic-specific deployment descriptor is added to the jar file– A Weblogic utility (command line or GUI) is used to generate the Weblogic-

specific implementation of the home interface and remote interface– Weblogic-specific stubs and skeletons are generated for the home and remote

implementation classes– The generated class files, stubs, and skeletons are added to the jar file– An entry is added to the weblogic.properties file to point to the jar file

containing the original EJB code, the generated code, the standard EJB deployment descriptor and the Weblogic-specific deployment descriptor

Page 80: Lewis 2001 SLD Introduction EJB

80

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Client View of a Session Bean -• Getting a JNDI InitialContextGetting a JNDI InitialContext• Looking up the home interfaceLooking up the home interface• Getting a reference to an EJBGetting a reference to an EJB• Calling methods on an EJBCalling methods on an EJB

Page 81: Lewis 2001 SLD Introduction EJB

81

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Getting a JNDI InitialContext• In most cases, the default constructor for In most cases, the default constructor for

javax.naming.InitialContext can be usedjavax.naming.InitialContext can be used– If executed inside a server environment (EJB, servlet, or JSP), this retrieves

an InitalContext from the local naming service– If executed outside of a server environment, the InitialContext is created

based upon information specified in Java system properties. Two properties are required:

• The JNDI initial context factory class name. You’ll get this from the documentation of the JNDI provider

• The URL to connect to the namespace the home interface is in. You’ll get this also from the documentation of the JNDI provider

• Sample code fragment:Sample code fragment:InitialContext ctx = new InitialContext();

Page 82: Lewis 2001 SLD Introduction EJB

82

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Looking up the home interface• Use the lookup method of the Context interface to get a Use the lookup method of the Context interface to get a

home interface referencehome 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 can’t use direct casting because IIOP (CORBA) stubs aren’t 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

• Sample code fragment:Sample code fragment:Object calcObject = ctx.lookup(“JavaConference.CalculatorHome”);CalculatorHome cHome = (CalculatorHome)

PortableRemoteObject.narrow(calcObject, CalculatorHome.class);

Page 83: Lewis 2001 SLD Introduction EJB

83

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Getting a reference to an EJB• The client uses a create method in the home interface to The client uses a create method in the home interface to

get a reference to the EJB get a reference to the EJB • The calculator home interface contains a method called The calculator home interface contains a method called

create that accepts no parameters:create that accepts no parameters:public Calculator create() throws CreateException, RemoteException;

• The client can use this method to get a reference to the The client can use this method to get a reference to the CalculatorCalculator– Calculator is the remote interface type– Behind the scenes, the client is really talking to a stub for the EJBObject

implementation class– The client can use the reference to invoke any of the methods in the remote

interface

• Sample code fragment:Sample code fragment:Calculator calc = cHome.create();Calculator calc = cHome.create();

Page 84: Lewis 2001 SLD Introduction EJB

84

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Calling methods on an EJB• The EJB’s remote interface defines the methods that can The EJB’s remote interface defines the methods that can

be called from a clientbe called from a client• In the case of the calculator example, the interface In the case of the calculator example, the interface

contains an add and a sub method: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:Sample Code fragment:System.out.println(“6 + 5 = “ + calc.add(6,5));System.out.println(“6 + 5 = “ + calc.add(6,5));

System.out.println(“6 - 5 = “ + calc.sub(6,5));System.out.println(“6 - 5 = “ + calc.sub(6,5));

Page 85: Lewis 2001 SLD Introduction EJB

85

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Stateless Session Bean Lifecycle -• OverviewOverview• State diagram of bean class instanceState diagram of bean class instance

– Describe the different states a bean can be in– Describe the transitions between the states and the triggers for the transitions

• Object interaction diagrams (OID Diagrams)Object interaction diagrams (OID Diagrams)– Describe the interactions between the various parts of an EJB system– Indicate the objects involved in a particular scenario– Indicate the sequence of interactions between the objects

• SummarySummary

Page 86: Lewis 2001 SLD Introduction EJB

86

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Overview • The client never deals with the the bean class instance The client never deals with the the bean class instance

directlydirectly– It always talks to the bean class instance via the associated EJBObject

• The container manages both the EJBObject instance and The container manages both the EJBObject instance and the bean class instancethe bean class instance

• Consequently, the container is in a position to manage Consequently, the container is in a position to manage these objects in a way that optimizes server resources these objects in a way that optimizes server resources and application performanceand application performance– This is one of the main benefits of EJB

Page 87: Lewis 2001 SLD Introduction EJB

87

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Lifecycle of Stateless Bean Class

1. newInstance()2. setSessionContext(sc)3. ejbCreate()

newInstance() means that the beanis instantiated using thedefault constructor.

1. ejbRemove()

Method calls

Does not exist

Ready pool

Page 88: Lewis 2001 SLD Introduction EJB

88

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Container Creation of Stateless SB

Bean class instance

Container

new

setSessionContext()

ejbCreate()

Page 89: Lewis 2001 SLD Introduction EJB

89

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Client Creation of Stateless SB

EJBObject

create()

Client EJBHome

new

Page 90: Lewis 2001 SLD Introduction EJB

90

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Client Call of a Stateless SB Method

Bean class instance

Business method

Client EJBObject

Business method

Page 91: Lewis 2001 SLD Introduction EJB

91

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Client Removal of a Stateless SB

remove()

Client EJBObject

Page 92: Lewis 2001 SLD Introduction EJB

92

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Container Removal of a Stateless SB

Bean class instance

Container

ejbRemove()

Page 93: Lewis 2001 SLD Introduction EJB

93

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Client Creation of a Stateless SB• When the client calls create on the home interface, the When the client calls create on the home interface, the

container creates an instance of the EJBObjectcontainer creates an instance of the EJBObject• At this point, the EJBObject instance is not associated At this point, the EJBObject instance is not associated

with a bean class instancewith a bean class instance

Container Pooled Beans

Client

EJB

Ho

mecreate() EJBObject

new

Page 94: Lewis 2001 SLD Introduction EJB

94

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Client Call of a Stateless SB Method• Any bean may be used for any method from any clientAny bean may be used for any method from any client• Since bean is stateless, they are all identicalSince bean is stateless, they are all identical• All method calls are independent of all othersAll method calls are independent of all others

Container Pooled Beans

Client

EJB

Ob

jectmethod()

Page 95: Lewis 2001 SLD Introduction EJB

95

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Summary of Stateless SB Life Cycle• Clients use Clients use create() and and remove()

– But they’re not actually creating and destroying instances

• Activation and passivation not neededActivation and passivation not needed– Since any bean can be used for any method– If more beans are needed for a given load, they are created– If a bean isn’t needed, it’s destroyed

• Container is free to pass any method call to any beanContainer is free to pass any method call to any bean– Change beans within a transaction– Whatever it wants to do

• Usually need many fewer beans than clientsUsually need many fewer beans than clients– Since clients are often “thinking”

• Stateless session beans minimize resources needed to Stateless session beans minimize resources needed to support given number of clientssupport given number of clients– But limited in their capability

Page 96: Lewis 2001 SLD Introduction EJB

96

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Stateful Session Beans -• OverviewOverview• LifecycleLifecycle

– State Diagram– Passivation/Activation– Removal

Page 97: Lewis 2001 SLD Introduction EJB

97

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Stateful Session Bean Overview• Stateful session beans have the same structure as Stateful session beans have the same structure as

stateless session beansstateless session beans– Home interface– Remote interface– Bean class

• The difference is that stateful session beans maintain The difference is that stateful session beans maintain client-specific data between method callsclient-specific data between method calls– This has implications for how the container manages stateful session beans– It also, of course, changes the way you code your bean because now you can

keep client-specific data in class member variables– It makes sense to pass parameters on the create method, since the parameter

values can be stored in member variables• You can define as many create methods as you need

Page 98: Lewis 2001 SLD Introduction EJB

98

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Coding a Stateful Session Bean• Define instance variables to hold client-specific stateDefine instance variables to hold client-specific state• Determine if state information is going to be passed to Determine if state information is going to be passed to

the bean’s create methodsthe bean’s create methods• Determine if there is any need to implement Determine if there is any need to implement javax.ejb.SessionSynchronization– See next slide for more information

• Declare the bean to be stateful in the deployment Declare the bean to be stateful in the deployment descriptordescriptor

Page 99: Lewis 2001 SLD Introduction EJB

99

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Stateful Session Beans and Transactions• Stateful sessions beans are often transactionalStateful sessions beans are often transactional

– Transaction behavior is declared at the method level in the deployment descriptor

– For example, a Teller Bean might have a withdraw method that debits account 1 and credits account 2. It would make sense to tell the container to run the withdraw method inside a transaction

• Conversational state is not transactionalConversational state is not transactional– That is, member variables are not restored to their initial state on transaction

boundaries– The optional SessionSynchronization interface can be used to code

transactional initialization logic

• If the bean class implements If the bean class implements javax.ejb.SessionSynchronization,the container the container notifies it of different points in the life cycle of the notifies it of different points in the life cycle of the transaction (tran has started, before commit, etc.)transaction (tran has started, before commit, etc.)– We will look at transactions in detail in Session 4

Page 100: Lewis 2001 SLD Introduction EJB

100

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Lifecycle of Stateful Bean Class

create(args)

1. newInstance()2. setSessionContext(sc)3. ejbCreate(args)

newInstance() means that the bean is instantiated using the default constructor.

remove() or timeout

Does not exist

Ready Passive

ejbPassivate()

ejbActivate()

ejbRemove()

timeout

Page 101: Lewis 2001 SLD Introduction EJB

101

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Creation of Stateful SB

EJBObject

create(args)

Client EJBHome

new

Bean class instance

new

setSessionContext(sc)

ejbCreate(args)

Page 102: Lewis 2001 SLD Introduction EJB

102

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Stateful Session Passivation/Activation• A container may passivate a bean when it is not in a A container may passivate a bean when it is not in a

transaction or method invocationtransaction or method invocation– The container decides when and if to passivate a bean– Passivation is usually an indication that the bean has been idle for some period

of time and/or the container needs the memory because of an increase in workload

– The container activates the bean upon method invocation

• Bean provider must ensure that the bean’s conversational Bean provider must ensure that the bean’s conversational state is serializable after state is serializable after ejbPassivate is executed is executed– If your bean’s conversational state is not serializable, the container will get an

error when it tries to passivate the bean– Normal rules of serialization plus some special cases for EJB (see next slide)

• Container is responsible for saving and restoring Container is responsible for saving and restoring conversational stateconversational state

Page 103: Lewis 2001 SLD Introduction EJB

103

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Conversational State• Conversational stateConversational state

– Definition in EJB 1.0• Bean’s field values • Plus the transitive closure of the objects reachable from the session bean’s fields

(i.e., the fields that would be stored by serializing the enterprise bean instance)• EJB Object references also must also be stored and reconstructed• This was defined more clearly in EJB 1.1 (below)

– Definition in EJB 1.1• A serializable object• A null• An enterprise bean’s remote interface reference, even if the stub class is not

serializable• An enterprise bean’s home interface reference, even if the stub class is not

serializable• A reference to the SessionContext object, even if it is not serializable• A reference to the environment naming context or any of its subcontexts• A reference to the UserTransaction interface

Page 104: Lewis 2001 SLD Introduction EJB

104

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Passivation of Stateful SB

ContainerBean class instance

Secondary storage

ejbPassivate()

write state

Page 105: Lewis 2001 SLD Introduction EJB

105

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Activation of Stateful SB

ContainerBean class instance

Secondary storage

read state

ejbActivate()

Page 106: Lewis 2001 SLD Introduction EJB

106

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Stateful Session Bean Removal• Bean is destroyed upon client invoking Bean is destroyed upon client invoking remove()• Bean may also be destroyed by container upon timeoutBean may also be destroyed by container upon timeout

– This can even happen when the bean is passivated

• ejbRemove is NOT guaranteed to be called is NOT guaranteed to be called– For example, if a timeout occurs when the bean is passivated– This means that if there are resources that may persist after bean removed

there must be an external cleanup mechanism. For example, if there is some database storage involved, you may need to periodically sweep the database for orphaned data

• Invoking a method on a bean after its removal throws an Invoking a method on a bean after its removal throws an exceptionexception

Page 107: Lewis 2001 SLD Introduction EJB

107

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Removal of Stateful SB

Client EJBObjectBean class instance

remove()

ejbRemove()

Page 108: Lewis 2001 SLD Introduction EJB

108

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Summary of Stateful SB Life Cycle• When the client calls When the client calls create() and and remove(), bean bean

instances are created and deletedinstances are created and deleted• Each instance is associated with a single clientEach instance is associated with a single client• Activation and passivation are usedActivation and passivation are used• Pooling is not usedPooling is not used• Life cycle is more complicated than stateless session Life cycle is more complicated than stateless session

beansbeans• Stateful session beans are more expensive than Stateful session beans are more expensive than

stateless beans but they provide greater functionalitystateless beans but they provide greater functionality

Page 109: Lewis 2001 SLD Introduction EJB

109

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Entity Bean Overview -• DefinitionDefinition• Container-managed persistence (CMP)Container-managed persistence (CMP)• Bean-managed persistence (BMP)Bean-managed persistence (BMP)• Similarities and differences between CMP and BMP Similarities and differences between CMP and BMP

Page 110: Lewis 2001 SLD Introduction EJB

110

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Entity Bean Definition• Entity Beans are EJBs that present an object view of Entity Beans are EJBs that present an object view of

persistent data and arepersistent 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 Entity beans usually represent data in a relational database but they don’t have todatabase but they don’t have to– 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

Page 111: Lewis 2001 SLD Introduction EJB

111

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Entity Bean Definition• When the underlying database is relational, a mapping When the underlying database is relational, a mapping

between the object view and the relational database must between the object view and the relational database must be definedbe defined– More complex beans may represent relationships like a join between two

tables. For example, the information for a particular customer plus all of that customer’s order items

– To keep things straightforward, this session talks in terms of entity beans representing rows in a relational database

• A specific entity bean such as the account entity bean corresponds to the account table

• An instance of an entity bean corresponds to a row in the corresponding table

Page 112: Lewis 2001 SLD Introduction EJB

112

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Represent Database or Application

ClientEJB

Server/Container

Account Bean Database

ClientEJB

Server/Container

Account Bean DatabaseExisting AppConnector API

Page 113: Lewis 2001 SLD Introduction EJB

113

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Types of Entity Beans• There are two types are of entity beans:There are two types are of entity beans:

– In bean-managed persistence (BMP), the bean provider implements persistence directly in the bean class

– In container-managed persistence (CMP), the persistence management is the responsibility of the container

Page 114: Lewis 2001 SLD Introduction EJB

114

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Container-managed Persistence (CMP)• Container automatically manages persistence Container automatically manages persistence

– Bean developer does not write database calls– How this is done is up to the vendor

• In general you define a mappingIn general you define a mapping– This maps the object data (the instance variables) to the datastore (the

columns in a relational table)– The vendor tools generate the code– O-R (Object-Relational) mapping is one of the more demanding tasks in

creating a system like this

• CMP makes life simpler for the bean writerCMP makes life simpler for the bean writer– Also, the bean is independent of the data source specifics

• CMP is very complex for the vendorCMP is very complex for the vendor– O-R mapping and tools to do it are still not very mature– Future support for object-relational mapping is expected

Page 115: Lewis 2001 SLD Introduction EJB

115

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Bean-managed Persistence (BMP)• Bean manages all persistenceBean manages all persistence

– The bean developer writes the persistence code as part of developing the bean

• Advantage - container doesn’t need to generate database Advantage - container doesn’t need to generate database callscalls– This may be necessary if automatic tools can’t handle it– CMP is not very mature– Bean writer has complete control– Denormalized tables, fancy object faulting, etc

• Disadvantage - more work for the bean writerDisadvantage - more work for the bean writer– More complex code– Persistence is hard coded into the bean– This makes it harder to adapt the bean to different data sources

Page 116: Lewis 2001 SLD Introduction EJB

116

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

BMP/CMP: Similarities and Differences• In many respects, BMP and CMP beans have much in In many respects, BMP and CMP beans have much in

commoncommon– Home interface– Remote interface– Primary key class– Client’s view

• In other respects, BMP and CMP are differentIn other respects, BMP and CMP are different– Implementation of bean class– Deployment descriptor details– Implementation of finder methods

• First, we will look at the similarities. Then we will look at First, we will look at the similarities. Then we will look at the differences between CMP and BMP the differences between CMP and BMP

Page 117: Lewis 2001 SLD Introduction EJB

117

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Entity Bean Interfaces -• Both CMP and BMP entity beans have:Both CMP and BMP entity beans have:

– A home interface• Create methods• Finder methods

– A remote interface• Business methods

– A primary key

• We will use a simple banking example to illustrate the We will use a simple banking example to illustrate the implementation of an Entity Beanimplementation of an Entity Bean– Account Entity contains fields for the id, name, initial balance, and the date

on which the account was opened

Page 118: Lewis 2001 SLD Introduction EJB

118

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Home Interface and Create Methods • The home interface is still the bean “factory” for entity The home interface is still the bean “factory” for entity

beansbeans– But now you also have to take into account that there is underlying data

• For entity beans, create methods in the home interface For entity beans, create methods in the home interface add a new row to the underlying dataadd 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:

public interface AccountHome extends EJBHome {public Account create(int id, String name, double

initialBalance) throws RemoteException,

CreateException;

}

Page 119: Lewis 2001 SLD Introduction EJB

119

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Finders - Retrieving Existing Data• Home interfaces also define Home interfaces also define finderfinder methods to look up methods to look up

existing objects or collections of objectsexisting objects or collections of objects– One method for each way to look up a bean– The arguments to the finder method are used to locate the bean(s)– The return type for finder that returns a single object is the remote interface

type (EJBObject)– Return value for finder that returns multiple objects is an Enumeration

representing a collection of remote interfaces• In EJB1.1 may also be a Collection

– The name of each finder method prefix must start with find – The throws clause can include FinderException

• Every home must have the Every home must have the findByPrimaryKey methodmethod– This allows locating to locate a bean by the primary key– It has a single argument of the primary key type– It must return a single EJBObject

Page 120: Lewis 2001 SLD Introduction EJB

120

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Finder Methods Examplepublic interface AccountHome extends EJBHome {

// create methods …

// e.g. to find all accounts with a minimum balancepublic Enumeration findByMinBalance (double minBalance)

throws RemoteException, FinderException;

public Account findByPrimaryKey(AccountPK primaryKey)throws RemoteException,

FinderException;// We’ll look at what PrimaryKeyType should be later

}

Note: AccountPK is a class that is defined later in thissection.

Page 121: Lewis 2001 SLD Introduction EJB

121

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Account Home Interface

EJBHome getEJBMetaData() getHomeHandle() remove(Handle) remove(Object)

Remote

extends

extends

API Interfaces

Bean Developer

“Home interface”AccountHome create(int,String, double) findByPrimaryKey(pk) findByMinBalance(double)

Page 122: Lewis 2001 SLD Introduction EJB

122

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Remote Interface• Just like with session beans, the remote interface for an Just like with session beans, the remote interface for an

entity bean defines the business methods that are entity bean defines the business methods that are available to the clientavailable to the client

• For example, the remote interface for an account object For example, the remote interface for an account object might look like the following: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;

}

Page 123: Lewis 2001 SLD Introduction EJB

123

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Account Remote Interface

“Remote interface”Account deposit(double) withdraw(double) getBalance() getOpenDate() getName()

extends

extends

API Interfaces

Bean Developer

EJBObject getEJBHome() getHandle() getPrimaryKey() isIdentical(EJBOBject) remove()

Remote

Page 124: Lewis 2001 SLD Introduction EJB

124

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Primary Key• Every entity bean has a unique identifier within its homeEvery entity bean has a unique identifier within its home

– This unique identifier is called the primary key– In general, you write a class to represent the primary key– You may also use a single specific field in the bean (starting with EJB 1.1)

• The home and primary key determine an object’s identity The home and primary key determine an object’s identity within a containerwithin a container– The primary key class can be any serializable class– Each EJB may have a different primary key class– In general, the bean writer defines the primary key class, and is responsible

for determining what constitutes the primary key– You can get the primary key from the EJBObject with the getPrimaryKey() method

– In EJB1.1, there are ways for the bean writer to defer defining the primary key until deployment time

Page 125: Lewis 2001 SLD Introduction EJB

125

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Entity Bean Implementation -• Entity Bean StateEntity Bean State• EntityBean InterfaceEntityBean Interface• Primary Key ClassPrimary Key Class• Create MethodsCreate Methods• Finder MethodsFinder Methods• Lifecycle MethodsLifecycle Methods• Application MethodsApplication Methods

Page 126: Lewis 2001 SLD Introduction EJB

126

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Entity Bean State• Generally there are instance variables to hold the data Generally there are instance variables to hold the data • For CMPFor CMP

– Bean provider must specify the containerManagedFields DD property– This specifies the fields container must manage state for – These fields must be declared public– They must be Serializable (primitives & instances of a Serializable class)– In 1.1 can include references to other beans (important for O-R mapping)– Mapping to underlying data must be defined using vendor tools

• Using a simple bank account exampleUsing a simple bank account example– Assume the underlying database table for an account had a column of type string

for an account id, and one of type double for a balance// CMP example of fields for an Account beanpublic String m_id;public double m_balance;public String m_name;public java.sql.Date m_open_date;

Page 127: Lewis 2001 SLD Introduction EJB

127

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

The EntityBean Interface• All entity beans must implement the All entity beans must implement the EntityBean

interfaceinterface– We’ll look at all the methods in detail a little later

public interface EntityBean extends EnterpiseBean {void ejbActivate();void ejbLoad();void ejbPassivate();void ejbRemove(); void ejbStore(); void setEntityContext(EntityContext ctx); void unsetEntityContext();

}

Page 128: Lewis 2001 SLD Introduction EJB

128

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

AccountBeanpackage learningpatterns.ejb.bank;import javax.ejb.*;

public class AccountBean implements EntityBean {

public int m_id;public double m_balance;public String m_name;public java.sql.Date m_open_date;

public void ejbActivate() {System.out.println(“AccountBean.ejbActivate”);

}

// … and so on for other required EntityBean methods

}

Page 129: Lewis 2001 SLD Introduction EJB

129

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Primary Key Class Details• The primary key class is defined by the bean developerThe primary key class is defined by the bean developer

– It must be Serializable

• For CMP, the primary key class is tied to the bean For CMP, the primary key class is tied to the bean implementationimplementation– Class must be public, and all fields in class must be public– There must be a public default constructor– Names of the fields must be a subset of the fields in the enterprise bean class– There must be a hashCode() and equals() method– Necessary for generation of findByPrimaryKey method

• It is also possible to use a single field in the bean classIt is also possible to use a single field in the bean class– As long as the field is serializable, and has a hashCode() and equals() method

• When comparing objects for equalityWhen comparing objects for equality– Can extract the primary keys and use the equals()method– Can also use the EJBObject isIdentical() method

Page 130: Lewis 2001 SLD Introduction EJB

130

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

AccountPK// Primary Key Class for AccountBeanpackage 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;

}

}

Page 131: Lewis 2001 SLD Introduction EJB

131

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Create Methods• You create a bean via a You create a bean via a create() call on the home call on the home

interfaceinterface– The container will then call the ejbCreate() and ejbPostCreate()

methods of the bean implementation– It will pass the arguments from create() to these methods

• An An ejbCreate() method must be defined for each method must be defined for each create() method in the home interface method in the home interface– They follow the same parameter rules as for session beans– They are public, have the same arguments as in the home interface– The arguments must be legal for Java RMI

• An An ejbPostCreate() method must also be defined for method must also be defined for each each createcreate methodmethod– Same arguments as ejbCreate– void return– Doesn’t throw CreateException, RemoteException

Page 132: Lewis 2001 SLD Introduction EJB

132

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

ejbCreate() - Entity Beans• For BMPFor BMP

– Should actually create row in database– Return value is the primary key

• For CMPFor CMP– Should initialize the instance variables from the passed in arguments– Doesn’t go to database– EJB1.1 - Return value type is also the primary key, but you should return

null. (The container will extract the values and create the primary key instance)

– EJB 1.0 - Return value is void– Return value type was changed from 1.0 to 1.1 so signature is consistent for

BMP and CMP

Page 133: Lewis 2001 SLD Introduction EJB

133

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

ejbCreate(), ejbPostCreate() - CMPpublic class AccountBean implements EntityBean {// …public AccountPK ejbCreate ( // EJB 1.0 - void returnint id, String name, double initialBalance)throws RemoteException, CreateException {m_id = id; // Initialize instance varsm_name = name;m_balance = initialBalance;m_open_date = new java.sql.Date(System.currentTimeMillis()); return null; // EJB 1.0 - no return}

public void ejbPostCreate (int id, String name, double initialBalance) {// Nothing to do in this case}}

Page 134: Lewis 2001 SLD Introduction EJB

134

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Finder Methods• For BMPFor 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 clientpublic class AccountBean implements EntityBean {

// …public Enumeration ejbFindByMinBalance (double minBalance)

throws RemoteException, FinderException {}}

• For CMPFor 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

Page 135: Lewis 2001 SLD Introduction EJB

135

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Activation and Passivation• Activation and passivation follow the same model as with Activation and passivation follow the same model as with

session beanssession beans– ejbPassivate and ejbActivate should respectively save and

reacquire resources

• setEntityContext should save the passed in context should save the passed in context for future usefor future use

• unsetEntityContext unsets the context unsets the context– Sets it to null

Page 136: Lewis 2001 SLD Introduction EJB

136

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Lifecycle Methods with CMP• ejbLoad and and ejbStore are are NOTNOT used for database used for database

accessaccess– Used for communication between server and bean instance– After loading the data from the database, ejbLoad is called to tell the bean– Before storing the data to the database, ejbStore is called to tell the bean– They do not perform any database operations– We’ll talk more about when these are called after we talk about transactions

Page 137: Lewis 2001 SLD Introduction EJB

137

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Lifecycle Methods with BMP• ejbLoad and and ejbStore AREARE used for database access used for database access

– When the container wants to refresh a bean with data from the database, ejbLoad is called on the bean

– This method should extract data from the database and place it in the bean– When the container wants store the data in the bean into the database, ejbStore is called on the bean

– This method should store data from the bean into the database

Page 138: Lewis 2001 SLD Introduction EJB

138

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

ejbRemove()• An An ejbRemove() method must be defined in the bean method must be defined in the bean

itselfitselfpublic void ejbRemove() {} – It is called when remove() is called on the bean– It will be called before the bean is removed

• For CMPFor CMP– You can put here any cleanup code, or release any resources that are being

used– Often it is an empty method

• For BMPFor BMP– You would put database code to actually remove the bean– You can also clean up and release resources

Page 139: Lewis 2001 SLD Introduction EJB

139

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Business Methods•Operate on the instance variablesOperate on the instance variables

public class AccountBean implements EntityBean {// …

public void deposit(int amount) {m_balance += amount;

}

// … and so on}

Page 140: Lewis 2001 SLD Introduction EJB

140

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Entity Beans and SQL Statements

Entity Bean Operation Corresponding SQL Statement

ejbCreate(…) insert

ejbfindByxxx(…) select

ejbRemove() delete

ejbStore() update

ejbLoad() select

CMP Entity Bean Container handles all SQLBMP Entity Bean Bean class contains SQL code

Page 141: Lewis 2001 SLD Introduction EJB

141

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

CMP and Deployment• Since the container is accessing the database on behalf Since the container is accessing the database on behalf

of the bean, the container needs to know:of the bean, the container needs to know:– What fields in the bean are to be persisted by the container– The type of persistence– How to get a connection to the database– The table names– The mapping between table columns and field names in the bean– The semantics of the finder methods

• For Weblogic, this information is specified in the For Weblogic, this information is specified in the following deployment descriptors:following deployment descriptors:– The standard EJB deployment descriptor (ejb-jar.xml)– weblogic-ejb-jar.xml– weblogic-cmp-rdbms-jar.xml

Page 142: Lewis 2001 SLD Introduction EJB

142

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

ejb-jar.xml - Part 1<?xml version="1.0"?><?xml version="1.0"?>

<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise <!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN' 'http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd'>JavaBeans 1.1//EN' 'http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd'>

<ejb-jar><ejb-jar>

<enterprise-beans><enterprise-beans>

<entity><entity>

<ejb-name>account</ejb-name><ejb-name>account</ejb-name>

<home>learningpatterns.ejb.bank.AccountHome</home><home>learningpatterns.ejb.bank.AccountHome</home>

<remote>learningpatterns.ejb.bank.Account</remote><remote>learningpatterns.ejb.bank.Account</remote>

<ejb-class>learningpatterns.ejb.bank.AccountBean</ejb-class><ejb-class>learningpatterns.ejb.bank.AccountBean</ejb-class>

<persistence-type>Container</persistence-type><persistence-type>Container</persistence-type>

<prim-key-class>learningpatterns.ejb.bank.AccountPK</prim...><prim-key-class>learningpatterns.ejb.bank.AccountPK</prim...>

<reentrant>False</reentrant><reentrant>False</reentrant>

<cmp-field><cmp-field>

<field-name>m_id</field-name><field-name>m_id</field-name>

</cmp-field></cmp-field>

Page 143: Lewis 2001 SLD Introduction EJB

143

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

ejb-jar.xml - Part 2 <cmp-field><cmp-field>

<field-name>m_name</field-name><field-name>m_name</field-name>

</cmp-field></cmp-field>

<cmp-field><cmp-field>

<field-name>m_open_date</field-name><field-name>m_open_date</field-name>

</cmp-field></cmp-field>

<cmp-field><cmp-field>

<field-name>m_balance</field-name><field-name>m_balance</field-name>

</cmp-field></cmp-field>

</entity></entity>

</enterprise-beans></enterprise-beans>

<assembly-descriptor><assembly-descriptor>

...

</assembly-descriptor></assembly-descriptor>

</ejb-jar></ejb-jar>

Page 144: Lewis 2001 SLD Introduction EJB

144

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

weblogic-ejb-jar - Part 1<?xml version="1.0"?><?xml version="1.0"?>

<!DOCTYPE weblogic-ejb-jar PUBLIC '-//BEA Systems, Inc.//DTD WebLogic 5.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'>EJB//EN' 'http://www.bea.com/servers/wls510/dtd/weblogic-ejb-jar.dtd'>

<weblogic-ejb-jar><weblogic-ejb-jar>

<weblogic-enterprise-bean><weblogic-enterprise-bean>

<ejb-name>account</ejb-name><ejb-name>account</ejb-name>

<caching-descriptor><caching-descriptor>

<max-beans-in-cache>1000</max-beans-in-cache><max-beans-in-cache>1000</max-beans-in-cache>

</caching-descriptor></caching-descriptor>

<persistence-descriptor><persistence-descriptor>

<persistence-type><persistence-type>

<type-identifier>WebLogic_CMP_RDBMS</type-identifier><type-identifier>WebLogic_CMP_RDBMS</type-identifier>

<type-version>5.1.0</type-version><type-version>5.1.0</type-version>

<type-storage>META-INF/weblogic-cmp-rdbms-jar.xml</type...><type-storage>META-INF/weblogic-cmp-rdbms-jar.xml</type...>

</persistence-type></persistence-type>

Page 145: Lewis 2001 SLD Introduction EJB

145

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

weblogic-ejb-jar - Part 2 <persistence-use><persistence-use>

<type-identifier>WebLogic_CMP_RDBMS</type-identifier><type-identifier>WebLogic_CMP_RDBMS</type-identifier>

<type-version>5.1.0</type-version><type-version>5.1.0</type-version>

</persistence-use></persistence-use>

</persistence-descriptor></persistence-descriptor>

<jndi-name>JavaConference.AccountHome</jndi-name><jndi-name>JavaConference.AccountHome</jndi-name>

</weblogic-enterprise-bean></weblogic-enterprise-bean>

</weblogic-ejb-jar></weblogic-ejb-jar>

Page 146: Lewis 2001 SLD Introduction EJB

146

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

weblogic-cmp-rdbms-jar.xml - Part 1<!DOCTYPE weblogic-rdbms-bean PUBLIC <!DOCTYPE weblogic-rdbms-bean PUBLIC

'-//BEA Systems, Inc.//DTD WebLogic 5.1.0 EJB RDBMS Persistence//EN''-//BEA Systems, Inc.//DTD WebLogic 5.1.0 EJB RDBMS Persistence//EN'

'http://www.bea.com/servers/wls510/dtd/weblogic-rdbms-persistence.dtd'>'http://www.bea.com/servers/wls510/dtd/weblogic-rdbms-persistence.dtd'>

<weblogic-rdbms-bean><weblogic-rdbms-bean>

<pool-name>BankPool</pool-name><pool-name>BankPool</pool-name>

<table-name>Account</table-name><table-name>Account</table-name>

<attribute-map><attribute-map>

<object-link><object-link>

<bean-field>m_id</bean-field><bean-field>m_id</bean-field>

<dbms-column>ID</dbms-column><dbms-column>ID</dbms-column>

</object-link></object-link>

<object-link><object-link>

<bean-field>m_name</bean-field><bean-field>m_name</bean-field>

<dbms-column>Name</dbms-column><dbms-column>Name</dbms-column>

</object-link></object-link>

......

</attribute-map></attribute-map>

Page 147: Lewis 2001 SLD Introduction EJB

147

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

weblogic-cmp-rdbms-jar.xml - Part 2 <finder-list><finder-list>

<finder><finder>

<method-name>findByMinBalance</method-name><method-name>findByMinBalance</method-name>

<method-params><method-params>

<method-param>double</method-param><method-param>double</method-param>

</method-params></method-params>

<finder-query><![CDATA[(>= m_balance $0)]]></finder-query><finder-query><![CDATA[(>= m_balance $0)]]></finder-query>

</finder></finder>

</finder-list></finder-list>

<options><options>

<use-quoted-names>false</use-quoted-names><use-quoted-names>false</use-quoted-names>

</options></options>

</weblogic-rdbms-bean></weblogic-rdbms-bean>

Page 148: Lewis 2001 SLD Introduction EJB

148

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Bean Managed Persistence -• Differences between CMP and BMPDifferences between CMP and BMP• Connecting to databaseConnecting to database• ejbLoad and and ejbStore• Finder methodsFinder methods

Page 149: Lewis 2001 SLD Introduction EJB

149

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Bean Managed Persistence (BMP)• Differences between CMP and BMP. In BMP:Differences between CMP and BMP. In BMP:

– Bean must get a database connection– Bean class contains implementations of the finder methods – Bean contains code to access the database:

• ejbCreate methods insert data to the database• ejbRemove deletes data from the database• ejbLoad selects data from the database• ejbStore updates data in the database• ejbFind methods select data from the database

– ejbCreate methods return a primary key instance instead of null– Deployment descriptor

Page 150: Lewis 2001 SLD Introduction EJB

150

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Connecting to Database• Is the most complicated partIs the most complicated part

– The rest is fairly straightforward JDBC

• We will need to use the EJB mechanism to access We will need to use the EJB mechanism to access resourcesresources– Resources are things like JDBC, JMS, and JavaMail objects– You access them through the JNDI Environment naming context

• For JDBC, you must use a JDBC For JDBC, you must use a JDBC DataSource– It must be using a transactional driver– For Weblogic, that’s the jts driver– It is created in the weblogic.properties file

Page 151: Lewis 2001 SLD Introduction EJB

151

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Accessing a JDBC DataSource• We’ll give an example using Weblogic serverWe’ll give an example using Weblogic server• This involves both the weblogic.properties file, and the This involves both the weblogic.properties file, and the

xml deployment descriptorsxml deployment descriptors– First you need to create the DataSource in the weblogic.properties file– Then you need to create a reference to it in the DD

• We’re only going to show the relevant parts of the DD• This is in the ejb-jar.xml and weblogic-ejb-jar.xml files

• Then you access it in your bean through JNDI using the Then you access it in your bean through JNDI using the reference name in the DDreference name in the DD

Page 152: Lewis 2001 SLD Introduction EJB

152

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Database Propertiesweblogic.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=everyone

Page 153: Lewis 2001 SLD Introduction EJB

153

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

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>

Page 154: Lewis 2001 SLD Introduction EJB

154

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Deployment Descriptor Details<resource-ref>

– Describes a resource reference<res-ref-name>

– JNDI name you will use to look up resource with– Note that using jdbc/ is not required - it is a convention only

<res-type>

– Fully qualified class name of the resource<res-auth>

– Authorization - container or bean– I.e. - will the bean writer need to pass in info like user/password, or will the

container deal with it

Page 155: Lewis 2001 SLD Introduction EJB

155

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

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-ejb-jar.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>

Page 156: Lewis 2001 SLD Introduction EJB

156

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

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>

Page 157: Lewis 2001 SLD Introduction EJB

157

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

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”

Page 158: Lewis 2001 SLD Introduction EJB

158

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Getting a Connection• We’ll encapsulate it in a methodWe’ll encapsulate it in a method

– First we get the JNDI ENC– Then we look up our DataSource and get a connection from itprivate Connection getConnection() throws SQLException {

Connection con = null;try {

InitialContext ctx = new InitialContext();javax.sql.DataSource ds = (javax.sql.DataSource)

ctx.lookup("java:comp/env/jdbc/BankPool");ctx.close();con = ds.getConnection();

}catch(SQLException sqle) {

throw sqle;}catch(Exception e) {

throw new SQLException(e.getMessage());}return con;

}

Page 159: Lewis 2001 SLD Introduction EJB

159

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Getting Data From the Database• It’s fairly straightforward JDBC from now onIt’s fairly straightforward JDBC from now on

– You have a connection to the database– All you need to do is to queries, updates, inserts, etc.

• We’ll create a refresh method that loads the data given a We’ll create a refresh method that loads the data given a primary keyprimary key– This can be used from multiple methods

Page 160: Lewis 2001 SLD Introduction EJB

160

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Getting Data From the DB - cont’d// We’ll use refresh from finders also, so it throws a FinderException

private void refresh(AccountPK pk) throws FinderException, RemoteException {

Connection con = null;Statement stm = null;try {

con = getConnection();stm = con.createStatement();ResultSet rs = stm.executeQuery("select Balance, Name,

OpenDate from Account where ID = " + pk.m_id);if (rs.next()) {

m_id = pk.m_id;m_balance = rs.getDouble(1);m_name = rs.getString(2);m_open_date = rs.getDate(3);

}else {

throw new FinderException ("Refresh: AccountBean (" + pk.m_id + ") not found");

}}

Page 161: Lewis 2001 SLD Introduction EJB

161

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Getting Data From the DB - cont’d// Continued from previous slide

catch (SQLException sqe) {throw new RemoteException (sqe.getMessage());

}finally {

try {if (stm != null)

stm.close();if (con != null)

con.close();}catch (Exception ignore) {}

}}

Page 162: Lewis 2001 SLD Introduction EJB

162

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

ejbFindByPrimaryKey// Given a Primary Key, loads the bean from the persistent storepublic AccountPK ejbFindByPrimaryKey(AccountPK pk) throws

FinderException, RemoteException {if (pk == null)

throw new FinderException ("primary key cannot be null");

// Load from the databaserefresh(pk);

// Print out some debuggingSystem.out.println("ejbFindByPrimaryKey (" + pk.m_id + ")

found");// return the primary keyreturn pk;

}

Page 163: Lewis 2001 SLD Introduction EJB

163

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

ejbLoad// Retrieves the Account data from the databasepublic void ejbLoad() throws RemoteException {

try {

refresh((AccountPK) m_ctx.getPrimaryKey());

}

catch (FinderException fe) {

throw new RemoteException (fe.getMessage());

}

}

Page 164: Lewis 2001 SLD Introduction EJB

164

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Entity Bean Lifecycle -• State DiagramState Diagram• Finder MethodsFinder Methods• Object Interaction DiagramsObject Interaction Diagrams

Page 165: Lewis 2001 SLD Introduction EJB

165

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Lifecycle of Entity Bean Class

1. newInstance()2. setEntityContext(ec)

Does not exist

Pooled Ready

ejbActivate() OR ejbCreate(args)

ejbPassivate() OR ejbRemove()

1. unsetEntityContext()

ejbFind<method>()

ejbLoad() ORejbStore() ORbusiness method

Page 166: Lewis 2001 SLD Introduction EJB

166

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Does Not Exist• When the container creates an instance, it:When the container creates an instance, it:

– Uses the default constructor– Calls setEntityContext

• Container decides when and if to create bean instancesContainer decides when and if to create bean instances• For better performance, a container may create instances For better performance, a container may create instances

when the server is started when the server is started

Page 167: Lewis 2001 SLD Introduction EJB

167

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Pooled State• Instances in the pooled state are NOT associated with an Instances in the pooled state are NOT associated with an

entity object identityentity object identity– Similar to stateless session beans in a pool; all are equal

• Even though a pooled bean has an EntityContext, certain Even though a pooled bean has an EntityContext, certain things in the EntityContext are undefinedthings in the EntityContext are undefined– For example, it is illegal to call getPrimaryKey()

• Instances in the pooled state are used to service find Instances in the pooled state are used to service find requestsrequests– Finder methods just return EJBObjects– Finder methods don’t associate the returned objects with an instance. It’s

only when you invoke a method on an EJBObject that it is associated with an instance

• It is less expensive for the container to transition an It is less expensive for the container to transition an instance from pooled to ready than to create an instanceinstance from pooled to ready than to create an instance

Page 168: Lewis 2001 SLD Introduction EJB

168

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Transitions (Pooled/Ready)• Two ways to go from pooled to ready:Two ways to go from pooled to ready:

– ejbCreate(args)• Done in response to a client call to a create(args)

– ejbActivate• Initiated by the container to service a client request when there isn’t a needed

entity in the ready state

• Two ways to go from ready to pooled:Two ways to go from ready to pooled:– ejbRemove()

• Done in response to a client call to remove– ejbPassivate()

• Initiated by the container when it decides there is no need to keep the entity in the ready state

Page 169: Lewis 2001 SLD Introduction EJB

169

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

The Ready State• Business methods may be calledBusiness methods may be called

– By client

• Container may call Container may call ejbLoad and and ejbStore– May be called multiple times– Used to synchronize bean state with underlying data store– Container may call them whenever it determines there is a need to

synchronize the instance’s state– For instance at the start and end of a transaction

Page 170: Lewis 2001 SLD Introduction EJB

170

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Creation of an Entity Bean

EJBObject

create(args)

Client EJBHomeBean class instance

ejbCreate(args)

new

ejbPostCreate(args)

Page 171: Lewis 2001 SLD Introduction EJB

171

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Passivation of an Entity Bean

ContainerBean class instance

ejbStore()

ejbPassivate()

Page 172: Lewis 2001 SLD Introduction EJB

172

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Activation of an Entity Bean

ContainerBean class instance

ejbActivate()

ejbLoad()

Page 173: Lewis 2001 SLD Introduction EJB

173

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Removal of an Entity Bean

Client EJBObjectBean class instance

remove()

ejbRemove()

Page 174: Lewis 2001 SLD Introduction EJB

174

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Summary of Entity Bean Life Cycle• When the client calls When the client calls create() and and remove(), bean bean

instances are not necessarily created and deletedinstances are not necessarily created and deleted• Activation and passivation are used but it is different Activation and passivation are used but it is different

than stateful session bean activation and passivationthan stateful session bean activation and passivation– Stateful session bean passivation writes the bean’s state to secondary storage– Entity bean passivation disassociates a bean instance from the entity’s object

identity– Stateful session bean activation reads the bean’s state from secondary storage– Entity bean activation associates a bean instance with entity object identity

• Pooling is usedPooling is used– Saves the expense of object creation– Services find requests

Page 175: Lewis 2001 SLD Introduction EJB

175

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Transactions and EJB -• General Review General Review • Transaction Overview in EJBTransaction Overview in EJB• Transaction AttributesTransaction Attributes• Transaction Isolation LevelsTransaction Isolation Levels• Bean-Managed TransactionsBean-Managed Transactions

Page 176: Lewis 2001 SLD Introduction EJB

176

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Overview of Transactions in EJB• EJB provides flexible support for transactionsEJB provides flexible support for transactions

– Supports flat transactions modeled after OMG Object Transaction Service 1.1 (OTS)

– Doesn’t support nested transactions, though it may in the future when vendors provide more support for this

– Support for distributed transactions

• Supports container-managed, bean-managed, and client-Supports container-managed, bean-managed, and client-managed transactionsmanaged transactions– The type of transaction control is defined in the transaction-type element of

the standard EJB deployment descriptor. Valid values are: Bean or Container– A client-controlled transaction is one that is started by a non-EJB client or an

EJB that is managing its own transactions

Page 177: Lewis 2001 SLD Introduction EJB

177

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Container Managed Transactions• Done by specifying transaction attributes for an EJBDone by specifying transaction attributes for an EJB

– They can be specified at a per bean or per method level– Container then generates the Tx code– Specified in the assembly section of the standard EJB deployment descriptor– This attribute is one of the following (described more fully later)

• NotSupported• Supports• Required• RequiresNew• Mandatory• Never (EJB 1.1)

Page 178: Lewis 2001 SLD Introduction EJB

178

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Transaction Propagation• The transaction manager uses the transaction attributes The transaction manager uses the transaction attributes

to determine what transaction context an invocation runs to determine what transaction context an invocation runs inin

• If necessary, it will propagate the transaction from one If necessary, it will propagate the transaction from one bean invocation to anotherbean invocation to another– This ensures that all beans touched by a transaction can be included in that

transaction when necessary

Page 179: Lewis 2001 SLD Introduction EJB

179

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

NotSupported• The bean should not run in a transactional contextThe bean should not run in a transactional context

– A container should always invoke the bean without a transaction scope– If a client calls with a transaction scope, it is suspended until the call returns,

and then resumed– The suspended transaction context is not passed to resources invoked from

the objectClient’s TX TX associated with method-- --T1 --

Page 180: Lewis 2001 SLD Introduction EJB

180

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Supports• The bean/method is invoked in the clients transaction The bean/method is invoked in the clients transaction

scopescope– If the client has one, it is passed in– If the client doesn’t have one, then there is no transaction scope

Client’s TX TX associated with method-- --T1 T1

Page 181: Lewis 2001 SLD Introduction EJB

181

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Required• If the invoking client is in a transaction, the bean is If the invoking client is in a transaction, the bean is

invoked in that transaction contextinvoked in that transaction context– If the invoking bean is not in a transaction, the bean is invoked in a new

transaction– The container attempts to commit the transaction when the method call

completes

Client’s TX TX associated with method-- T2T1 T1

Page 182: Lewis 2001 SLD Introduction EJB

182

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

RequiresNew• The bean is always invoked in a new transaction The bean is always invoked in a new transaction

contextcontext– The container starts a new transaction before invoking a method, and

attempts to commit it when the method returns– If a client is associated with a transaction, it is suspended before the

new transaction is started, and resumed when it completes

Client’s TX TX associated with method-- T2T1 T2

Page 183: Lewis 2001 SLD Introduction EJB

183

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Mandatory• The bean is always invoked in the clients transactionThe bean is always invoked in the clients transaction

– If the client tries to invoke the bean without a transaction context, the container throws the TransactionRequired exception to the client

Client’s TX TX associated with method-- errorT1 T1

Page 184: Lewis 2001 SLD Introduction EJB

184

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Never• Client is required to call without a transaction contextClient is required to call without a transaction context

– Container invokes bean without a Tx context– EJB 1.1 only

Client’s TX TX associated with method-- --T1 error

Page 185: Lewis 2001 SLD Introduction EJB

185

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Bean-Managed Transactions• EJBs with a transaction type of Bean are allowed to use EJBs with a transaction type of Bean are allowed to use

the the javax.transaction.UserTransaction interface to interface to demarcate transaction boundariesdemarcate transaction boundaries– They can access this using the EJBContext method

UserTransaction getUserTransaction()throws IllegalStateException;

– EJBContext is the superclass of SessionContext & EntityContext

– If the bean does not have the TX_BEAN_MANAGED attribute an exception is thrown

• Only allowed for Session Beans in EJB 1.1Only allowed for Session Beans in EJB 1.1

Page 186: Lewis 2001 SLD Introduction EJB

186

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Transactions and Beans• The container controls concurrent access to beans with The container controls concurrent access to beans with

transactionstransactions– Beans can only be accessed by the transaction that is active on them– Until the transaction completes, no other transaction can access it

• The container uses transactions to manage entity bean The container uses transactions to manage entity bean interaction with the database. One common pattern:interaction with the database. One common pattern:– At the beginning of a transaction, it will load the bean from the database– At the end of a transaction, it will store the bean to the database– In CMP, it does this in its generated code– With BMP, this happens when the ejbLoad and ejbStore methods are called

Page 187: Lewis 2001 SLD Introduction EJB

187

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Beans Can Take Part in Transactions• Beans can take part in transactions with the followingBeans can take part in transactions with the following EJBContext methodsmethodspublic boolean getRollbackOnly();public void setRollbackOnly();– When a bean calls setRollbackOnly, it is communicating that a

transaction should be rolled back when it is time to terminate it– It allows beans control over the outcome of a transaction– Note that this doesn’t initiate a rollback, just sets a flag– setRollbackOnly doesn’t take an argument so a bean can’t revert the

rollback request of another bean

Page 188: Lewis 2001 SLD Introduction EJB

188

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Transaction Isolation Levels - 1.1• Specification of isolation levels no longer possible in Specification of isolation levels no longer possible in

Deployment DescriptorDeployment Descriptor• For session beans with bean managed TxFor session beans with bean managed Tx

– Use the resource manager interface to set Tx isolation level

• For container managed TxFor container managed Tx– The details of how to specify the isolation level varies by server– Different servers support different levels of granularity

• Isolation functionality is an area of competition– Container generated code is responsible for managing Tx– Container code must ensure there are no conflicting isolation level

requests for a resource manager within a transaction.

Page 189: Lewis 2001 SLD Introduction EJB

189

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Transaction Isolation Levels - 1.0• The EJB provider must specify the transaction isolation The EJB provider must specify the transaction isolation

level in the DDlevel in the DD– The possible levels are

• TRANSACTION_READ_UNCOMMITTED• TRANSACTION_READ_COMMITTED• TRANSACTION_REPEATABLE_READ• TRANSACTION_SERIALIZABLE

– For session beans and entity beans with bean-managed persistence, the container sets the specified isolation level on the database connection at the start of each transaction

– For entity beans with container-managed persistence, the container ensures that the generated database calls achieve the specified isolation level

Page 190: Lewis 2001 SLD Introduction EJB

190

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Specifying Transaction Attributes• Transaction attributes are specified in the standard EJB Transaction attributes are specified in the standard EJB

deployment descriptordeployment descriptor– In EJB 1.1, this is done in the <container-transaction> section of

the assembly section– In EJB 1.0, the information is contained in the serialized deployment

descriptor

Page 191: Lewis 2001 SLD Introduction EJB

191

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

AccountBean DD Fragment<?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>

...

<assembly-descriptor>

<container-transaction>

<method>

<ejb-name>account</ejb-name>

<method-name>*</method-name>

</method>

<trans-attribute>Required</trans-attribute>

</container-transaction>

</assembly-descriptor>

</ejb-jar>

Page 192: Lewis 2001 SLD Introduction EJB

192

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Client TellerBeantransfer

AccountBean

AccountBean

deposit

withdraw

Transaction Example• A transfer involves two account objectsA transfer involves two account objects

– You withdraw from one, deposit to another– How do you do this in one transaction?

• One way to do this is to create a teller session bean that One way to do this is to create a teller session bean that has a transfer method that calls the withdraw method on has a transfer method that calls the withdraw method on the “from” account and the deposit method on the “to” the “from” account and the deposit method on the “to” accountaccount

Page 193: Lewis 2001 SLD Introduction EJB

193

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Transaction Attributes - Choice 1• There are several reasonable choices for the transaction There are several reasonable choices for the transaction

attributes. Here’s one choice:attributes. Here’s one choice:

Client TellerBeantransfer

AccountBean

AccountBean

deposit

withdrawRequiresNew

Required

Required

Page 194: Lewis 2001 SLD Introduction EJB

194

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Transaction Attributes - Choice 2• Here’s another choice. Other choices are reasonable. Here’s another choice. Other choices are reasonable.

The final choice depends upon the requirements of the The final choice depends upon the requirements of the applicationapplication

Client TellerBeantransfer

AccountBean

AccountBean

deposit

withdrawRequiresNew

Mandatory

Mandatory

Page 195: Lewis 2001 SLD Introduction EJB

195

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Environment Properties -• Allows you to specify properties in the deployment Allows you to specify properties in the deployment

descriptor and access them in the beandescriptor and access them in the bean– May be used to tailor behavior of a bean

• You use the You use the <env-entry> tag in the deployment descriptortag in the deployment descriptor– Values may be of type String, or any of the primitive wrapper types - Double, Integer, etc.

• In EJB 1.1, you retrieve the environment properties by In EJB 1.1, you retrieve the environment properties by using a special JNDI context called the using a special JNDI context called the environment environment naming context naming context (ENC)(ENC)– This is obtained in a bean by creating an InitialContext object using the

no-arg constructor– You then do lookups relative to the naming context java:comp/env– So, if you have an environment property named bank/ManagerWithdrawalThreshold, you will look it up as java:comp/env/bank/ManagerWithdrawalThreshold

Page 196: Lewis 2001 SLD Introduction EJB

196

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Setting Environment Properties• Let’s say we want to control large withdrawals in our Let’s say we want to control large withdrawals in our

Account beanAccount bean– For instance, any withdrawal over $1000 will need approval from a manager– We don’t want to hard code the $1000 limit. It may very likely change– We can put it in the deployment descriptor, and then retrieve it in the bean

• Here’s an environment property from our bank DDHere’s an environment property from our bank DD– Name is ManagerWithdrawalThreshold– Type is Integer– Value is 1000

<env-entry>

<env-entry-name>bank/ManagerWithdrawalThreshold</env-entry-name>

<env-entry-type>java.lang.Integer </env-entry-type>

<env-entry-value>1000</env-entry-value>

</env-entry>

Page 197: Lewis 2001 SLD Introduction EJB

197

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Using Environment Properties• In our withdrawal method we can look up this property as In our withdrawal method we can look up this property as

followsfollowspublic void withdrawal(int amount)

throws ProcessingErrorException {

// Check if balance large enough to cover withdrawal

// If balance is OK, check if we need manager approval

InitialContext ctx = new InitialContext();

Integer threshold = (Integer)ctx.lookup(“java:comp/env/bank/ManagerWithdrawalThreshold”);

if (amount > threshold.intValue()) {

// Get manager approval

}

// … etc. NOTE - Exception handling not shown

ctx.close();

}

Page 198: Lewis 2001 SLD Introduction EJB

198

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Security -• GoalsGoals• RolesRoles• Users and GroupsUsers and Groups• Types of SecurityTypes of Security• Example of Programmatic SecurityExample of Programmatic Security• Logging OnLogging On

Page 199: Lewis 2001 SLD Introduction EJB

199

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Goals of EJB security• Integrate application security into the EJB programming Integrate application security into the EJB programming

modelmodel– Authentication– Access control – Portability– Ease of use

• Allow security policies to be set by the application Allow security policies to be set by the application assembler or deployer rather than being hard-coded at assembler or deployer rather than being hard-coded at development time development time

• Work with existing security systemsWork with existing security systems• Fit into the overall J2EE environmentFit into the overall J2EE environment

Page 200: Lewis 2001 SLD Introduction EJB

200

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Roles• A role is a logical name that identifies a job function for A role is a logical name that identifies a job function for

the purpose of enforcing security policiesthe purpose of enforcing security policies– For example, a person in a manager role might have greater authority than a

person in a customer role– Roles may be defined by the bean developer or the application assembler– A user may serve in more than one role

• Role names (e.g., “Customer”) are specified and used Role names (e.g., “Customer”) are specified and used within the standard EJB deployment descriptor to set the within the standard EJB deployment descriptor to set the basic security policybasic security policy

Page 201: Lewis 2001 SLD Introduction EJB

201

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Example: Roles & Method Permissions• Fragment of role and method permission declarations in the Fragment of role and method permission declarations in the

standard EJB deployment descriptor:standard EJB deployment descriptor:<ejb-jar><ejb-jar>...... <assembly-descriptor> <assembly-descriptor>...... <security-role> <security-role> <description></description> <description></description> <role-name>Customer</role-name> <role-name>Customer</role-name> </security-role> </security-role> <method-permission> <method-permission> <description></description> <description></description> <role-name>Customer</role-name> <role-name>Customer</role-name> <method> <method> <ejb-name>teller</ejb-name> <ejb-name>teller</ejb-name> <method-name>*</method-name> <method-name>*</method-name> </method> </method> </method-permission> </method-permission>... ...

Page 202: Lewis 2001 SLD Introduction EJB

202

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Users and Groups• Individual users (“principals”) are defined to the serverIndividual users (“principals”) are defined to the server• Users can be and usually are assigned to groups (e.g, Users can be and usually are assigned to groups (e.g,

“JavaConference”)“JavaConference”)• The groups are then mapped to rolesThe groups are then mapped to roles

– For example, all users in group “JavaConference” might be mapped to the logical role of “Customer”

• Each server provides a way to define users and groupsEach server provides a way to define users and groups– The details vary by server– In Weblogic, the default is to use the Weblogic properties file– In the J2EE Reference Implementation, you use the realmtool utility– Production servers also provide ways to hook into existing security systems.

For example, Weblogic can be configured to use the NT security database

Page 203: Lewis 2001 SLD Introduction EJB

203

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Example: Mapping a Group to a Role• Fragment of role assignment in the Weblogic-specific Fragment of role assignment in the Weblogic-specific

deployment descriptor:deployment descriptor:<weblogic-ejb-jar><weblogic-ejb-jar>...... <security-role-assignment> <security-role-assignment> <role-name>Customer</role-name> <role-name>Customer</role-name> <principal-name>JavaConference</principal-name> <principal-name>JavaConference</principal-name> </security-role-assignment> </security-role-assignment>......</weblogic-ejb-jar></weblogic-ejb-jar>

Page 204: Lewis 2001 SLD Introduction EJB

204

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Example: Definition of Users & Groups• Definition of two users and a group in the Weblogic Definition of two users and a group in the Weblogic

properties file:properties file:weblogic.password.Student1=passwordweblogic.password.Student1=passwordweblogic.password.Student2=passwordweblogic.password.Student2=passwordweblogic.security.group.JavaConference=Student1,Student2weblogic.security.group.JavaConference=Student1,Student2

Page 205: Lewis 2001 SLD Introduction EJB

205

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Types of Security• Declarative securityDeclarative security

– Security definitions (groups and roles) are specified via deployment descriptors. Container is responsible for verifying that the caller is in the correct role before it calls the bean method

• Programmatic securityProgrammatic security– Security definitions (groups, and roles) are specified via deployment

descriptors– The bean:

• Contains code to determine if a user is in a specific role and respond accordinglyOR

• Gets the identify of the caller and uses it to validate the request– For example, AccountBean’s withdraw method might reject the request if

the caller’s identify doesn’t match the account’s name

Page 206: Lewis 2001 SLD Introduction EJB

206

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Example of Programmatic Security• public void withdraw(double amount) throws ProcessingErrorException{public void withdraw(double amount) throws ProcessingErrorException{

System.out.println("AccountBean withdraw() called."); System.out.println("AccountBean withdraw() called."); // Does the caller's identity match the account name? // Does the caller's identity match the account name? String caller = entityContext.getCallerPrincipal().toString(); String caller = entityContext.getCallerPrincipal().toString(); System.out.println("caller = " + caller); System.out.println("caller = " + caller); if (caller.equals(m_name)) { if (caller.equals(m_name)) { if (this.getBalance() < amount) { if (this.getBalance() < amount) { throw new ProcessingErrorException("Account cannot cover throw new ProcessingErrorException("Account cannot cover withdrawal of " + amount); withdrawal of " + amount);

} } else { else { this.m_balance -= amount; this.m_balance -= amount;

} } } } else { else { throw new ProcessingErrorException(caller + throw new ProcessingErrorException(caller + " denied access to " + m_name); " denied access to " + m_name); } }}}

Page 207: Lewis 2001 SLD Introduction EJB

207

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

Logging On• Users who do not logon explicitly are assigned a default Users who do not logon explicitly are assigned a default

userid and roleuserid and role– Actual values vary by server and are sometimes configurable– The default userid for Weblogic is “guest”– The default role for Weblogic is “everyone”

• So far, all of the examples in this tutorial have used the So far, all of the examples in this tutorial have used the default valuesdefault values

• User identity is assigned when the JNDI InitialContext is User identity is assigned when the JNDI InitialContext is createdcreated– In Weblogic, you simply specify the principal and credential properties– In J2EE, this is handled by a client container

• By default, security information is propagated from one By default, security information is propagated from one J2EE component to another (e.g., from a servlet to an J2EE component to another (e.g., from a servlet to an EJB) EJB)

Page 208: Lewis 2001 SLD Introduction EJB

208

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- EJB Programming Restrictions -• The EJB specification places certain restrictions on the The EJB specification places certain restrictions on the

bean code. These restrictions are necessary for the bean code. These restrictions are necessary for the container to do its job:container to do its job:– No read/write static fields. Static fields should be declared as final– No use of thread synchronization primitives– Must not try to create and/or manage threads– No use of AWT to attempt to display information– No use of java.io.* classes to access files or directories

• System.out.println appears to be an exception to this– No attempt to create a class loader– No attempt to create/change the security manager– Must not try to load a native library– Must not create a socket or attempt listen to a socket

Page 209: Lewis 2001 SLD Introduction EJB

209

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- EJB 2.0 -• EJB 2.0 is a major revision to the EJB 1.1 specificationEJB 2.0 is a major revision to the EJB 1.1 specification• Includes a more flexible and portable programming Includes a more flexible and portable programming

model for CMP entity beansmodel for CMP entity beans– EJB 2.0 containers/servers must still support the EJB 1.1 model– Standardized query language for defining finder methods (EJB QL)– Handles more complex relationships

• Bean to dependent objects• Dependent objects to beans• Bean to bean

– Adds support for new home interface methods

• Support for JMSSupport for JMS– An EJB can be a message producer or consumer– An EJB that wishes to produce a message uses the JMS API – A new type of bean, MessageDrivenBean, has been defined to make it easy

for developers to create secure and scalable message consumers

Page 210: Lewis 2001 SLD Introduction EJB

210

Introduction to EJB Copyright © 2001, LearningPatterns.com, Inc. O'Reilly Conference on Java

- Tips -• Use instances of serializable classes to reduce network Use instances of serializable classes to reduce network

roundtripsroundtrips• Avoid client-controlled and bean-managed transactions if Avoid client-controlled and bean-managed transactions if

possiblepossible• Avoid chaining stateful session beansAvoid chaining stateful session beans• Encapsulate entity bean access inside session beansEncapsulate entity bean access inside session beans• If using entity beans, investigate vendor-specific If using entity beans, investigate vendor-specific

performance optionsperformance options– If the database is not accessed outside of the EJB server, the container should

be able to reduce the number of calls to ejbLoad()– If the entity bean state has not changed, ejbStore should not update the database

• some containers give the bean a way to tell the container to not call ejbStore– Some containers support timer-based calls to ejbLoad(). This is useful for

some beans