Thursday 26 November 2009

Transaction isolation levels, consenquences and configuration

1.     Introduction
 In this post I sum up the different isolation levels and how we can configure them in JBoss AS depending on the type of datasource defined for our JEE application.


2.     JDBC transaction isolation levels
Transaction isolation levels specify what data is visible to statements within a transaction. These levels directly impact the level of concurrent access by defining what interaction is possible between transactions against the same target data source.

READ UNCOMMITTED: allows a row changed by one transaction to be read by another transaction before any changes in that row have been committed (a "dirty read"). If any of the changes are rolled back, the second transaction will have retrieved an invalid row.

READ COMMITTED: prohibits a transaction from reading a row with uncommitted changes in it. This is the default level for most of databases.

REPEATABLE READ: prohibits a transaction from reading a row with uncommitted changes in it, and it also prohibits the situation where one transaction reads a row, a second transaction alters the row, and the first transaction rereads the row, getting different values the second time (a "non-repeatable read").

SERIALIZABLE: includes the prohibitions in TRANSACTION_REPEATABLE_READ and further prohibits the situation where one transaction reads all rows that satisfy a WHERE condition, a second transaction inserts a row that satisfies that WHERE condition, and the first transaction rereads for the same condition, retrieving the additional "phantom" row in the second read.

NONE: transactions are not supported.

Depending on your isolation level we can have three phenomena:

Dirty reads

1.     Transaction A inserts a row into a table.
2.     Transaction B reads the new row.
3.     Transaction A rolls back.
4.     Transaction B may have done work to the system based on the row inserted by transaction A, but that row never became a permanent part of the database.

Nonrepeatable reads

1.     Transaction A reads a row.
2.     Transaction B changes the row.
3.     Transaction A reads the same row a second time and gets the new results.

Phantom reads

1.     Transaction A reads all rows that satisfy a WHERE clause on an SQL query.
2.     Transaction B inserts an additional row that satisfies the WHERE clause.
3.     Transaction A re-evaluates the WHERE condition and picks up the additional row.


Isolation Level
Dirty Read
Nonrepeatable Read
Phantom Read
READ UNCOMMITTED
Permitted
Permitted
Permitted
READ COMMITTED
No Permitted
Permitted
Permitted
REPEATABLE READ
No Permitted
No Permitted
Permitted
SERIALIZABLE
No Permitted
No Permitted
No Permitted



3.     How to set transaction isolation level in JBoss AS 4.2.2
 As far as I know we can configure it within server/my_server/deploy/*-ds.xml (i.e oracle-ds.xml, mysql-ds.xml).

There are two types of datasources where we can define it:

local-tx-datasource: identifies a datasource that uses single phase commit transactions, therefore there is just one resource per JTA transaction (local transaction).

xa-tx-datasource: identifies a datasource that uses two phase commit transactions, therefore there are more than one resource per JTA transaction (global transaction).

Note: Use xa-tx-datasource when it is really needed. It is expensive in terms of performance.

The element to set is  

transaction-isolation: specifies the java.sql.Connection transaction isolation level to use. The constants defined in the Connection interface are the possible element content values and include:

TRANSACTION_READ_UNCOMMITTED
            TRANSACTION_READ_COMMITTED
TRANSACTION_REPEATABLE_READ
TRANSACTION_SERIALIZABLE
TRANSACTION_NONE

We can find further information in this link JBoss web site

Monday 23 November 2009

Introducing security concepts in JBoss AS

Authentication in JBoss AS

Authentication is the process by which a system verifies the identity of a user. There are two important concepts:

Principal: a human user, machine or process that’s trying to prove its identity on another system.

Credentials: one or more forms of identifications provided by a principal, i.e. passwords, certificates or any other reliable form of identification.

Security data can be kept in different data sources, so JBoss SX has different login modules that can read security information from different locations such as a database or an LDAP server.







Authorization in JBoss AS

Authorization is the process of verifying that a principal has sufficient privileges to access an application resource.

Authorization is often achieved by assigning one or more roles to a principal and then associating one or more roles with a component or resource that a principal might want to access. When the principal tries to access the component, the system looks at the roles allowed to access the component and the roles assigned to the principal. If the principal has one of the roles assigned to the component, then he can access the component; otherwise, the principal can’t access the component. This process is called role-based authorization.

Java EE defines declarative, role-based authorization for standard component technologies such as servlet, JSP, and EJB. Declarative authorization means that you can assign roles to components via configuration without the need to write any code.

Note: There are certain situations where role-based security doesn’t cut it. This fact becomes evident when the security you want to apply depends on the context of the request that the user sends. Applying security based on information in the request is often called context-based security, or programmatic security. For example, you want to allow a bank employee to enter deposits under 10,000 GPB, but anything over 10,000 GPB would require manager’s approval.

You can implement context-based security in several ways for each of the different component models. For EJBs, you can use JBoss SX security proxies or EJB3 interceptors. For web applications, you can use servlet filters, custom valves, or interceptors.






Configuring security

Each Java EE component or resource has a different mechanism for defining security. The definition of what method to use and what should be secured is defined in each component’s standard deployment descriptor. But, the Java EE specification doesn’t specify the underlying security implementation; it doesn’t describe where the security data should be kept, how it should be retrieved, or how it should be validated. Each application server vendor has to create its own security implementation and allow programmers to configure and use it through vendor-specific deployment descriptors.

JBoss AS’s security implementation is called JBoss SX, which builds on top of the Java Authentication and Authorization Service (JAAS) to secure all the Java EE technologies running in the application server.

When a request comes into JBoss AS, the targeted application component or resource (web application, EJB application, JMS queue/topic, or whatever), it may be—doesn’t need to know where the underlying security data exists or how it’s accessed. The component request is routed to a JBoss SX component called a security domain, an abstraction used to secure all requests made to a component. The security domain performs any necessary security checks and notifies the component whether the user can proceed or not. The security domain knows how to use one or more login modules to load security data from a data source.

Security domains are configured at the server level and can be used by any component within the server. Security domains are bound into JNDI when the server starts; pointing to the security domain’s JNDI context maps a component to a security domain. You can add or modify existing security domain definitions within the server/my_server/conf/login-config.xml file.


Note: When you define a security domain in the login-config.xml file, JBoss SX doesn’t automatically bind the security domain into JNDI. JBoss SX only binds a security domain into JNDI after you deploy an application that references the security domain.






Everything together - Step by Step Example

Bank’s secure Java EE-enabled website with a secure public-key certificate from a trusted certificate authority (CA).

Alvaro accesses the bank website and clicks on a link that should take his to her account summary. This link might be something like https://www.alvarobank.com/accountSumm.

The page is accessed via a secured protocol (HTTPS), the server sends its secure certificate to Alvaro’s web browser, like all major browsers, has a list of well-known certificate authorities. On receiving the bank’s certificate, her browser turns around and asks the trusted certificate authorities if the certificate belongs to the bank C.
Assuming that one of the certificate authorities acknowledges the authenticity of the bank’s certificate, Alvaro’s browser tries to forward her to the account summary page he originally requested.

Alvaro can now trust that he’s accessing his bank and that nobody can intercept her communication with her bank. Also, as long as he accesses the bank over the secure protocol, all her communications are transferred over a secure channel.

The bank needs to know if it can trust him. The URL for the account summary page is secured with form-based authentication. Users also must be a part of the AccountHolder role before accessing the page. Before Alvaro can access the account summary page, his request is intercepted by the JBoss Web Server web container. The container realizes that the URL that he’s accessing is secured, so it checks with the security framework to see if Alvaro is already logged in. After realizing that he’s not, a login form is sent back to Alvaro, prompting him for his username and password.

When Alvaro types in her credentials (user and password) and submits the form, the web container receives the form submission and passes Alvaro’s credentials to the application server’s security framework. The security framework accesses security information from a database, which it queries to determine whether or not Alvaro can access to the resource he’s requesting. First, the security framework should authenticate Alvaro, comparing the password she supplies against a known password to see if she should be granted access to the system at all. Then, the security framework should authorize Alvaro, determining if his username is associated with a role that can access the resource.

Everything matches up, so the security framework returns control back to the web container. Now that Alvaro’s credentials have been verified, the web container forwards her request to the resource associated with the URL for the account summary.

The account summary page is implemented as a servlet. In order for the servlet to render Alvaro’s account summary information, it needs to access her account information.
The servlet makes a call to the getAccountSummary(User u) method on a session EJB called Account, which runs in the EJB container. Because the EJB container runs locally, the servlet automatically propagates the security credentials.
The EJB method only allows access to users with the AccountHolder role. The EJB server accesses the JBoss SX security framework to determine if Alvaro is authenticated and authorized to access the resources. Again, access to the EJB method succeeds, and Alvaro’s account information loads from the application database. After the account summary loads, control returns to the servlet, which renders the output and sends it back to Alvaro, still over a secure channel.



Sunday 15 November 2009

Transfer Obejcts vs Business Objects (JPA entities) across the tiers

Introduction

In this article I try to launch a very common technical discussion about what is the best approach, Transfer objects or Business objects (JPA entities) across the tiers. Once more time, I think that there is no a golden rule. It depends on the use case, the complexity of the application in terms of architecture and frameworks used.

Transfer Object across the tiers


Pros
1. Reduces network traffic in distributed systems. Transfer objects are passed to the client in a single remote call.


2. Improves client performance by removing any need to assemble data models.


3. Decouples business logic from the client and keeps it in the business tier.


4. Improves transaction performance by isolating the components that can be updated.


Cons
1. Data in transfer objects might get obsolete. The transfer object has a copy of the data which is not automatically updated if the data changes on the server.


2. The system can be complicated when using concurrent access or transaction management processes.


3. Synchronization logic can complicate the system if updatable transfer objects are used.
Object creation overhead on the server side increases.


Business Object across the tiers



Pros
1. Good approach in simple presentation tier design.


2. Makes easier the development in business and presentation tier because there is no need to assemble data models.

Cons
1. Couples presentation tier and business tier.

Note: If the business requirements don’t change often I consider that is good point to use them but otherwise it could be a nightmare for each single change to adapt the presentation tier.


2. In the case that the user interface requires a complex set of properties:

2.1. The domain model to pass across tiers can become heavyweight in terms of memory.

2.2. The development in the presentation tier can be complex because we need to navigate across multiple business objects to get the properties.

2.3. The development in business tier can become very tedious because we will load a lot of properties in the domain model (properties from BO1 -> properties from BO2 -> properties from BO3 and so on). There are two approaches to have all the properties in presentation tier:

      
       2.3.1 In business tier: Eager relationships in JPA entities.
       2.3.2 In business tier: “Fetch Join” in application services.


      Note: Some frameworks keep transaction opened during the render of the user interface.         
      In the case the relationships in the JPA entities can be defined as LAZY. We do not have      
      to be worry about exceptions as org.hibernate.LazyInitializationException in the case of      
      using Hibernate as JPA provider.


Wednesday 4 November 2009

JMS: Message-driven Bean - Part 3

Introduction
The message-driven bean model develops an Enterprise Bean that is asynchro­nously invoked by the container to handle the processing of incoming messages.
From the perspective of the client, the existence of a message-driven bean is completely hidden behind the destination or endpoint for which the message-driven bean is the message listener.



Implementing the MessageListener
A message-driven bean implements javax.jms.MessageListener interface (JMS Message driven bean). The container uses the listener interface to register the message-driven bean with the message provider and to pass incoming messages by invoking implemented message listener methods. There are different ways to define a message-driven bean.
1.     @MessageDriven (name="ShippingRequestJMSProcessor",
              messageListenerInterface="javax.jms.MessageListener")
public class ShippingRequestProcessorMDB {

2.     public class ShippingRequestProcessorMDB implements MessageListener
3.     Deployment descriptor.

The bean’s message listener method void onMessage(Message message) is called by the container when a message has arrived for the bean to service. The message lis­tener method contains the business logic that handles the processing of the message.
Note: If the message-driven bean class implements more than one interface other than java.io.Serial­izable, java.io.Externalizable, or any of the interfaces defined by the javax.ejb pack­age, the message listener interface must be specified by the messageListenerInterface element of the MessageDriven annotation or the messaging-type element of the mes­sage-driven deployment descriptor element.
Activation Configuration Properties
The activationConfig property of the @MessageDriven annotation allows you to provide messaging system-specific configuration information through an array of ActivationConfigProperty instances.
ActivationConfigProperty
propertyName
propertyValue
Description
destinationType
javax.jms.Queue
Tells the container this JMS MDB is listening to a queue.
javax.jms.Topic
Tells the container this JMS MDB is listening to a topic.
destinationName
jms/ShippingRequestQueue
Specifies that we are listening for messages arriving at a destination with the JNDI name of jms/ShippingRequestQueue.
connectionfactoryJndiName
jms/QueueConnectionFactory
Specifies the JNDI name of the connection factory that should be used to create JMS connections for the MDB.
acknowledgeMode
AUTO_KNOWLEDGE
The session automatically acknowledges receipt after a message has been received or is successfully processed.
DUPS_OK_ACKNOWLEDGE
The session can lazily acknowledge receipt of the message.
subscriptionDurability
Durable
Once a consumer obtains a durable subscription on a topic, all messages sent to the topic are guaranteed to be delivered to the consumer.
NonDurable (By default)
In the pub-sub domain, a message is distributed to all currently subscribed consumers. In general, this is much like a broadcast message in that anyone who is not connected to the topic at the time does not receive a copy the message.
messageSelector
JMSType = ‘car’ AND color = ‘blue’ and weight > 2500
Determines which messages a JMS message-driven bean is to receive.

Example 1.
@MessageDriven(
           name="ShippingRequestProcessor",
           activationConfig = {
               @ActivationConfigProperty(
                   propertyName="destinationType",
                   propertyValue="javax.jms.Queue"),
               @ActivationConfigProperty(
                   propertyName="connectionFactoryJndiName",
                   propertyValue="jms/QueueConnectionFactory"
               ),
               @ActivationConfigProperty(
                   propertyName="destinationName",
                   propertyValue="jms/ShippingRequestQueue")
           }
       )
Using bean lifecycle callbacks
The container is responsible for the following:
1.     A MDB instance’s life starts when the container invokes newInstance on the MDB class to create a new instance. Next, the container injects the bean’s MessageDriverContext, if applicable, and performs any other dependency injection as specified by metadata annotations on the bean class or by the deployment descriptor. The container then calls the bean’s PostConstruct lifecycle callback methods, if any.
2.     The MDB instance is now ready to be delivered a message sent to its associated destination or endpoint by any client or a call from the container to the timeout callback method.
3.     When the container no longer needs the instance (happens when the container wants to reduce the number of instances in the method-ready pool), the container invokes the PreDestroy lifecycle callback methods for it, if any. This ends the life of the MDB instance.





The following lifecycle event callbacks are supported for message-driven beans.
PostConstruct.
PreDestroy.
A message driven bean can be registered with the EJB timer service for time-based event notifications. The container invokes the appropriate bean instance timeout callback method when a timer for the bean has expired.
The AroundInvoke business method interceptor methods are supported for message-driven beans.
Serializing Message-Driven Bean Methods
The container serializes calls to each message-driven bean instance. Most containers will support many instances of a message-driven bean executing concurrently; however, each instance sees only a serial­ized sequence of method calls. Therefore, a message-driven bean does not have to be coded as reentrant.
The container must serialize all the container-invoked callbacks (e.g., lifecycle callback interceptor methods and timeout callback methods), and it must serialize these callbacks with the message listener method calls.
Concurrency of Message Processing
A container allows many instances of a message-driven bean class to be executing concurrently, thus allowing for the concurrent processing of a stream of messages. No guarantees are made as to the exact order in which messages are delivered to the instances of the message-driven bean class, although the container should attempt to deliver messages in order when it does not impair the concurrency of mes­sage processing. Message-driven beans should therefore be prepared to handle messages that are out of sequence: for example, the message to cancel a reservation may be delivered before the message to make the reservation.
Transaction Context of Message-Driven Bean Methods and acknowledgment
If the MDB uses container-managed transaction demarcation:
§          In message listener methods
REQUIRED. The message receipt is part of the transac­tion and message acknowledgment is handled automatically as a part of the transaction commit.
NOT_SUPPORTED.
§          In timeout callback methods
REQUIRED.
REQUIRES_NEW.
NOT_SUPPORTED.
If the MDB uses bean-managed transaction demarcation uses the javax.trans­action.UserTransaction interface to demarcate transactions, the message receipt is not part of the transaction. The receipt is acknowledged by the container (AUTO_ACKNOWLEDGE semantics or DUPS_OK_ACKNOWLEDGE).
Dealing with Exceptions
A message-driven bean’s message listener method must not throw the java.rmi.RemoteExcep­tion.
Message-driven beans should not, in general, throw RuntimeExceptions.
A RuntimeException that is not an application exception thrown from any method of the mes­sage-driven bean class (including a message listener method and the callbacks invoked by the container) results in the transition to the “does not exist” state. If a message-driven bean uses bean-managed trans­action demarcation and throws a RuntimeException, the container should not acknowledge the message.
From the client perspective, the message consumer continues to exist. If the client continues sending messages to the destination or endpoint associated with the bean, the container can delegate the client’s messages to another instance.
The message listener methods of some messaging types may throw application exceptions. An applica­tion exception is propagated by the container to the resource adapter.

Some Basic Scenarios
 Scenario 1.

 Scenario 2.