Enterprise Java Beans

  • Uploaded by: booksofpavan
  • 0
  • 0
  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Enterprise Java Beans as PDF for free.

More details

  • Words: 7,061
  • Pages: 89
Enterprise Java Beans A Component Technology

EJB

1. Learning objectives 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14.

Component Technology characteristics Standard Infrastructure needs Application Servers Containers J2EE Architecture and its components EJB Model, Overview & JNDI EJB Specifications, Roles EJB Design Approaches, Architecture Types of Beans EJB Interfaces & Session Contexts Life cycles of different Beans EJB Jar files & Deployment Descriptor Sample examples Components comparison

A STAR or a different color represents important points to NOTE

4. Component Technology Components are deployable units that provide a business service to their clients. • • • •

Each component provides an interface in the form of operations, properties and events Components can be developed in any language such as JAVA,C++,VB Components are frequently organized into application frameworks for vertical domains Component models such as Active X and EJB standardize communication and allow for prebuilt purchased components

5. Component Characteristics Components Characteristics include 

Properties



Reusability



Operations



Shareable



Events



Distributable



Deployable



Self Containment



Self description

6. Component P O E Components should have a mechanism for exporting 

Properties



Operations



Events

7. Deployable Components

Components are operation independent of • • • •

Hardware The underlying operating system Their Application Server The network protocol they use

8. Reusable Components

Component services can be used as a part of business logic of other components

9. Shareable Components

If multiple clients are using a component simultaneously, the component will provide the same quality of service to all the clients

10. Distributable Components Components should provide services to clients running locally or remotely

EJB Container EJB

Possible Remote CLIENTS

Local CLIENTS

Remote CLIENTS

Remote CLIENTS

Remote CLIENTS

11. SelfContained Components Components should only contain the code necessary to implement their services Infrastructure services should be injected by the execution environment

12. Standard Infrastructure Needs Standard infrastructure services include • • • • • • • • •

Directory Services Distributed transaction management Security management Concurrent access management Persistence management Resource pooling (e.g. DB connections) Administration interface Load Balancing Fault tolerance

13. Applicatoin Servers An application server provides the infrastructure and services to run components/applications Application Server products are mostly

J2EE based solutions

Non-J2EE solutions (PHP, Cold Fusion, Perl, etc.)

Microsoft Solutions (COM, ASP.Net VB.Net,C# etc.)

14. Object Pooling An application server may create a pool of bare objects that may be used as EJBs when requests are made

App Server EJB Container EJB EJB CLIENT Network CLIENT

Pool EJB

EJB

EJB EJB

DB

15. Directory of Application Servers Application Servers provide clients access to software or other applications that run only on the server Examples include web servers, e-mail servers and database servers Popular Application Servers are: • • • •

I.B.M. Web Sphere BEA Web Logic Sun Java System Application Server 7.x Jboss

The full list with vital statistics are available at http://www.devx.com/enterprise/html/16268 http://www.javacommerce.com/articles/serverlist.htm

16. Container Container means a pre developed Software

A Container :

Fish cannot survive outside water & EJB’s cannot survive outside containers

• • •

provides the environment in which a bean executes generates Home Object generates EJB Object Implicit Middleware



manages individual bean instances

&

To increase capability. clustering is taken care by the vendor

Transaction

gained through declaration

Container provides System services like

Persistence

Security

Connection

Pooling

Threading

App Server EJB Container EJB STUB CLIENT

Network

Container intercepts requests

EJB EJB

Container knows what to do, as you describe everything in a special descriptor file

17. J2EE Overview Deployment Descriptors (DDs)

Web Server Independence Application Server Independence Database Independence Enterprise Resource Management Services Distributed Communication Services Common Programming Services Operating System Independence Hardware Independence

Enterprise Components services

standards

component-based

J2EE Container/Server J2EE Interfaces Management Services Deployment/Configuration J2SE Language/Interfaces J2SE Runtime Operating System Platform Hardware Platform

Deploy Tools

Data

18. J2EE 1.4 APIs J2EE defines a model for developing multi-tier, web based, enterprise applications with distributed components Applet Container HTTP/S Applet J2SE

Web Container JSP

Application Client Container HTTP/S

J2SE

X C B S R C S

JAF

JMX A D N B I C

EJB JAX- J J RPC A A X C SAAJ R C

W J E M B S S

Java Mgmt J J J C N D Mail T O D B JAF JMX A N

J2SE

RMI/ IIOP

I

J2SE 4 TIER

3 TIER

Client JAX- J W Mgmt J J C RPC A E D M O X B JMX B SAAJ S N R S C

EJB Container

Servlet

JSP Servlet ENGINE JAX- J J W J Java Mgmt J J J C RPC A A E M Mail N D T O SAAJ

RMI/ IIOP

EIS DAO DB

2 TIER

MainFrames

For all the APIs refer http://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html

C

19. Enterprise JavaBeans Model EJB is Sun’s J2EE transactional, vendor-neutral, enterprise component architecture providing • • • •

Modelling of business entities as well as synchronous and asynchronous processes Persistence via explicit code (bean-managed) or via services of the EJB server (container-managed) Vendor neutrality and inter operability XML driven deployment and configuration

EnterpriseJava Beans EJBs need a Container EJBs are deployable components EJBs are assembled to form a complete Appl EJBs are based on RMI IIOP and JNDI Technologies

!=

Java Beans JBs do not need a container JBs are development components JBs are Classes with no argument constructor JBs have a get and a set method on them

20. EJB Overview EJB simplified distributed development –Develop EJB implementation logic –Define Home/Local Remote/Local interfaces –Container delegates client calls –Container manages resources/lifecycle/callbacks

EJB Client LocalHome

Client Process

EJB Client

create remove find STUB

Home create remove find Remote invoke

Network

Local

invoke STUB

EJB Impl create timeout remove passivate activate find load invoke store

Delegate Delegate Delegate Delegate

EJB Pool

J2EE EJB Container/Server

21. When to use EJB If any of these requirements hold for your application • • •

the application must be scalable and distributable Transactions will be required to ensure data integrity the application will have a variety of clients

22. Java Naming and Directory Interface (JNDI) JNDI Provides a standardized way of accessing resources in a distributed environment Protocol and naming service agnostic • DNS • NDIS • LDAP • X.500 Implemented by the javax.naming package and three other packages below it javax.naming.InitialContext is the entry point to the EJB Server • bind – associates a name with an object • lookup – finds an object given the name

23. EJB Specification The EJB specification defines interfaces between • • •

the EJB and its container the container and the application server the container and the client

24. EJB Roles Service & Tool Provider provides Server, Container and integrates with distributed facilities

EJB Provider

Application Assembler

creates EJB components

assembles apps from per-built EJB comp

Deployment Specialist deploys apps and understands architecture issues

supplies tools

Tools Provider

develops EJBs EJB Provider

builds application Application Assembler

deploys system

Deployer

supplies Application Server

Application Server Provider

System Administrator maintains deployment

25. EJB Design Approaches EJB model is based on three basic design approaches for building distributed component systems Stateless server approach Persistent Object approach

Session-oriented approach

The EJB specification provides these as Stateless session Beans Stateful session Beans All EntityBeans implements

Interface

javax.ejb.EntityBean extends

Implementing one of these interfaces indicates your JAVA class is an EJB.

Message driven beans Entity Beans

All SessionBeans implements

All MessageDrivenBeans

Interface

javax.ejb.SessionBean

implements

Interface

javax.ejb.MessageDrivenBean

extends

extends

javax.ejb.EnterpriseBean interface extends It is only a marker Interface java.io.Serializable and there are no methods to Implement. Serialization is the reason EJB is distributable.

As all these are extending the two Interfaces hence they have the behavior of both the Interfaces.

26. EJB Architecture Naming

Service such as LDAP

2

Naming

Transaction Persistence Server Security A SERVICES

H

Server B

App Server

H

JNDI Initial Context H

3

1 H

Home Obj Stub

Application Client EJB

Obj Stub

Home Interface

4

Home Object (FACTORY)

10

5 6

creates

RMI/IIOP

7

EJB Container

8

Remote Interface

EJB Object (Wrapper)

EIS

EJB

DB

(Business Logic Class)

9

MainFrames

delegates request

11 Container implements/autogenerates code for the Interfaces

we have written

We will write only this Container manages TRANSACTIONS, PERSISTENCE, SECURITY & POOLING

27. EJB Flow Chart C

Start

ask JNDI Server for the Home Object

1

JNDI Server returns ref of Home Stub

2

ask Home for the EJB Object

invokes a business method thru Remote Stub

7

goes to the JNDI Server and gets the EJB Object

8

Remote Interface then wraps a request to the Bean class

3

creates EJB Object

4

returns reference of Remote Stub

5

C

6

9

Clients receives the required info

End

28. Client View of EJB ENTITY BEANS are like NOUNS as they represent data or data related logic.

App Server EJB Container EJB Home or EJB Local Home

Application Client

RMI/ IIOP

EJB Object or EJB Local Object

JMS Destination

e.g •Bank teller •Credit Card authorization

Session Bean instance

Entity Bean instance

e.g •Bank account balance •Purchase order

Message Driven Bean instance

e.g •Stock trade messages •Work flow messages

SESSION BEANS are like VERBS as they represent action or business process related logic. MESSAGE DRIVEN BEANS have message oriented logic. If all the processing is done in the same Application server then we use EJB Local(Object & Home) interfaces. Using local interfaces are optional. Local interfaces pass by REFERENCE and EJB (Object/Home) pass by VALUE. Using local interfaces avoids stubs, skeletons, network and so it is faster.

29. EJB Client EJB clients utilizes the Java Naming and Directory Interface (JNDI) to look up for the references to home interfaces use home and remote EJB interfaces to utilize all EJB-based functionality

30. EJB Home Interface EJB home interfaces extends javax.ejb.EJBHome EJB home interfaces provide operations for clients to • create EJBs • remove EJBs • find handles to EJB remote interface objects • have its stub placed into JNDI at startup

31. EJB Remote EJB remote interfaces extends javax.ejb.EJBObject EJB remote interfaces • provide business-specific functionality of an EJB • are similar to RMI Remote interface

32. EJB Implementation EJB implementation Class in which EJB developer codes the business methods defined in the bean’s component interface(s) to provide any application specific • • • • • • •

business method invocation creation removal finding activation passivation, database storage database loading logic

33. Session Context The Container has already reference to the bean The bean interacts with the Container through SessionContext and • • •

retrieves home interfaces gets and sets transactions attributes obtains security attribute

The setSessionContext method is used to inform the bean about the session context

34. Stateless Session EJB Stateless session EJBs have the following behaviour • • • • • •

provide a single use service do not maintain state on behalf of the client are relatively short lived do not survive EJB server crashes any two instances of the same stateless session EJB type are always identical each instance can be shared by multiple clients

35. Stateless Session EJBs View Stateless Session

EJB Client LocalHome Local

Client Process EJB Client

Home Remote

Network

Logic input

EJB Pool

output

J2EE EJB Container/Server

EJB Impl Developer View EJB gets requests and generates responses An instance can service multiple clients over time EJB Client Developer View creates it, uses it and then it’s done

EJB Container View can pull instances from pool upon client request can shrink/grow pool as needed A few pooled beans can service thousands of clients

36. Life Cycle of Stateless Session Bean Each method call is an invocation from the container to the Bean

Container decided it needs more instances in the pool to service clients

Bean Instance does not exiist Class.newInstance() setSessionContext()

ejbRemove()

ejbCreate()

Pool of equivalent method ready instances Client called another Transactional business method on the EJB Object.

Transactional Business Method

Client called remove() on the EJB object (or the client times out)

37. Stateful Session EJBs View Stateful Session

EJB Client LocalHome Local

Client Process EJB Client

Home Remote

Network

Logic State input

EJB Pool

output

J2EE EJB Container/Server EJB Impl Developer View EJB gets requests and generates responses An instance can service multiple clients over time EJB Client Developer View creates it, uses it and then it’s done EJB Container View can pull instances from pool upon client request can shrink/grow pool as needed

38 .Life Cycle of Stateful Session Bean Each method call is an Invocation from the container to the Bean

Client called remove() on the EJB object (or the client times out)

Bean Instance does not exiist

Client called create(args) on the home Interface.

Class.newInstance() setSessionContext() Client called a non-transactional business method on the EJBObject

Bean instance is ready to service method calls

ejbPassivate() ejbActivate()

Client called a transactional business method on the EJB Object

beforeCompletion() afterBegin()

Client called another Transactional business method on the EJB Object.

Client times out

ejbCreate(args) Non-Transactional Business Method

If transaction ended in a commit..

ejbRemove()

Container’s limit of instantiated beans are reached, so it must swap your bean out.

afterCompletion(true)

Bean instance is within a transaction and ready to service method calls

afterCompletion(false)

Client called a method on a passivated bean, so Container must swap your Bean back in

We need to write all the methods that are there in the

Transactional Business Method

Bean instance is in the passive state

Implemented class

If we implement Javax.ejb.SessionSynchronization then we need to write these methods.

If transaction ended in an abort.

39. Stateful vs Stateless Stateful Bean

Stateless Bean

A stateful bean contains a conversational state that is retained across method calls and transactions.

A stateless bean does not have any state between calls to its methods.

The create method takes arguments e.g. create(String id) , create(int I , String id) There can be one or more arguments in a create method

The create method does not take arguments e.g create() There can be no arguments in a create method

e.g An EJB that unzips 100 bytes of data An EJB that checks to see if a stock symbol is valid

e.g An EJB that books a flight and rents a car at a travel agent’s web site.

Method by method comparison can be seen in EJB20Matrix.doc at http://www.volantec.biz/cmp20.htm

40. Entity Bean Entity Bean has the following behaviour • • • • •

They are a representation of persistent data They can survive a crash Multiple clients can be using EJBs that represent the same data The EJB instance contains a copy of the data in the persistent store has a Primary key like in a Database record.

41. BMP Entity EJBs (BMP = Bean-Managed Persistence) Entity Bean (BMP)

EJB Client LocalHome Local

Client Process EJB Client

Hand Coded Logic

Home Remote

Network

EJB Pool

input output

J2EE EJB Container/Server

Persisted objects (via hand-coding)

data

EJB Impl Developer View encapsulates data from a data source as objects implements object-relational mapping (often JDBC) implements inserts, deletes, queries and updates EJB Client Developer View creates, finds, updates and removes entity objects EJB Container View persists and manages concurrent access of instances

42. Primary key class • 



Applicable only to entity beans Uniquely differentiates instances sharing the same EJBHome Class must be a legal value type in RMI-IIOP    

Implements java.io.Serializable all the members should be public It should implement hashCode() and equals(.. ) methods does not implement java.rmi.remote

43. Shared Entity Bean When multiple clients share an Entity EJB they • • •

receive their own instance share the underlying data do not have to handle synchronization

App Server EJB Container

CLIENT

EJB Network

CLIENT

EJB

DB

44. Life Cycle of BMP Entity Bean Each method call is an Invocation from the container to the Bean

Container decided it needs another Entity Bean insinstance

newInstance()

unsetEntityContext() JVM will garbage collectt and call finalize()

setEntityContext() Client called instance independent ejbHome() Business method

Client called a finder Method on the home interface ejbHome()

Client called create() on the home interface (this will Create new database data)

Container determined that the database is out of synch with the bean. The Bean needs to load the new Database data.

ejbFind()

Pooled

Activates the Bean

Passivates the Bean

ejbCreate()

ejbActivate()

ejbStore()\

ejbPostCreate()

ejbLoad()

ejbPassivate()

ejbLoad() Client called a business method on a EJBObject

Container decided it doesn’t need the Entity Bean instance anymore

Does not exiist

Ready

Business Method

ejbRemove()

ejbStore()

Client called remove() on the EJB object (this will destroy Database data)

Container determined that the database is out of synch with the bean. The Bean needs to store its Data into the Database

45. CMP Entity EJBs (CMP = Container-Managed Persistence) Entity Bean (CMP)

EJB Client LocalHome Local

Client Process EJB Client

Generated Logic

Home Remote

Network

EJB Pool

input output

J2EE EJB Container/Server Persisted objects (via container services) data

Persistence DDs

EJB Impl Developer View specifies CMP fields and relations among entities in DDs specifies queries via EJB-QL in DDs uses tools to map standard object view to specific relational view EJB Client Developer View creates, finds, updates and removes entity objects EJB Container View persists and manages concurrent access of instances

46. Life Cycle of CMP Entity Bean Each method call is an Invocation from the container to the Bean

NOTE : BMP has no ejbSelect()

Container decided it needs another Entity Bean in

newInstance()

unsetEntityContext() JVM will garbage collectt and call finalize()

setEntityContext() Client called instance independent ejbHome() Business method ejbHome() Client called create() on the home interface (this will create new database data)

Container determined that the database is out of Synch with the bean. The Bean needs to load the new Database data.

Client called a finder method on the home Interface, or bean called its own ejbSelect() method to locate Database data

ejbFind() or ejbSelect()

Pooled

Activates the Bean

Passivates the Bean

ejbCreate()

ejbActivate()

ejbStore()\

ejbPostCreate()

ejbLoad()

ejbPassivate()

ejbLoad() Client called a business method on a EJBObject

Container decided it doesn’t need the Entity Bean instance anymore

does not exiist

Ready

Business Method Or ejbSelect()

ejbRemove()

ejbStore()

Client called remove() on the EJB object (this will destroy Database data)

Container determined that the database is out of Synch with the bean. The Bean needs to store its Data into the Database

47. BMP vs CMP Bean Managed Persistance

Container Managed Persistance

BMP offers a tactical approach

CMP is more strategic

The developer takes care of handling persistence

Vendor takes care of everything by using O-R or OODB mappings using metadata.

BMP uses hard coded queries so we can optimize our queries

A developer cannot optimize performance as the vedor takes care of it

We should start developing CMP beans, unless we require some kind of special bean, like multi-tables, that cannot be completely realized with a single bean. Then when we realize that we need something more or that we prefer handling the persistence (performance issue are the most common reason), we can change the bean from a CMP to a BMP

Method by method comparison can be seen in EJB20Matrix.doc at http://www.volantec.biz/cmp20.htm

48. Message Driven Bean MDB has the following behaviour • Is stateless • is a JMS listener • when a JMS message arrives the method onMessage() is executed • does not survive EJB server crashes • provides a single-use service • is relatively short lived • is only a bean class – no interfaces

49. Message Driven EJBs Producer Process Message Producer

Messaging

Messaging Service Message

Network

API

Message-Driven Bean

Message Queue

Handler Logic Message

input

Message Listener

EJB Pool

J2EE EJB Container/Server

Asynchronous messaging EJB Impl Developer View gets async requests via messaging paradigm-specific interface An instance can service multiple clients over time EJB Client Developer View Messages sent to endpoint & handled by messaging service Specific to particular messaging paradigm used EJB Container View pulls instance from pool and delivers message

50. Life Cycle of Message Driven Bean Each method call is an Invocation from the container to the Bean

Container decided it needs another Message DrivenBean Instance

Does not exiist

newInstance() ejbRemove() setMessageDrivenContext() ejbCreate()

Pooled

onMessage()

51. Deployment Deployment involves taking an EJB compliant bean and • • • •

creates XML that describes the EJB packages the bean and XML into a Jar generates container files for the EJB configures properties of the EJB Server

Declaring without programming helps the application assembler to change the XML file easily. BEAN Provider declares components’ middleware service requirements in a DEPLOYMENT DESCRIPTOR File. Bean Provider describes how the Container should perform the LifeCycle Management, Persistence, Transaction and Security.

52. Other interfaces and classes 



Local interfaces are used for access within server context 

javax.ejb.EJBLocalHome



javax.ejb.EJBLocalObject

Interfaces for serializing EJB references  



E.g.: •Inter component calls •Servlet invocation

HomeHandle - reference to EJBHome Handle - reference to EJBObject

EJBMetaData interface provides mechanism to gather information about the bean   

reference to EJBHome object Home, component interface and primary key classes functions to determine bean type

53. Exceptions 



System exceptions are unchecked and propagated to the client as java.rmi.RemoteException Application exceptions are checked and propagated to the client as a descendant of java.lang.Exception  EJB-specific exceptions include FinderException, CreateException, RemoteException (all in javax.ejb package)  Business method exceptions are at the discretion of the EJB developer

EXAMPLE 1 STATELESS BEAN

54. Steps to Develop an EJB C

Start

Write .java files for the BEAN, HOME and REMOTE interfaces Write the Deployment descriptor Compile all the STEP 1 files into .class files Using the Jar utility create an EJB Jar file containing STEP 2 & STEP 3 files C

1 5 2

Configure your EJB Server. E.g DB connections thread pooling etc Then copy the EJB Jar file

Start your EJB container and 6 confirm that it has loaded the EJB Jar file.

3 Connect to your EJB by writing a test 7 Client .java file compile it and run it . 4 End

Please download the trial Application Server software from the links provided on the Reference slide at the end.

55. Hello World Object Model using RMI We will apply the previous slide flow chart procedure to make up our first EJB example These Interfaces comes with Java 2 Platform java.rmi.Remote

java.io.Serializable

These Interfaces comes with EJB distribution Javax.ejb.EJBObject

Javax.ejb.EJBHome

Javax.ejb.EnterpriseBean Javax.ejb.SessonBean

Supplied by the Bean Provider / Developer/ We will write ! Hello world Remote Interface

Hello World Home Interface

We need to CODE only this block

Generated for us by the Container verdor’s tools Hello world EJB Object

Hello World Home Object

Hello World Bean Implementation Class

NOTE : Object implementation is Vendor specific. The container may implement either A single object for each client or A single object for all the clients.

56. Hello World Object Model using LOCAL If all the processing is done in the same Application server then we use EJB Local (Object & Home) interfaces. Using local interfaces are optional. Local interfaces pass by REFERENCE and EJB (Object/Home) which is the previous slide model you saw will pass by VALUE. As these interfaces does not extend Java.rmi.Remote the overhead of creating stubs, skeletons,network traffic is avoided and so it is faster but the drawback is if our code relies on Local interfaces then we cannot call a bean remotely.

No Network so LOCAL IMROVES PERFORMANCE

These Interfaces comes with Java 2 Platform java.rmi.Remote

These Interfaces comes with EJB distribution Javax.ejb.EJBLocalObject

Javax.ejb.EJBLocalHome

java.io.Serializable Javax.ejb.EnterpriseBean Javax.ejb.SessonBean

Supplied by the Bean Provider / Developer/ We will write ! Hello world LocalInterface

Hello World Local Home Interface

We need to CODE only this block Generated for us by the Container verdor’s tools Hello world EJB LocalObject

Hello World Local Home Object

Hello World Bean Implementation Class

NOTE : Object implementation is Vendor specific. The container may implement either A single object for each client or A single object for all the clients.

57. HelloBean Home Interface EJB Example requirement : When the client interacts with the EJB we need to return a “Hello World” greeting. To provide an EJB with the above requirement we have to create Remote & Home Interfaces , Bean Business logic class and a deployment descriptor. For clarity please see the previous slide Hello World Object Model using RMI. This is the Home Interface for the Home EJB (HelloBean). Rules of Java says package declaration should be at the beginning and ends with a semi colon package examples ; import java.io.Serializable; import java.rmi.RemoteException; Importing the required files import javax.ejb.CreateException; import javax.ejb.EJBHome; public interface HelloHome extends javax.ejb.EJBHome Our interface HelloHome is extending EJBHome means it has all the behaviour of EJBHome { Hello create() throws java.rmi.RemoteException, javax.ejb.CreateException; Interface methods should end with a semicolon ;

This method creates/manufactures the EJBObject and returns it . This create() method corresponds to the ejbCreate() method in HelloBean. As for every Interface we need implementation,Note so Container will implement code) forRemote this Home In Home Interface we are(autogenerate throwing 2 exceptions andInterface Create . for us, which is the EJBHome Object

}

NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.

58. HelloLocalHome Interface So now lets code the HelloLocalHome Interface This is the LocalHome Interface for the Home EJB (HelloBean).

package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon import javax.ejb.EJBLocalHome; import javax.ejb.CreateException; import javax.ejb.FinderException; import java.util.Collection; Our interface HelloLocalHome is extending EJBLocalHome means it has all the behaviour of EJBLocalHome

public interface HelloLocalHome extends javax.ejb.EJBLocalHome { HelloLocal create() throws javax.ejb.CreateException; This methodso creates/manufactures the EJBLocal Objectcode) and returns . This create() corresponds to the As for every Interface we need implementation, Container will implement (autogenerate for this itmethods Local Home for method us, isa the LocalHome Interface should endwhich with semicolon ; Object ejbCreate() method in HelloBean. Note LocalHome Interface we are throwing Create and not Remote there is no network NOTE : Rules of In Interfaces states that there should be only no implementation so you exception will find as only method signatures.

}

59. HelloBean Remote Interface So lets code the Remote Interface Clients interact with the EJB Object through this Remote interface that is why we need to write this interface.

package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon import java.util.*; Importing the required files import javax.ejb.EJBObject; import java.rmi.RemoteException; public interface Hello extends javax.ejb.EJBObject Our interface Hello is extending EJBObject means it has all the behaviour of EJBObject { public String hello() throws java.rmi.RemoteException; As our requirement wants a business logic to greet Hello World a single method would be sufficient . } Interface methods should end with a semicolon ; As Remote interface is used to interact with the Bean we need to mirror all the method signatures what are there in a Bean class so that is why we are writing only one method in this Remote interface. Note EJB specification states that all remote calls should throw RemoteException so we are throwing it. As for every Interface we need implementation, so Container will implement (autogenerate code) for this Remote Interface for us, which is the EJBObject

NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.

60. HelloLocal Interface Clients interact with the EJB Object through this Local interface when there is no network involved..

package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon import javax.ejb.EJBLocalObject; public interface HelloLocal extends javax.ejb.EJBLocalObject Our interface Hello is extending EJBLocalObject means it has all the behaviour of EJBLocalObject { Interface methods should end with a semicolon ; public String hello() ; As our requirement wants a business logic to greet Hello World a single method would be sufficient . } As Local interface is used to interact with the Bean we need to mirror all the method signatures what are there in a Bean class so that is why we are writing only one method in this Local interface. Note As there is no remote calls no Remote Exception is thrown

As for every Interface we need implementation, so Container will implement (autogenerate code) for this Local Interface for us, which is the EJB Local Object

NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.

61. The Bean Class So now lets code the actual EJB Class This is where we will code our Business logic

package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon import java.util.*; Importing the required files import javax.ejb.*; public class HelloBean implements javax.ejb.SessionBean NOTE : Note If it is: Entity this isBean a class weand will not implement an Interface javax.ejb.EntityBean like the other two and (Home if it is /Message Remote).driven This isbean implementing we will implement SessionBean javax.ejb.MessagedrivenBean so it is a Session Bean As per the below note in red we need to write all the methods what are in javax.ejb.SessionBean . { private SessionContext This ctx; ejbCreate() corresponds to the Homeobject Create(). NOTE : in Stateless Bean no arguments are sent public void ejbCreate() { System.out.println(“ejbCreate()”); } There is nothing much to clean up. public void ejbRemove() { System.out.println(“ejbRemove()”);} These are called Management or In Statelss Bean ejbActivate public void ejbActivate() { System.out.println(“ejbActivate()”);} Call back methods and ejbPassivate Do not apply public void ejbPassivate() { System.out.println(“ejbPassivate()”); } public void setSessionContext(javax.ejb.SessionContext ctx) { Storing the Context in a variable so that it can be queried later . NOTE : Because it is a Session Bean we are using setSessionContext for Entity Bean we this.ctx = ctx; } use setEntityContext and for Message Driven Bean we use setMessageDrivenContext. public String hello() { System.out.println(“Hello()”); return “Hello World! “ ; } Our Business method which matches } our Remote Interface method signature Java does not support multiple inheritance so you can extend only one class. To overcome this they had given us the Implementation option . So when we use implement we need to implement or write all the methods what are there in the interface we implemented.

62. The Deployment descriptor So now lets complete our EJB by writing the deployment descriptor.

THERE ARE MANY TOOLS WHICH CREATES THE DESCRIPTOR FOR US

As a Bean provider we need to specify the Middleware needs through this descriptor. XML Standard requirement <ejb-jar> <enterprise-beans> <session> <ejb-name> Hello The nickname for this particular Bean examples.HelloHome The fully qualified name of the Home Interface examples.Hello The fully qualified name of the Remote Interface examples.HelloLocalHome The fully qualified name of the Local HomeInterface examples.HelloLocal The fully qualified name of the Local Interface <ejb-class>examples.HelloBean The fully qualified name of the EJB Class <session-type>Stateless Whether the session bean is stateful or stateless Container

63. The Client So now lets code our Client to access our simple stateless session bean. package examples; Rules of Java says package declaration should be at the beginning and ends with a semi colon import javax.naming.Context; importing the necessary files import javax.naming.InitialContext; import java.util.Properties; As there is static key word this main method executes first before any other method in that class public class HelloClient { public static void main(String [] args) throws Exception{ Properties props = System.getProperties(); Assigning props variable with properties information for JNDI initialization Context ctx = new InitialContext(props); Obtaining the JNDI initial context is the starting point for connection to a JNDI tree By passing environment properties we will choose our JNDI driver,network a reference to the Home Object obj = ctx.lookup(“HelloHome”); Get location of the server etc. Object- the factory for Hello EJB Objects. HelloHome home = (HelloHome) javax.rmi.PortableRemoteObject.narrow( obj, HelloHome.class); Use the factory to create the Hello EJB Object. We are then calling the hello() method We are casting HelloHome here, as Home Objects are RMI-IIOP objects and so we Hello hello = home.create(); On the EJB Object. The EJB object will delegate the call to the Bean,receive the Need to use a special RMI-IIOP cast. Results and return it to us . We then print it on the screen. System.out.println(hello.hello()); hello.remove();}} Once we are done with the EJB Object, we can remove it. NOTE : To call Local Interface you need not cast with the PortableRemoteObject. So the block in red will be changed to Object obj = ctx.lookup(“java:comp/env/HelloLocalHome”); ( to get a ref to LocalHome Object) HelloLocalHome home = (HelloLocalHome)obj;

64. EJB Jar File The folder structure within the Ejb-jar file is META-INF/MANIFEST.MF META-INF/ejb-jar.xml examples/HelloBean.class examples/HelloLocalHome.class examples/HelloLocal.class examples/Hello.class

Properties File

Remote/Local Interface

HomeLocalHome Interface

Enterprise Bean Class

Deployment Descriptor

Jar Manifest

Jar Creator

Jar file

DEPLOYED

Or manually run C:\>Jar cf HelloWorld.jar * Jar file is a .ZIP compression format . META-MF file is a listing file automatically created by the Jar utility. Please read the Deployment instructions provided by the Application server as it is Vendor specific

65. EJB Application Assembler Jar file

.JAR

JAR ARC HIEVE (.jar) EJB-JAR.XML REMOTE HOME EJB

Deployment Descriptor

.WAR

Deployment Tool WEB ARCHIEVE (.war) WEB.XML Enterprise Archive (.EAR Files) (Application.XML)

HTML

JSP Servlets

EXAMPLE 2 STATEFUL BEAN

66. Stateful Session Remote Interface package declaration should be in the beginning package samples.ejb.stateful.simple.ejb; import java.util.*; import javax.ejb.EJBObject; import java.rmi.RemoteException; import samples.ejb.stateful.simple.tools.BookException;

Importing the required classes

Remote Cart is extending EJBObject means Cart has all the behaviour of it public interface Cart extends EJBObject Our bean class CartBean methods are mirrored here { public void addBook(String title) throws RemoteException;

public void removeBook(String title) throws BookException, RemoteException;

public Vector getContents() throws RemoteException; }

EJB spec says all remote interface methods need to throw remote exception There will not be any implementation in Interfaces

67. Stateful Session Home Interface package declaration should be in the beginning package samples.ejb.stateful.simple.ejb; import java.io.Serializable; import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EJBHome;

Importing the required classes

CartHome is extending EJBHome means CartHome has all the behaviour of it public interface CartHome extends EJBHome { In a Stateful Bean you can have more than one create method taking arguments Cart create(String person) throws RemoteException, CreateException; In our bean class CartBean these represent ejbCreate(String person) & ejbCreate(String person, String id)

Cart create(String person, String id) throws RemoteException, CreateException; }

EJB spec says all Home interface methods need to throw remote & create exceptions There will not be any implementation in Interfaces

68. Stateful Session Bean Class package samples.ejb.stateful.simple.ejb;

package declaration should be in the beginning

import java.util.*; import javax.ejb.*; import samples.ejb.stateful.simple.tools.BookException; import samples.ejb.stateful.simple.tools.IdVerifier;

Importing the required classes

public class CartBean implements SessionBean {

CartBean Class is implementing sessionbean means this bean class is a session bean String customerName; String customerId; Vector contents;

We definedThis thisalso method in the Cart interface. person) method represents the remote Home create(String

public void ejbCreate(String person) throws CreateException { if (person == null) { throw new CreateException("Null person not allowed."); } else { customerName = person; } customerId = "0"; contents = new Vector();

as this is the Bean class we will implement the business logic here

}

NOTE : AS we are implementing and not extending we need to write all the methods that are there in the Sessionbean

69. Stateful Session Bean Class public void ejbCreate(String person, String id) throws CreateException { if (person == null) { This also Werepresents defined this the Cart remote interface themethod Home in create(String person, String throw new CreateException("Null person not allowed."); } else { customerName = person; }

id) method we defined

The new operator is instantiating the instance of a class IdVerifier idChecker = new IdVerifier(); if (idChecker.validate(id)) { customerId = id; We are calling the validate(id) } else { throw new CreateException("Invalid id: " + id); }

method from the class ID Verifier

// This block is a supporting business method written in idVerifier class contents = new Vector(); }

We defined this method in the Cart remote interface

public void addBook(String title) { contents.addElement(title); }

We defined this method in the Cart remote interface

public void removeBook(String title) throws BookException { boolean result = contents.removeElement(title); We defined contents as if (result == false) { throw new BookException(title + " not in cart."); } }

a vector

70. Stateful Session Bean Class We defined this method in the Cart remote interface public Vector getContents() { return contents; } public CartBean() {} public void ejbRemove() {}

Bean class constructor We need to write these methods as we are implementing SessionBean

public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {} }

Rules of implement states we need to implement all methods that are there in the implemented interface

71. Stateful Deployment Descriptor THERE ARE MANY TOOLS WHICH CREATES THE DESCRIPTOR FOR US

<ejb-jar version="2.1" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd"> CartJAR required by any XML document <enterprise-beans> <session> CartEJB The nickname for this particular Bean <ejb-name>CartEJB samples.ejb.stateful.simple.ejb.CartHome The fully qualified name of the Home Interface The fully qualified name of the Remote Interface samples.ejb.stateful.simple.ejb.Cart <ejb-class>samples.ejb.stateful.simple.ejb.CartBean The fully qualified name of the EJB Class <session-type>Stateful Bean type is mentioned here Container <security-identity> <use-caller-identity/> Closing session and ejb

72. Stateful Deployment Descriptor <method> <ejb-name>CartEJB <method-intf>Remote <method-name>getContents Required <method> <ejb-name>CartEJB <method-intf>Remote <method-name>removeBook <method-params> <method-param>java.lang.String NotSupported

Passing Bean class methods and parameter info

Passing Bean class methods and parameter info

73. Stateful Deployment Descriptor <method> <ejb-name>CartEJB <method-intf>Remote <method-name>addBook <method-params> <method-param>java.lang.String Required


Passing Bean class methods and parameter info

74. Stateful Session Client package declaration should be in the beginning

package samples.ejb.stateful.simple.ejb; import java.util.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.rmi.PortableRemoteObject; public class CartClient {

Importing the required classes

Client class

public static void main(String[] args) { As static is there this main method will execute first try { The new operator is instantiating the instance of Context initial = new InitialContext(); Object objref = initial.lookup("java:comp/env/ejb/SimpleCart");

a class

Looking into JNDI CartHome home = (CartHome)PortableRemoteObject.narrow(objref, Casting with CartHome.class);

a suitable RMI IIOP object

Creating the object Cart shoppingCart = home.create("Duke DeEarl","123"); shoppingCart.addBook("The Martian Chronicles"); adding books to the object shoppingCart.addBook("2001 A Space Odyssey"); shoppingCart.addBook("The Left Hand of Darkness"); Vector bookList = new Vector(); bookList = shoppingCart.getContents();

Invoking the bean class method through remote interface Cart

75. Stateful Session Client We defined booklist as a vector

Enumeration enumer = bookList.elements(); while (enumer.hasMoreElements()) { String title = (String) enumer.nextElement(); System.out.println(title); }

After storing in the variable “title” we are printing it

shoppingCart.removeBook("Alice in Wonderland"); shoppingCart.remove(); Removing a particular book System.exit(0);

using the bean class method removeBook through remote interface Cart –as we defined it this way Cart shoppingCart = home.create("Duke DeEarl","123");

} catch (BookException ex) { System.err.println("Caught a BookException: " + ex.getMessage()); System.exit(0); We had written a new class BookException } catch (Exception ex) { System.err.println("Caught an unexpected exception!"); ex.printStackTrace(); System.exit(1); } } }

and using its method to catch any errors

76. Book Exception package samples.ejb.stateful.simple.tools;

public class BookException extends Exception { /** * Default constructor. */ public BookException() { } /** * Constructor with a String as a parameter. * @param msg message, describing the exception. */ public BookException(String msg) { super(msg); } }

77. ID Verifier package samples.ejb.stateful.simple.tools; public class IdVerifier { /** * Default constructor. */ public IdVerifier() { } public boolean validate(String id) { boolean result = true; for (int i = 0; i < id.length(); i++) { if (Character.isDigit(id.charAt(i)) == false) result = false; } return result; } }

ALL EXAMPLES CAN BE SEEN AT http://www.weblogic.com/docs/examples/ejb/Package-examples.ejb.html http://my.execpc.com/~gopalan/java/entity.html http://java.sun.com/developer/onlineTraining/Beans/EJBTutorial/ http://developers.sun.com/prodtech/javatools/jsstandard/reference/techart/entitybeans.html

78. Component Comparison Component Distributability EJB Can implement the Remote or Local Interface ActiveX Uses Microsoft’s architecture for determining how clients’ invocation requests are sent to components. DCOM used as underlying transport mechanism CORBA ORB makes use of GIOP and other protocols to perform IPC

79. Component Comparison Components provide interfaces in the form of Operations EJB exports operations through Remote Interface ActiveX exports operations in the same interface CORBA exports methods through Interface Repository

80. Component Comparison Self – Container Components EJB Containers inject code to handle transactions, database management, security, distributability and other customisable services. Containers can be provided independent of App Server and EJB providers

ActiveX Transactions, database management, legacy integration have to be coded into the logic of the component. Security policy can be inherited from NTLM. Transactions can be aided through MTS

CORBA CORBAServices have different APIs. CORBAServices can be complicated to code with. CORBAServices are not supported by all ORBs

81. Component Comparison Components provide interfaces in the form of Properties. EJB Properties are not explicitly exported but can be mimicked through accessor operations ActiveX exports Properties in the same interface CORBA Properties not explicitly exported but can be mimicked through attributes

82. Component Comparison Components provide interfaces in the form of Events. EJB Events supported through JMS with Message Driven Bean ActiveX exports Events in the same interface CORBA Events supported through Event Service but cannot be exported

83. Component Comparison Component Reusability EJB Incorporating the contents of an EJB can be done in two ways: • by having the new EJB use the services of an old EJB as a direct client or • by writing an EJB class that inherits from an existing one These two methods of leveragability give developers maximum flexibility

84. Component Comparison Component Reusability Active X Incorporating the contents of an ActiveX can be done in two ways: •



by having the new ActiveX use the services of an old ActiveX as a client or by Delegation

The Components being reused must be registered on the development machine

85. Component Comparison Component Reusability CORBA Every CORBA object has to have its own interface definition CORBA objects can use the services of other Objects No mechanism for inheritance or Object reuse inherently supported, though

86. Component Comparison Components Shareability EJB Application Server makes multiple instances of EJB Objects. Client contexts can be stored in different thread contexts. Different types of EJBs identify levels of shareability.

ActiveX uses Microsoft's in–process/out-of-process architecture for sharing multiple ActiveX components and Client components.

CORBA ORB makes multiple instances of CORBA objects. Clients’ contexts are managed by ORB but can behave differently based upon vendor’s Implementation.

Related Documents

Enterprise Java Beans
November 2019 13
Enterprise Java Beans
May 2020 11
Enterprise Java Beans
May 2020 11
Java Beans
November 2019 22
Java Beans
May 2020 20

More Documents from "Adarsh"