EJB Container services Presentation by Arun Kalluri (04/02/2001)

47
EJB Container services Presentation by Arun Kalluri (04/02/2001)

Transcript of EJB Container services Presentation by Arun Kalluri (04/02/2001)

EJB Container services

Presentation by Arun Kalluri (04/02/2001)

Introduction

EJB container provides support for transaction, security, communications and Exception handling.

Implementation differs between EJB containers.

Allows to deploy the applications using only the tools provided by server vendor

The topics covered are: Transaction Security Exception handling Communication

Transactions

Definition- A set of operations that must be processed as a single unit.

Characteristics-1. Atomic: operations in a set must succeed or fail.2. Consistent: Data base must be left in a state that does not

compromise a business logic, regardless of the success or failure of a transaction.

3. Isolated: Business logic an proceed without consideration for other activities of the system.

4. Durable: once the transaction has been succeeded, the results will be reflected in a persistent store.

A transaction has a discrete starting point and ending point.

Transactions come at a cost in performance and scalability.

Containers cannot manage the transactions for some beans.

The EJB programmer can choose any of the following

Bean managed transaction demarcation-use a simple API to demarcate transaction boundaries

Container managed transaction demarcation-provide information in the XML deployment descriptor.

The developer of session bean must declare the type of transaction in XML deployment descriptor<transaction-type>Bean</transaction-type>

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

Declarative semantics

NotSupported Operates in an unspecified transaction context. Gives EJB container wide latitude to access resources. If a method with ‘NoSupported’ transactional attribute is called

by another method with some specific transactional context, then the EJB container will suspend the transaction of the second method.

Supports Container acts the same as if the transactional attribute is

‘required’ or ‘NotSupported’, if the method is called by a client with valid transaction context or without an existing transaction context.

RequiresNew The container will suspend the existing transaction and start

new one, if the method is called with an existing transaction context.

If no transaction context, then new transaction is created and commits it when method returns.

Required The Container will always invoke this method with valid

transaction context. If a client has a transaction context, then that is passed by

container, otherwise it will create a new one.

Mandatory If method called is called with an existing transaction context,

the container will use it. If the method is called without a valid existing transaction

context, container throws exception.(java.transaction.TransactionRequiredException).

Never If method is called with transaction context, the container throws

an exception(java,rmi.RemoteException) If a method is called with no transactional context, the container

acts as if the transactional attribute is ‘NotSupported’

Specifying Transactional Attributes

The transactional attributes of a method are declared in a XML deployment descriptor.

Deployment descriptor uses <container-transaction>

Each transaction element has two child elements: method, transactional attribute.

Three ways to specify a method element.

Example 1

<container-transaction>

<method>

<ejb-name>Product</ejb-name>

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

</method>

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

</container-transaction>

Example 2

<container-transaction>

<method>

<ejb-name>Product</ejb-name>

<method-name>getname</method-name>

</method>

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

</container-transaction

Example 3

<container-transaction>

<method>

<ejb-name>Product</ejb-name>

<method-name>getTaxes</method-name>

<method-params>

<method-param>java.lang.string</method-param>

<method-param>int</method-param>

</method-params>

</method>

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

</container-transaction>

Choosing transactional attributes

If you have a method that modifies a data in a relational database, best attribute is ‘required’.

If you want to access a data in context of other operation that modified the data, then ‘support attribute’ is preferred.

If the resource, the bean uses does not support external transaction coordinator, ‘NotSupported is preferred for all methods.

An entity bean’s persistence callback methods ejbload() and ejbstore() are called with same transactional attributes of the business method that triggered these methods.

Ejbstore() method is guaranteed to be called before on the transaction’s commit boundary.

EJB container’s management of state caching works only if the business methods work in a transaction.

Two minimum guarantees Container calls ejbload() atleast once between the time the ejb

is associated with an object identity and the time the business method is called.

Container calls the ejbstore() atleast once between the time the method is called and the time the ejb is disassociated with the object identity.

User controlled Transactions

begin()- the client starts the transaction. commit()- the transaction can be

completed successfully. rollback()- transaction can be completed

unsuccessfully. getstatus()- checks if the transaction is

rolled back.

Disadvantages of user controlled transaction

Client is taking the responsibility Changes should be made to java code

instead of XML file.

Isolation levels

Keeping the transaction isolated from effects of other transaction on the same data

Managing Isolation levels APIs is resource specific and not EJB.

EJBs that manage their own resources can specify the isolation levels programmatically.

JDBC provides two methods in java.sql.connection void setTransactionIsolation(int level) int getTransactionIsolation()

Accesses to a resource within a single transaction should have same isolation level

Java.sql.Connection interface operates four predefined isolation levels.

These isolation levels are integer constants defined in connection class.

Isolation levels deal with three well defined problems-’dirty reads’, ‘non-repeatable reads’ and ‘phantom reads’

The three problems in increasing difficulty are: Dirty read-allows a row changed by one transaction to be

read by another transaction before any changes in the row take places.

Non-repeatable read-one transaction reads the row, the other transaction alters or deletes the row and first transaction re-reads the row getting different values.

Phantom read-one transaction reads all rows that satisfy a condition, a second transaction inserts a row that satisfies the

condition and the first transaction rereads the row.

TRANSACTION_READ_UNCOMMITED Prevents none of the problems

TRANSACTION_READ_COMMITED Prevents dirty read

TRANSACTIONAL_REPEATABLE READ Prevents dirty read and no-repeatable reads

TRANSACTION_SERIALIZABLE Prevents all problems

Long transactions

Transactions should be kept short There is a chance that a transaction

could be left opened Using user controlled transactions Requiring the same transaction for subsequent business

methods

Transaction would continue till a business method has

usertransaction.commit()

Optimistic locking Allows multiple clients to access the same data Checking is done at the server, when the business method

sends the data to be updated.

Pessimistic Locking Tells a second client that some othr client is using the data and

it should discard the work. Client wanting to modify the data should check the right to

modify token for that data.

Two-phase commit

A Protocol that allows multiple transaction managers to participate in a single transaction

There are two scenarios in which it will occur:

Application logic access multiple resources in same transaction EJBs in multiple application server participates in same

transaction

Security

EJB specification concerns itself exclusively with access control

The system level security concerns and the logic to access the server are maintained by application server.

The application server maps the valid identity to logical role that EJB application developer or deployer defines.

The EJB container is responsible for the following actions:

Examining the identity of the caller of a business method.

Examine the deployment information to see if the identity has the right to call the business method.

Throw java.rmi.RemoteException if access is illegal Make the identity and role information available to the

EJB for additional fine grained checks.

Security Roles

Mechanism by which caller identities are mapped onto logical roles.

Security roles gives set of permissions for given type of user to successfully use an application.

EJB-specific security roles are defined in XML

<security-role><description>

This role includes…..opens accounts, closes, increase account overdraft

</description><role-name>account_manager</role-name></security-role><security-role><description>This role includes…..integrity of data, read only, access accounts only </description><role-name>Executive</role-name></security-role>

Mapping should be done between existing users and groups and security roles at the time of deployment.

Method permissions

Mechanism to grant a security role to access a business method.

Mapping is done using entries, known as method permissions on XML deployment descriptor.

There are many to many relationships in this mapping.

<method-permission>

<role-name>teller</role-name>

<role-name>account_manager</role_name>

<method>

<ejb-name>AccountManager</ejb-name>

<method-name>findByPrimaryKey</method-name>

</method>

<method>

<ejb-name>AccountManager</ejb-name>

<method-name>deposit</method-name>

</method>

</method-permission>

Programmatic Access Control

Sometimes, whether an operation has to be performed depends upon the data.

In such times the identity of the user is important and just security roles do not give total information to execute a method.

Javax.ejb.EJBContext provides two methods for more fine grained security.

java.security.principal getCaller Principal boolean isCallerInRole(String roleName) An application programmer can write the

code that can fine grain the security and throw an exception if that particular user or group do not have access to the business method.

We must reference any roles defined in the code of EJB to the security roles defined.

<security-role-ref>

<description>…….</description>

<role-name>corporate_account_manager</role-name>

<role-link>executive</role>

</security-role-ref>

Note: even if note link matches with role name, this xml code should be used.

Exceptions

EJB container provides a certain amount of support .

An application exception thrown by EJB code should be handled by business logic

An unexpected exception or system exception thrown by the ejb or related code is handled by EJB container.

Application Exceptions

is declared in the throws clause of a method in the home or remote interface.

Exception java.rmi.RemoteException

Application exception must not be derived from

Java.lang.RuntimeException Java.rmi.RemoteException

The client should be reported with the same exception that is thrown by a EJB instance

An exception thrown from the method participating in the transaction need not necessarily rollback the transaction.

The EJB container will try to commit all the transactions in spite of exceptions.

Using the EJBContext interface, the bean throwing the exception can roll back the transaction through setRollbackonly() method.

Public class AccountManagerEJB implements SessionBean{Public SessionContext ctx;Public void debitfunds(double amount, string Customer) throws

InsufficientFundsException{Try{BankCustomer bankcustomer= getBankCustomer(customer);Bankcustomer.imposeFeeForActivity();Bankcustomer.withdrawFunds();}catch (InsufficientFundsException ife){Ctx.Rollbackonly();Throw ife;}catch(RemoteException e){ Throw new EJBException(e); }}

Predefined Application Exceptions

CreateExceptionindicates that application level exception occurred during create() operation on home interface.

DuplicateKeyExceptionindicates that a data constraint such as primary key or foreign key is violated.

FinderExceptionThis exception is thrown from ejbfindxxx() during an operation on home interface.

ObjectNotFoundExceptionThis exception occurs when find method request an entity which does not exist.

RemoveExceptionIndicates an exception that occurred while removing the bean

System Exceptions

An exception from which the application does not expect to recover

No portable way to adjust the deployment of the application in the container.

It is better to check the parameters in the logic than writing code for Exception handling.

Whenever a system exception is thrown, it should be logged by the container

The EJB container provides two recovery services to ensure the application states remain consistent

The current transaction is rolled back Discard the EJB instance

A client can still access the Remote interface if the instance is a stateless session or entity bean.

EJB container closes any resources that was obtained through resource factory using the JNDI namespace

User defined System Exceptions

Must be derived from Java.lang.RuntimeException Java.rmi.RemoteException Java.lang.Error

EJB must propagate an exception to the container, if it is derived from Runtime Exception or Error.

If it is any other error, EJB should simply throw an instance of javax.ejb.EJBException, which can wrap the original exception.

The container translates every system exception into a java.rmi.RemoteException or subclass and passes to the client.

If the EJB that throws the exception is involved with a client in a tranaction, the EJB class throws javax.transaction

Communication

The EJB specifications enforces rules to support distributed access to EJB.

The important rule is the home and remote interfaces are implemented as RMI interfaces.

Several EJB container vendors have implemented their own version of RMI

Communication between Heterogeneous servers are difficult.

Virtual machine method calls are relatively simple

It is better to place EJB containers where servlets and JSPs are genrating the web pages.

summary

The four basic services provided by EJB container are transaction, security, Exception handling and communications.

The behavior of business methods in a transactions can be controlled declaratively.

Security is specified declaratively in deployment declarations

Business logic code can access the identity of the user. EJB container is responsible for recovery from System

exceptions EJB specification provides rules that are designed to

facilitate remote communications.

QUESTIONS