Ejb

  • November 2019
  • 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 Ejb as PDF for free.

More details

  • Words: 8,099
  • Pages: 136
Enterprise Java Beans Session 1 : Introduction Session 2 : Session Beans Session 3 : Entity Beans Session 4 : MDBeans and Services

Enterprise Java Beans

Distributed Object  





An object that is callable from a remote system It can be called from an in-process client , an out-of-process client, or a client located elsewhere on the network. The client and the distributed object will use stubs and skeletons for communication between them. Stub The client calls a stub, which is a client-side proxy object. This stub is responsible for masking networking communications from the client. The stubs know how to call over the network using sockets, messaging parameters as necessary into their network representation.

Enterprise Java Beans

Continued...



Skeleton The stub calls over the network to a skeleton, which is a server-side proxy object. The skeleton masks network communication from the distributed object. The skeleton delegates the call to the distributed object.

Enterprise Java Beans

Distributed Object

Enterprise Java Beans

Enterprise Java



An Enterprise Bean is a server-side component that can be deployed in a distributed multi-tier environment.



They work across JVMs and are portable distributed components



EJBs have stubs and skeletons that are generated for marshalling.



Each EJB server is a separate JVM (separate process)



EJB Relies on RMI-IIOP Protocol

Enterprise Java Beans

Types of EJB Session Beans --Stateless Beans --Stateful Beans Entity Beans --Bean Managed Persistent Entity Beans --Container Managed Persistent Entity Beans Message Driven Beans

Enterprise Java Beans

Constitutes of EJB 

Remote Interface This interface duplicates all of the business logic methods that the corresponding bean class exposes.



Home Interface Home interface defines methods for creating, destroying and finding EJB objects.



Local Interfaces The clients call Enterprise Beans through their local objects rather than remote EJB Objects. These local objects implement local interface rather than a remote interface.



Enterprise Bean class This is the class which contains all the logic. This is a simple java class that confirms to a well-defined interface and obeys certain rules.

Enterprise Java Beans

Continued..



Primary Key The primary key is a very simple class that provides a pointer into a database; Only entity beans need a primary key. This class must implment java.io.Serializable (so the entity bean can automatically be sent to persistent storage)

Enterprise Java Beans

…Constitutes of EJB



Deployment Descriptors Used to inform the about the middleware needs. The container inspects the Deployment Descriptors to fulfill the requirements that lay out.



Vendor Specific Files Each EJB Server vendor may require that you include additional files specific to that vendor, such as XML files, text files or binary files.



EJB Jar File An EJB jar file is compressed file that contains everything that we have described. It is the unit of deployment and is given to the application server.

Enterprise Java Beans

Session Beans Stateful session beans are to be used to  Hold business logic specific to a single client  Represent non-persistent state  Use as a Facade, single point of entry  Representing workflow between business objects  Shopping cart bean example

Stateless session beans are used to  To provide service objects  e.g., mailing service  To provide procedural view of data  Caller provides all the input, and gets all the output  To operate on multiple data entities at a time,  e.g., updating inventory for a bunch of items

Enterprise Java Beans

… Session Beans



Developer programs three classes: 

Home interface, contains methods for creating (and locating for entity beans) bean instances.



Remote interface, contains business methods the bean offers.



Bean class, contains the business logic of the enterprise bean.

Enterprise Java Beans

Entity Beans 

Represent persistent data  One logical record in the database  e.g., account, order,…



Providing concurrent access to multiple clients



Providing robust, long-lived data  Survives server crashes



Two ways to use entity beans for persistence  BMP : You code it yourself (inside ejbCreate(), ejbRemove(), ejbLoad() and ejbStore())  CMP : Let the container do it for you (Define ‘cmp’ and ‘cmr’ fields in an abstract class); this is the preferred way

Enterprise Java Beans

… Entity Beans



Programmer creates four classes:  Home interface for locating beans  Remote interface that contains business methods for clients.  Bean class that implements bean’s behaviour.  Primary key class – that represents primary key in the database. Used to locate beans.



Primary key class is not needed if primary key is a single field that could be java class (for example, Integer).

Enterprise Java Beans

Message Driven Beans



A message driven bean is an enterprise bean that allows J2EE applications to process messages asynchronously.



It acts as a JMS listener, which is similar to an event listener except that it receives messages instead of events.



The messages can be sent by any J2EE component: an application client, another enterprise bean, or a web component, or a non-J2EE system using JMS.



Retain no data or conversational state.

Enterprise Java Beans

EJB Architecture

EJB Server EJB container

Home Interface

Home Object

Enterprise Java Bean

EJB Client

Security

EJB Object

Transaction Service (JTE)

Remote Interface

Naming Service (JNDI)

Invoke Business methods of EJB

Messaging

Locate, Create and Remote, instance of EJB

Enterprise Services and API Enterprise Java Beans

Databases

EJB Architecture Details



The Ejb object is generated by the utilities provided by the vendor of your Ejb container and is based on the bean classes and the information provided by the deployment descriptor. The Ejb object wraps the bean instance and works with the container to apply transactions, security and other system level operations to the bean at run time.



Ejb home object is a lot like the Ejb object. Its another class that’s generated automatically when you install an enterprise bean in a container.It implements all the methods defined by the home interfaces and is responsible for locating,creating and removing enterprise beans.

Enterprise Java Beans

Architectural Roles 

Bean Provider The bean provider supplies business components , or enterprise beans. These Enterprise beans are not complete applications, but rather are deployable components.



Application Assembler The application assembler is the overall application architect. This party is responsible for understanding how varies components fit together and writes applications that combine components. The application assembler is the consumer of the beans supplied by the bean provider.



EJB Deployer EJB deployers are aware of specific operational requirements such as security, integration, hardware required and performance-tuning.

Enterprise Java Beans

…Architectural Roles



System Administrator Once the deployment goes live , the system administrator steps to oversee the operational solution. The system administrator is responsible for the upkeep and the monitoring of the deployed system and may make use of runtime monitoring and management tools that the EJB server provides.



Server & Container Provider In most of the times the server and container would be provided by a single vendor. The EJB container (Application Server) is the runtime environment in which the beans live. The container supplies middleware services to the beans and manage them.

Enterprise Java Beans

EJB..contd

Session 2 : Session Beans

Enterprise Java Beans

Session Beans



A Session Bean represents a conversation with a single client  Its lifetime is typically the life of the client  Only one create method allowed  They will not be shared between multiple clients  Removed when the EJB container crashes.



There are two types of session beans:  Stateful  Stateless



The type of the session bean is declared at deployment time  The developer must be cognizant of the type when coding the bean Enterprise Java Beans

Stateless Beans



Stateless Beans do not save any state between invocations  They may perform a service for a client  The create() method will not have any parameters , as the stateless beans does not maintain the client state.  Can participate in Transaction.  Minimizes the resources needed.  Any instance can be used for any client

Enterprise Java Beans

Stateless Session Beans: Life Cycle

Does not exist

ejbRemove

Method -ready pool Enterprise Java Beans

Stateful Beans



Stateful beans save state between method invocations  Typically, the bean maintains state by storing it in instance variables in the bean itself  They can not be shared between clients  A stateful session bean is created and assigned to a specific client and is removed when the client finishes.  A Stateful session object has a unique identity that is assigned by the container at create time.

Enterprise Java Beans

Stateful Session Bean: Life Cycle

Does not exist create (args)

ejbRemove timeout

1. 2. 3.

newInstance setSessionContext ejbCreate(args)

remove or timeout

ejbPassivate Passivate

Method ready ejbActivate

Enterprise Java Beans

EnterpriseBean Interface



Base interface for all enterprise bean interfaces

public interface EnterpriseBean extends java.io.Serializable { } 





It is the common superinterface of SessionBean and EntityBean interfaces All enterprise beans are serializable because EnterpriseBean implements Serializable This EnterpriseBean Interface is a marker Interface, implementing this interface indicates that your class is indeed an enterprise bean class.

Enterprise Java Beans

Session Bean Interface



All session beans must implement the SessionBean interface,where this SessionBean interface implements EnterpriseBeans by default.

public interface SessionBean extends EnterpriseBean { public void ejbActivate(); public void ejbPassivate(); public void ejbRemove(); public void setSessionContext(SessionContext ctx); }

Enterprise Java Beans

Activation and Passivation



A container vendor may implement a swapping mechanism to move instances of beans from memory to secondary 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

Enterprise Java Beans

ejbActivate() and ejbPassivate()



 

ejbPassivate()allows the container to notify a bean that 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 swapped in Beans can use these methods to release and acquire resources  For example open files, sockets and database connections  Very often these methods are left empty

Enterprise Java Beans

ejbRemove() and setSessionContext()





ejbRemove()is 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 associate a session instance with the context maintained by the container  The bean can store this in an instance variable for future use

Enterprise Java Beans

Session Bean Class 

Session bean definition illustrating code required by SessionBean interface

package learningpatterns.ejb.calculator; import javax.ejb.*; public class CalculatorBean implements SessionBean { private SessionContext m_ctx = null; public void ejbActivate() {} public void ejbPassivate() {} public void ejbRemove() {} public void setSessionContext(SessionContext ctx) { m_ctx = ctx; } // More to follow Enterprise Java Beans

Bean’s Application methods



The bean class must define all the methods in the remote interface  They must have the same signature  The one difference is that they do not need to throw a RemoteException  These methods do the actual work of your bean  They will be invoked when someone invokes the corresponding method through the EJBObject

Enterprise Java Beans

Calculator Bean Application methods package learningpatterns.ejb.calculator; import javax.ejb.*; public class CalculatorBean implements SessionBean { // … SessionBean required methods as before // Note - these methods DON’T throw RemoteException public int add(int i1, int i2) { return i1+i2; } public int sub(int i1, int i2) { return i1-i2; } }

Enterprise Java Beans

ejbCreate() methods



The bean class must define all the create methods in the home interface  The name of these methods must be ejbCreate  They must be public and have the same arguments as in the home interface  They must return void  The arguments must be legal for Java RMI  They may, but do not need to throw a RemoteException  They may throw a CreateException  They may throw application specific exceptions

Enterprise Java Beans

Calculator Bean ejbCreate() methods package 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 void public void ejbCreate() { // Nothing for us to do } }

Enterprise Java Beans

Deployment Overview





Deploying an enterprise bean is one of the primary steps in development of an EJB At a high-level, deployment can be viewed as having two 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:

Enterprise Java Beans

Continued..



  

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

Enterprise Java Beans

Deployment Descriptor 





There are many attributes which can’t be known by the developer, such as database drivers or network location of databases There are other attributes, such as transaction and security information, that shouldn’t be coded into the bean The deployment descriptor is a standard mechanism provided 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 Enterprise Java Beans

XML Deployment Descriptor











EJB 1.1 uses XML as the deployment descriptor format  XML = Extensible Markup Language XML files are text files that include markup tags similar to HTML tags  Tags are matched with an end tag, and look like this Content  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 (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 here  We then describe each part The DD must be in a file called ejb-jar.xml Enterprise Java Beans

Calculator Deployment Descriptor <ejb-jar> <enterprise-beans> <session> <ejb-name>calculator learningpatterns.ejb.calculator.CalculatorHome learningpatterns.ejb.calculator.Calculator <ejb-class> learningpatterns.ejb.calculator.CalculatorBean <session-type>Stateless

Enterprise Java Beans

…Deployment Descriptor

Container <method> <ejb-name>calculator <method-name>* Required

Enterprise Java Beans

Deployment Descriptor Details

 The fully qualified class name of the home interface  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  Defines the transaction management type of a bean (Container or Bean)

Enterprise Java Beans

Continued ..

 Defines how a bean is used in an application. Describes the security roles and transactional attributes of a bean  Defines which transactional attributes apply to which methods  We’ll cover transactions more later

Enterprise Java Beans

Deployment Descriptor Details



Container vendors generally provide tools to create and modify 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

Enterprise Java Beans

Standard EJB Jar file 







EJBs 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 up 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 ejb-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 files

Enterprise Java Beans

Vendor Specific Details

<weblogic-ejb-jar> <weblogic-enterprise-bean> <ejb-name>calculator <max-beans-in-free-pool>100 <jndi-name>JavaConference.CalculatorHome

Enterprise Java Beans

Deploying the EJB jar file

 

The details vary by server 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 Weblogicspecific 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

Enterprise Java Beans

Client View of a Session Bean

-

Getting a JNDI InitialContext Looking up the home interface Getting a reference to an EJB Calling methods on an EJB

Enterprise Java Beans

Getting a JNDI InitialContext 



In most cases, the default constructor for javax.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: InitialContext ctx = new InitialContext();

Enterprise Java Beans

Looking up the home interface



Use the lookup method of the Context interface to get a home interface reference  public Object lookup(String name);  We have set up the following JNDI name in our Calculator bean jar file  JavaConference.CalculatorHome  Cast the return value to the home interface type  To be compatible with RMI over IIOP you 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

Enterprise Java Beans

Continued..



Sample code fragment: Object calcObject = ctx.lookup(“JavaConference.CalculatorHome”); CalculatorHome cHome = (CalculatorHome) PortableRemoteObject.narrow(calcObject, CalculatorHome.class);

Enterprise Java Beans

Getting a reference to an EJB









The client uses a create method in the home interface to get a reference to the EJB The calculator home interface contains a method called create that accepts no parameters: public Calculator create() throws CreateException, RemoteException; The client can use this method to get a reference to the Calculator  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: Calculator calc = cHome.create(); Enterprise Java Beans

Calling methods on an EJB







The EJB’s remote interface defines the methods that can be called from a client In the case of the calculator example, the interface contains an add and a sub method: public int add(int i1, int i2) throws RemoteException; public int sub(int i1, int i2) throws RemoteException; Sample Code fragment: System.out.println(“6 + 5 = “ + calc.add(6,5)); System.out.println(“6 - 5 = “ + calc.sub(6,5));

Enterprise Java Beans

EJB ….contd

Session 3: Entity Beans

Enterprise Java Beans

Entity Bean





Entity Beans are EJBs that present an object view of persistent data and are  shared by multiple clients  transactional  long lived (i.e., they live as long as the data)  able to survive a server crash Entity beans usually represent data in a relational database  The data could be stored in an object database  An entity bean can also be used to encapsulate the behavior of a non-EJB application  Legacy applications  Connector API is being defined in EJB 2.0

Enterprise Java Beans

Entity Bean: Life Cycle

Enterprise Java Beans

Types of Entity Beans



There are two types 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

Enterprise Java Beans

Container Managed Persistence(CMP) 







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 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 writer  Also, the bean is independent of the data source specifics CMP 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

Enterprise Java Beans

Bean-managed Persistence (BMP) 





Bean manages all persistence  The bean developer writes the persistence code as part of developing the bean Advantage - container doesn’t need to generate database calls  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 writer  More complex code  Persistence is hard coded into the bean  This makes it harder to adapt the bean to different data sources

Enterprise Java Beans

BMP/CMP: Similarities and Differences





In many respects, BMP and CMP beans have much in common  Home interface  Remote interface  Primary key class  Client’s view In other respects, BMP and CMP are different  Implementation of bean class  Deployment descriptor details  Implementation of finder methods

Enterprise Java Beans

Entity Bean Interfaces



Both CMP and BMP entity beans have:  A home interface  Create methods  Finder methods  A remote interface  Business methods  A primary key

Enterprise Java Beans

Home Interface and Create Methods





The home interface is still the bean “factory” for entity beans  But now you also have to take into account that there is underlying data For entity beans, create methods in the home interface add a new row to the underlying data  They return a reference (EJBObject) to the bean just like with session beans  They will likely take data which is used to create the bean  Assume we need an account number and initial balance to create an account. The account home might have the following create method:

Enterprise Java Beans

Home Interface and Create Methods

public interface AccountHome extends EJBHome { public Account create(int id, String name, double initialBalance) throws RemoteException,CreateException; }

Enterprise Java Beans

Finders - Retrieving Existing Data 



Home interfaces also define finder methods to look up existing 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 findByPrimaryKey method  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 Enterprise Java Beans

Finder Methods Example public interface AccountHome extends EJBHome { // create methods … // e.g. to find all accounts with a minimum balance public 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 this section.

Enterprise Java Beans

Remote Interface 



Just like with session beans, the remote interface for an entity bean defines the business methods that are available to the client For example, the remote interface for an account object might look like the following: public interface Account extends EJBObject { public void deposit(double amount) throws RemoteException; public void withdraw(double amount) throws RemoteException, ProcessingErrorException; public double getBalance() throws RemoteException; public java.util.Date getOpenDate() throws RemoteException; public String getName() throws RemoteException; }

Enterprise Java Beans

Primary Key 



Every 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 within 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

Enterprise Java Beans

-Entity Bean Implementation

-

Entity Bean State -- Database Data Entity Bean Interfaces -- Home Interface, Remote Interface Primary Key Class -- Unique identifier of an Entity Bean Create Methods -- ejbCreate() metnods with various parameters Finder Methods -- ejbFind() methods Lifecycle Methods – Container methods like ejbStore, ejbLoad … Application Methods – Businees Logic Methods

Enterprise Java Beans

-Entity Bean State

 



Generally there are instance variables to hold the data For 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 example

Enterprise Java Beans

- Continued..



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 bean public String m_id; public double m_balance; public String m_name; public java.sql.Date m_open_date;

Enterprise Java Beans

-The EntityBean Interface 

All entity beans must implement the EntityBean interface 

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(); }

Enterprise Java Beans

-AccountBean package learningpatterns.ejb.bank; import javax.ejb.*; public class AccountBean implements EntityBean { public public public public

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

public void ejbActivate() { System.out.println(“AccountBean.ejbActivate”); } // … and so on for other required EntityBean methods } Enterprise Java Beans

-Primary Key Class Details 







The primary key class is defined by the bean developer  It must be Serializable For CMP, the primary key class is tied to the bean implementation  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 class  As long as the field is serializable, and has a hashCode() and equals() method When comparing objects for equality  Can extract the primary keys and use the equals()method  Can also use the EJBObject isIdentical() method

Enterprise Java Beans

-AccountPK // Primary Key Class for AccountBean package learningpatterns.ejb.bank; public class AccountPK implements java.io.Serializable { public int m_id; public AccountPK() { super(); } public AccountPK(int id) { super(); this.m_id = id; } public int hashCode() { Integer i = new Integer(m_id); return i.hashCode(); } public boolean equals(Object obj) { AccountPK compareTo = (AccountPK) obj; return m_id == compareTo.m_id; } }

Enterprise Java Beans

-Create Methods 





You create a bean via a create() call on the home interface  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 ejbCreate() method must be defined for each create() 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 ejbPostCreate() method must also be defined for each create method  Same arguments as ejbCreate  void return  Doesn’t throw CreateException, RemoteException Enterprise Java Beans

-ejbCreate() - Entity Beans





For BMP  Should actually create row in database  Return value is the primary key For CMP  Should initialize the instance variables from the passed in arguments  Doesn’t go to database

Enterprise Java Beans

-ejbCreate(), ejbPostCreate() – CMP public class AccountBean implements EntityBean { public AccountPK ejbCreate ( // EJB 1.0 - void return int id, String name, double initialBalance) throws RemoteException, CreateException { m_id = id; // Initialize instance vars m_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 } } Enterprise Java Beans

-Finder Methods 

For BMP  There is a corresponding method in the bean class  This method starts with the prefix ejbFind and has the same suffix part and arguments as in the home interface  The return value is a PrimaryKey or enumeration of PrimaryKeys  The container constructs the EJBObjects from the primary key and returns them to the client public class AccountBean implements EntityBean { // … public Enumeration ejbFindByMinBalance (double minBalance) throws RemoteException, FinderException {} }

Enterprise Java Beans

-Finder Methods



For CMP  The implementations are written by the container  There is no corresponding ejbFind in the bean  The vendor must have some way of specifying the semantics of finders

Enterprise Java Beans

-Activation and Passivation



 

Activation and passivation follow the same model as with session beans  ejbPassivate and ejbActivate should respectively save and reacquire resources setEntityContext should save the passed in context for future use unsetEntityContext unsets the context  Sets it to null

Enterprise Java Beans

-Lifecycle Methods with CMP



ejbLoad and ejbStore are NOT used for database access  Used for communication between server and bean instance  After loading the data from the database, ejbLoad is called  Before storing the data to the database, ejbStore is called  They do not perform any database operations

Enterprise Java Beans

-Lifecycle Methods with BMP



ejbLoad and ejbStore ARE 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

Enterprise Java Beans

-ejbRemove()







An ejbRemove() method must be defined in the bean itself public void ejbRemove() {}  It is called when remove() is called on the bean  It will be called before the bean is removed For CMP  You can put here any cleanup code, or release any resources that are being used  Often it is an empty method For BMP  You would put database code to actually remove the bean  You can also clean up and release resources

Enterprise Java Beans

-Business Methods



Operate on the instance variables

public class AccountBean implements EntityBean { // … public void deposit(int amount) { m_balance += amount; } // … and so on }

Enterprise Java Beans

-Entity Beans and SQL Statements Entity Bean Operation

Corresponding SQL Statement

ejbCreate(…)

insert

ejbfindByxxx(…)

select

ejbRemove()

delete

ejbStore()

update

ejbLoad()

select

Enterprise Java Beans

-CMP and Deployment 



Since the container is accessing the database on behalf 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 following deployment descriptors:  The standard EJB deployment descriptor (ejb-jar.xml)  weblogic-ejb-jar.xml  weblogic-cmp-rdbms-jar.xml

Enterprise Java Beans

-ejb-jar.xml - Part 1 <ejb-jar> <enterprise-beans> <entity> <ejb-name>account learningpatterns.ejb.bank.AccountHome learningpatterns.ejb.bank.Account <ejbclass>learningpatterns.ejb.bank.AccountBean Container <prim-keyclass>learningpatterns.ejb.bank.AccountPK False m_id

Enterprise Java Beans

-ejb-jar.xml - Part 2 m_name m_open_date m_balance ... Enterprise Java Beans

-weblogic-ejb-jar - Part 1 <weblogic-ejb-jar> <weblogic-enterprise-bean> <ejb-name>account <max-beans-in-cache>1000 WebLogic_CMP_RDBMS 5.1.0 META-INF/weblogic-cmp-rdbmsjar.xml Enterprise Java Beans

-weblogic-ejb-jar - Part 2

WebLogic_CMP_RDBMS 5.1.0
<jndi-name>JavaConference.AccountHome

Enterprise Java Beans

-weblogic-cmp-rdbms-jar.xml - Part 1 <weblogic-rdbms-bean> <pool-name>BankPool Account m_id ID m_name Name ... Enterprise Java Beans

-weblogic-cmp-rdbms-jar.xml - Part 2 <method-name>findByMinBalance <method-params> <method-param>double = m_balance $0)]]> <use-quoted-names>false

Enterprise Java Beans

-Bean Managed Persistence (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

Enterprise Java Beans

-Connecting to Database







Is the most complicated part  The rest is fairly straightforward JDBC We will need to use the EJB mechanism to access resources  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 DataSource  It must be using a transactional driver  For Weblogic, that’s the jts driver  It is created in the weblogic.properties file

Enterprise Java Beans

-Accessing a JDBC DataSource

 



We’ll give an example using Weblogic server This involves both the weblogic.properties file, and the xml 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 reference name in the DD

Enterprise Java Beans

-Database Properties weblogic.jdbc.connectionPool.BankPool=\ url=jdbc:cloudscape:Bank,\ driver=COM.cloudscape.core.JDBCDriver,\ initialCapacity=1,\ maxCapacity=2,\ capacityIncrement=1,\ props=user=none;password=none;server=none # Add a Transactional DataSource for the connection pool: # It creates a JNDI entry named weblogic.jdbc.jts.BankPool weblogic.jdbc.TXDataSource.weblogic.jdbc.jts.BankPool=BankPool # Add an ACL for the connection pool: weblogic.allow.reserve.weblogic.jdbc.connectionPool.BankPool=ever yone

Enterprise Java Beans

-ejb-jar.xml <ejb-jar> <enterprise-beans> <entity> <ejb-name>account …. Bean jdbc/BankPool javax.sql.DataSource Container

Enterprise Java Beans

-Deployment Descriptor Details  Describes a resource reference  JNDI name you will use to look up resource with  Note that using jdbc/ is not required - it is a convention only  Fully qualified class name of the resource  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

Enterprise Java Beans

-weblogic-ejb-jar.xml

<weblogic-ejb-jar> <weblogic-enterprise-bean> <ejb-name>account <max-beans-in-cache>1000

Enterprise Java Beans

-weblogic-ejb-jar.xml jdbc/BankPool <jndi-name> weblogic.jdbc.jts.BankPool <jndi-name>JavaConference.AccountHome

Enterprise Java Beans

-Weblogic DD Details  Sets up a resource reference  Sets up a particular resource  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”

Enterprise Java Beans

-Getting a Connection



We’ll encapsulate it in a method  First we get the JNDI ENC  Then we look up our DataSource and get a connection from it private 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(); } Enterprise Java Beans

-....Getting a Connection

catch(SQLException sqle) { throw sqle; } catch(Exception e) { throw new SQLException(e.getMessage()); } return con; }

Enterprise Java Beans

-Getting Data From the Database





It’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 primary key  This can be used from multiple methods

Enterprise Java Beans

-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); }

Enterprise Java Beans

-Getting Data From the DB - cont’d else { throw new FinderException ("Refresh: AccountBean (" + pk.m_id + ") not found"); } }catch (SQLException sqe) { throw new RemoteException (sqe.getMessage()); } finally { try { if (stm != null) stm.close(); if (con != null) con.close(); } catch (Exception ignore) { } } }

Enterprise Java Beans

-ejbFindByPrimaryKey // Given a Primary Key, loads the bean from the persistent store public AccountPK ejbFindByPrimaryKey(AccountPK pk) throws FinderException, RemoteException { if (pk == null) throw new FinderException ("primary key cannot be null"); // Load from the database refresh(pk); // Print out some debugging System.out.println("ejbFindByPrimaryKey (" + pk.m_id + "found"); // return the primary key return pk; }

Enterprise Java Beans

-ejbLoad

// Retrieves the Account data from the database public void ejbLoad() throws RemoteException { try { refresh((AccountPK) m_ctx.getPrimaryKey()); } catch (FinderException fe) { throw new RemoteException (fe.getMessage()); } }

Enterprise Java Beans

EJB ..contd

Session 4 : Message Driven Beans

Enterprise Java Beans

Message Driven Beans 1.Message driven beans are EJB Components that listen for message published on a JMS Server. 2.Message Driven Beans can’t be accessed by clients. 3.MDBs require neither Home nor Remote interfaces 4.MDBs are the only EJBs that can receive JMS messages 5.The MDBs are designed to enable an EJB to be asynchronously invoked to handle the processing of incoming Messages. 6.Message Driven Beans have only an onMessage() method which are called asynchronous upon message arrival. 7. It acts as a JMS listener, which is similar to an event listener except that it receives messages instead of events. 8. They retain no data or conversational state Enterprise Java Beans

JMS  



JMS is an API for Enterprise Messaging. JMS has two parts: an API, in which we write code to send and receive messages, and Service Provider Interface(SPI) where we can plug in JMS Drivers. Message Types: Bytes Message, Object Message, Stream Message, Text Message and Map Message Message Domains: Publish/Subscribe: There can be many message producers talking to many message consumers.Subscribers register their interest in particular event topic.Providers create messages that are distributed to all of the subscribers. Point-to-Point: In this domain there will be only a single message consumer for each messages. Multiple Producers can send messages to the queue,but each message is delivered only to a single consumer. Enterprise Java Beans

Message Driven Beans(Life Cycle)

does not exist

ejbRemove()

onMessage(msg)

method -ready pool Enterprise Java Beans

General Programming Model for a Message Consumer

Enterprise Java Beans

General Programming Model for a Message Producer

Enterprise Java Beans

MDB Application View

Enterprise Java Beans

MDB Features

A middle man sits between the client and the server. And the client does not need to wait when performing a request. There can be more than one message producers as well as message consumers. Message Driven Beans do not have return Values. They can not send exceptions back to clients.

Enterprise Java Beans

Application Client import javax.naming.*; import javax.jms.*; public class Client{ public static void main(String args[]) throws Exception{ Context ctx = new InitialContext(System.getProperties()); queueConnectionFactory = (queueConnectionFactory) ctx.lookup (“javax.jms.MyQueueConnectionFactory"); queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queue = (queue) jndiContext.lookup("java:comp/env/jms/QueueName"); queueSender = queueSession.createSender(queue); message = queueSession.createTextMessage(); for (int i = 0; i < NUM_MSGS; i++) { message.setText("This is message " + (i + 1)); System.out.println("Sending message: " + message.getText()); queueSender.send(message); } } }

Enterprise Java Beans

Bean Class import javax.ejb.*; Import javax.kms.*; public class SimpleMessage implements MessageDrivenBean,MessageListener{ protected MessageDrivenContext ctx; Public void setMessageDrivenContext(MessageDrivenContext ctx){ this.ctx=ctx;} public void ejbCreate(){} public void onMessage(Message inMessage) { TextMessage msg = null; try { if (inMessage instanceof TextMessage) {msg = (TextMessage) inMessage; System.out.println(" Message received: " + msg.getText()); } else { System.out.println ("wrong type: " + inMessage.getClass().getName()); } } Enterprise Java Beans

Bean Class

catch (JMSException e) { e.printStackTrace(); mdc.setRollbackOnly(); } catch (Throwable te) { te.printStackTrace(); } } public void ejbRemove(){} } }

Enterprise Java Beans

Deployment Descriptor <ejb-jar> <enterprise-beans> <message-driven> <ejb-name>SimpleBean <ejb-class>examples.SimpleBean,/ejb-class> container <message-driven-destination> <destination-type>javax.jms.queue<destination-type> Enterprise Java Beans

Creating the Queue

Creating the Queue 1. Create the queue with the j2eeadmin command: j2eeadmin -addJmsDestination jms/MyQueue queue 2. Verify that the queue was created: j2eeadmin -listJmsDestination

Enterprise Java Beans

EJB ..contd

Session 5 : Services

Enterprise Java Beans

Container Services



Database management  Database connection pooling  DataSource, offered by the J2EE server. Needed to access connection pool of the server.  Database access is configured to the J2EE server -> easy to change database / database driver



Transaction management  Distributed transactions  J2EE server offers transaction monitor which can be accessed by the client.

Enterprise Java Beans

…Services



    

Security management  Authetication  Authorization  encryption Authentication Persistence Naming Concurrency Load Balancing

Enterprise Java Beans

Transaction Properties

Transaction is a series of operations that appear to execute as one large, atomic operation. Atomicity: Guaranties that operations performed within a transaction undergo an all-or-nothing paradigm. Consistency: Makes the system state to be consistent after a transaction completes. Isolation: Protects concurrently executing transactions from seeing each other’s incomplete results. Durability: Guaranties that updates to managed resources such as Database Records, survive failures.

Enterprise Java Beans

Transaction Attributes Not Supported: Upon entering the method, any current transaction is suspended for the duration of the invocation. Required: If there is no transaction active, then one will be started upon entering the method. The transaction will be committed before leaving the method if the container started it. If there is a transaction already running, no new transaction will be started. Supports: If a transaction is active work is done in the context of that transaction. No new transactions are started. Requires New: A new transaction will be started upon entering the method even if there is a transaction active. Mandatory: Upon entering the method, an exception is thrown if there is no transaction active. Never: This bean can never be involved in a transaction, an exception will be thrown if a transaction is active. Bean Managed: The bean itself controls the transaction. This option is not available for Entity Beans. Enterprise Java Beans

Transaction Attributes Table

Enterprise Java Beans

Transactional Isolation

Isolation: Guaranties that concurrent users are isolated from one another, even if they are touching the same database data. Transactional violation: occurs when a database is accessed concurrently by multiple client. 1.Dirty Read: A dirty read occurs when your application reads data from a database that has not been committed to the permanent storage yet. 2.Unrepeatable Read: This problem occurs when a component reads data from a database, but when rereading the data, the data has been changed. 3.Phantom Problem: A new set of data that magically appears in a database between two database read operations.

Enterprise Java Beans

Transactional Isolation

Isolation Level: READ UNCOMMITED - DOES NOT OFFER ANY ISOLATION GUARANTEES READ COMMITED

- SOLVES THE DIRTY READ PROBLEM

REPEATABLE READ - SOLVES DIRTYREAD & UNREPEATABLE READ PROBLEM. SERIALIZABLE

- SOLVES ALL THE THREE PROBLEMS

Enterprise Java Beans

Security  





Declarative EJB Security is based per method permission The container will throw an Exception if an unauthorized user tries to access a restricted method To specify access control and security roles: 1) Security role references <security-role-ref> 2) Security roles <security-role> 3) Method permissions <method-permission> More fine grained access control can be made programatically (throw Exception if access denied) - javax.ejb.EJBContext - getCallerPrincipal(); - isCallerInRole(String);

Enterprise Java Beans

Security Roles & Method Permissions

<ejb-jar> <enterprise-beans> <entity> <ejb-name>SecureEJB ... <security-role-ref> InternalTrusted TrustedUser <security-role> TrustedUser

Enterprise Java Beans

Security Roles & Method Permissions

<method-permission> TrustedUser <method> <ejb-name>SecureEJB <method-name>doSecureStuff


Enterprise Java Beans

Persistence



Container supplies mapping tools to map the bean’s fields to fields in the data store



Connection pools



CMP entity beans

Enterprise Java Beans

Naming

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

Enterprise Java Beans

Concurrency

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

Enterprise Java Beans

Load Balancing & Fail Over





Load Balancing  Maximizes the usage of the computing resources of all of your server machines  Essential to ensuring that the application is scalable Fail over  A request may be redirected from one server to another because of a machine or network failure  Necessary for critical, enterprise applications

Enterprise Java Beans

Enterprise Beans Types: Overview

EJB client

JMS client

Deployment descriptors

OC4J EJB EJB home EJB container home interface object EJB comp. interface

EJB Local/ remote object

JMS Listener

SB bean Entity

bean MDB bean

Enterprise Services Naming, Transactions, Security Enterprise Java Beans

Database Or External Apps

Related Documents

Ejb
November 2019 25
Ejb
May 2020 13
Ejb
May 2020 11
Ejb
November 2019 22
Ejb
November 2019 25
Ejb
November 2019 17