Tuesday 29 December 2009

Beyond Technologies: Domain Driven Design - Layered architecture

1. Introduction
In this post I sum up the most important concepts about Domain Driven Design.
I recommend you when you read this post not to think in technologies. Put away the technical knowledge and think from an upper level, from an architectural level.

2. Domain Driven Design elements
In future posts I will show my understanding about the following concepts:


  • Layered Architecture
  • Services
  • Entities
  • Value Objects
  • Aggregates
  • Repositories
  • Factories


3. Isolating the domain with a Layered architecture




The design and implementation of business logic constitute the domain layer. Isolating the domain implementation is a prerequisite for domain-driven design.




User interface

  • It shows information to the user
  • It interprets the user´s commands.

Application Layer

  • It defines the jobs the software is supposed to do.
  • The tasks are meaningful to the business or necessary for interaction with the application layers of other systems.
  • This layer is thin and does not contain business rules or knowledge
  • It coordinates tasks and delegates work to collaborations of domain objects in the next layer down.

Domain Layer or Model layer

  • It represents concepts of the business and the business rules.
  • The state that reflects the business situation is controlled and used here
  • This layer is the heart of the business software.

Infrastructure Layer

  • Provides generic technical capabilities that support the higher layers: message sending for the application, persistence for the domain, drawing widgets for the UI, and so on.
  • This infrastructure layer may also support the pattern of interactions between the four layers through an architectural framework.

Martin Fowler says: “If the architecture isolates the domain-related code in a way that allows a cohesive domain design loosely coupled to the rest of the system, then that architecture can probably support domain-driven design”.

4. References

Eric Evans 2004. Domain Driven Design. Tackling Complexity in the Heart of Software. Addison-Wesley.

Tuesday 8 December 2009

Locking in JPA 2.0

1.     Introduction
The JPA specification 2.0 assumes that the databases to which persistence units are mapped will be accessed by the implementation using read-committed isolation (or a vendor equivalent in which long-term read locks are not held).

2.     Optimistic Locking
Optimistic locking is a technique that is used to insure that updates (merge operation) to the database data corresponding to the state of an entity are made only when no intervening transaction has updated that data since the entity state was read.

Version Attributes
The Version field or property is used by the persistence provider to perform optimistic locking. An entity is automatically enabled for optimistic locking if it has a property or field mapped with a Version mapping.

@Entity
@Table(name = "ITEMS")
public class Item implements Serializable {
         
          @Id
          @Column(name = "ITEM_ID")
          private Long itemId;
         
@Column(name = "ITEM_NAME")
          private Long itemName;

          @Version
          @Column(name = "OPT_LOCK")
          private Integer version;
         
         
}

The persistence provider's implementation of the merge operation must examine the version attribute when an entity is being merged and throw an OptimisticLockException if it is discovered that the object being merged is a stale copy of the entity—i.e. that the entity has been updated since the entity became detached.

The version attribute is updated by the persistence provider runtime when the object is written to the database.

UPDATE ITEMS SET ITEM_NAME = 'Name test', OPT_LOCK = 2 WHERE ITEM_ID = 700 AND OPT_LOCK = 1

Optimistic lock modes
If transaction calls lock(entity, LockModeType.OPTIMISTIC) on a versioned object, the entity manager must ensure that neither dirty read nor non-repeatable read occurs.

If transaction calls lock(entity, LockModeType.OPTIMISTIC_FORCE_INCREMENT) on a versioned object, the entity manager must ensure that neither dirty read nor non-repeatable read occur and force an increment to the version at the end of the transaction, even if the entity is not modified.

Note: LockModeType.OPTIMISTIC is synonymous with LockModeType.READ and LockModeType. OPTIMISTIC_FORCE_INCREMENT is synonymous with LockModeType.WRITE.

3.     Pessimistic Locking
Pessimistic concurrency locks the database row when data is read and it ensures that transactions do not update the same entity at the same time, which can simplify application code, but it limits concurrent access to the data which can cause bad scalability and may cause deadlocks. Pessimistic locking is better for applications with a higher risk of contention among concurrent transactions. 

Pessimistic locking guarantees that once a transaction has obtained a pessimistic lock (long-term database locks) on an entity instance:

No other transaction (whether a transaction of an application using the Java Persistence API or any other transaction using the underlying resource) may successfully modify or delete that instance until the transaction holding the lock has ended.

If the pessimistic lock is an exclusive lock (LockModeType.PESSIMISTIC_WRITE or LockModeType.PESSIMISTIC_FORCE_INCREMENT), that same transaction may modify or delete that entity instance.

A persistence provider may use an underlying database platform's SELECT FOR UPDATE statements to implement pessimistic locking if that construct provides appropriate semantics, or the provider may use an isolation level of repeatable read.

Pessimistic lock modes
These lock modes are used to immediately obtain long-term database locks. Any locks must be obtained immediately and retained until transaction completes (commits or rolls back).

If transaction calls lock(entity, LockModeType.PESSIMISTIC_READ) or lock(entity, LockModeType.PESSIMISTIC_WRITE) on an object, the entity manager must ensure that dirty read nor non-repeatable read occurs.

If transaction calls lock(entity, LockModeType.PESSIMISTIC_FORCE_INCREMENT) on a versioned object, the entity manager must ensure that dirty read nor non-repeatable read occurs and must also force an update (increment) to the entity's version column.


4.     API to use
There are multiple APIs to specify locking an Entity: 
1.     EntityManager methods: lock, find, refresh
2.     Query methods: setLockMode 
3.     NamedQuery annotation: lockMode element 


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.