Monday 29 March 2010

Java EE 5 Annotations and Resource Injection in some container managed components

The Annotations that are required by a Java EE technology compliant web container:


Annotations
@DeclareRoles (*)
@RunAs (*)
@EJB
@EJBs
@Resource
@Resources
@PersistenceContext
@PersistenceContexts
@PersistenceUnit
@PersistenceUnits
@PostConstruct
@PreDestroy
@WebServiceRef
@WebServiceRefs



Annotations must be supported on the following container managed classes that implement the following interfaces:

Component Type
Component Type Classes implementing the following interfaces

Notes
Servlets
javax.servlet.Servlet

Java Servlet Specification version 2.5

References must be injected prior to any lifecycle methods being called and the component instance being made available the application.

Filters
javax.servlet.Filter

Listeners
javax.servlet.ServletContextAttributeListener
javax.servlet.ServletRequestListener
javax.servlet.ServletRequestAttributeListener
javax.servlet.http.HttpSessionListener
javax.servlet.http.HttpSessionAttributeListener
javax.servlet.AsyncListener

ManagedBean
JavaServer Faces Specification v 2.0

Only beans declared to be in request, session, or application scope are eligible for resource injection.

Methods on managed beans declared to be in request, view, session, or application scope, annotated with @PostConstruct, must be called by the JSF implementation after resource injection is performed (if any) but before the bean is placed into scope.

Methods on managed beans declared to be in request, session, or application scope, annotated with @PreDestroy, must be called by the JSF implementation before the bean is removed from its scope or before the scope itself is destroyed, whichever comes first. In the case of a managed bean placed in view scope, methods annotated with @PreDestroy must only be called when the view scope is destroyed.



(*) Annotations not allowed in Managed Bean


Thursday 18 March 2010

OO concepts: Adapter pattern

Introduction
In this post I sum up the Adapter pattern, an interesting OO pattern very useful in many situations. From my point of view, in the most enterprise situations where I needed to integrate with external systems, the idea of using adapter pattern provided to the systems a transparent way to communicate with other interfaces.
It is relevant to mention that this pattern is very important to build the ANTICORRUPTION LAYER in Domain Driven Design.

Description
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that could not otherwise because of incompatibles interfaces.

Scenario
The figure shows a design of a Web search engine that queries the databases of multiple libraries.
Libray1SearchEngine and Libray2SearchEngine classes have already implemented. These two classes implement Searchable interface so that the SearchInvoker class can call them interchangeably.
Let assume that a search implementation for a third library is wanted. Most of the code is already written in the Libray3SearchEngine class.
This class is used in a previously developed client-server application. Unfortunately, Libray3SearchEngine does not have all the needed functionality and has a different interface than the other search engine classes. The library plans to continue using the previously developed client-server application, so if you modified Libray3SearchEngine, you would have to maintain two versions of the class. You don’t want to complicate SearchInvoker by making it deal with the different interfaces, so you need a way to adapt Libray3SearchEngine to the Searchable interface.



Solution
The Adapter pattern recommends creating a new Adapter class that implements the DesiredInterface and propagates requests to the existing Adaptee class. The Client class calls methods on Adapter, not on Adaptee. If the DesiredInterface requires some functionality that is not supported by Adaptee, Adapter can implement that functionality directly.

Object Adapter Strategy Structure



Class Adapter Strategy Structure


Solution in this scenario



Consequences
The advantages of using the Adapter pattern are:
§          The client class is not complicated by having to use a different interface and can use polymorphism to swap between different implementations of DesiredInterface.
§          The adaptee class is not modified.
The disadvantages of using the Object Adapter strategy are:
§          There are two objects involved, so you must create an additional object.
§          All requests are forwarded, so there is a slight increase in the overhead.
The disadvantages of using the Class Adapter strategy are:
§          The interface of the adapter class also supports the interface of the adaptee class, so the client is coupled to the adaptee class.
§          In Java programming language, the single subclassing slot for a class is used up in adaptation. Therefore, you must use interfaces to support other features.

References
Gamma, Helm, Johnson, and Vlissides 2004. Design Patterns. Elements of Reusable Object-Oriented Software. Addison-Wesley.

Wednesday 10 February 2010

OO concepts: Observer pattern

Introduction
In this post I sum up the Observer pattern, an interesting OO pattern very useful in many situations.

Description
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.


The Observer pattern describes how to establish these relationships. The key objects in this pattern are subject and observer. A subject may have any number of dependent observers. All observers are notified whenever the subject undergoes a change in state. In response, each observer will query the subject to synchronize its state with the subject’s state.

This kind of interaction is also known as publish-subscribe. The subject is the publisher of notifications. It sends out these notifications without having to know who its observers are. Any number of observers can subscribe to receive notifications.

Basic Pattern



Complex Pattern



Consequences
The advantages are:
§          You can vary and independently reuse classes for the Subject and Observer objects.
§          The abstract classes (or interfaces) are coupled together. Therefore, the coupling is looser than if the concrete classes were coupled.
§          You can easily add Observer objects without a single change to the Subject object.
The disadvantages are:
§          An observer system can become flooded with updates if the granularity of the update is too fine or its frequency too high. This is a critical problem in distributed systems.
§          The observer system often calls the subject when it receives a notification. This can create a bottleneck, preventing the timely update of the other observer systems.

References
Gamma, Helm, Johnson, and Vlissides. Design Patterns. Elements of Reusable Object-Oriented Software. Addison-Wesley.

Tuesday 2 February 2010

Beyond Technologies: Domain Driven Design - Anticorruption layer

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.

Scenario
On a large project, one subsystem will often have to interface with several other, independently developed subsystems. These will reflect the problem domain differently. When systems based on different models are combined, the need for the system to adapt to the semantics of the other system can lead to a corruption of the new system’s own model.

We should create an isolating layer, ANTOCORRUPTION LAYER, to provide clients with functionality in terms of their own domain model. The layer talks to other system through its existing interface, requiring little or no modification to other system. Internally, the layer translates in both directions as necessary between the two models.

Note: ANTOCORRUPTION LAYER is not a mechanism for sending messages to another system, is a means of linking two BOUNDED CONTEXTS.

Designing the interface
The public interface of the ANTICORRUPTION LAYER usually appears as a set of SERVICES. Building a whole new layer responsible for the translation between the semantics of the two systems gives us an opportunity to reabstract the other system’s behavior and offer its services and information to our system consistently with our model.


Implementation
The ANTICORRUPTION LAYER is a combination of FAÇADES, ADAPTERS and translator, along with the communication and transport mechanisms needed to talk between systems.

A FAÇADE is an interface for a subsystem that simplifies access for the client and makes the subsystem easier to use. It should be written strictly in accordance with the other system’s model. The FAÇADE belongs in the BOUNDED CONTEXT of the other system. It just presents a friendlier face specialized for your needs.

An ADAPTER is a wrapper that allows a client to use a different protocol than that understood by the implementer of the behavior. When a client sends a message to an ADAPTER, it is converted to a semantically equivalent message and sent on to the “adaptee”. The response is converted and passed back.

For each SERVICE we define, we need an ADAPTER that supports the SERVICE’s interface and knows how to make equivalent requests of the other system or its FAÇADE.

The remaining element is the translator. The ADAPTER’s job is to know how to make a request. The actual conversion of conceptual objects or data is a distinct, complex task that can be placed in its own object, making them both much easier to understand. A translator can be a lightweight object that is instantiated when needed. It needs no state and does not need to be distributed, because it belongs with the ADAPTER it serves.



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

Friday 15 January 2010

Beyond Technologies: Domain Driven Design - Factories and Repositories

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.


Encapsulating with FACTORIES
A FACTORY encapsulates the knowledge needed to create a complex object or AGGREGATE, which may itself have no responsibility in the domain model but is still part of the domain design. Provide an interface that encapsulates all complex assembly and that does not require the client to reference the concrete class of the objects being instantiated.
There are some PATTERNS to design FACTORIES
1. FACTORY METHOD
2. ABSTRACT FACTORY
3. BUILDER
Requirements for a FACTORY are:
§          Each creation method is atomic and enforces all invariants of the created object or AGGREGATE.
§          A FACTORY should only be able to produce an object in a consistent state.
§          For an ENTITY, this means the creation of the entire AGGREGATE, with all the invariants satisfied, but probably with optional elements still to be added.
§          For an immutable VALUE OBJECT, this means that all attributes are initialized to their correct final state. If the interface makes it possible to request an object that can not be created correctly, then an exception should be raised or some other mechanism should be invoked that will ensure that no improper return value is possible.
§          The FACTORY should be abstracted to the type desired, rather than the concrete classes created.


Accessing with REPOSITORIES
The goal of domain-driven design is to create better software by focusing on a model of the domain rather than the technology.
A REPOSITORY represents all objects of a certain type as a conceptual set. It acts like a collection, except with more elaborate querying capability. Objects of the appropriate type are added and removed, and the machinery behind the REPOSITORY inserts them or deletes them from the database.
Clients request objects from the REPOSITORY using query methods that select objects based on criteria specified by the client, typically the value of certain attributes. The REPOSITORY retrieves the requested object, encapsulating the machinery of database queries and metadata mapping. Repositories can implement a variety of queries that select objects based on whatever criteria the client requires.





A REPOSITORY lifts a huge burden from the client, which can now talk to a simple, intention-revealing interface, and ask for what it needs in terms of the model. To support all this requires a lot of complex technical infrastructure, but the interface is simple and conceptually connected to the domain model.
For each type of object that needs global access, create an object that can provide the illusion of an in-memory collection of all objects of that type. Set up access through a well-known global interface. Provide methods to add and remove objects, which will encapsulate the actual insertion or removal of data in the data store. Provide methods that select objects based on some criteria and return fully instantiated objects or collections of objects whose attribute values meet the criteria, thereby encapsulating the actual storage and query technology. Provide REPOSITORIES only for AGGREGATE roots that actually need direct access. Keep the client focused on the model, delegating all object storage and access to the REPOSITORIES.


REPOSITORIES have many advantages, including the following:
·         
          1. They present clients with a simple model for obtaining persistent objects and managing their life cycle.
2. They decouple application and domain design from persistence technology, multiple database strategies, or even multiple data sources.
3. The communicate design decisions about object access.
4. They allow easy substitution of a dummy implementation, for use in testing.


The REPOSITORY will delegate to the appropriate infrastructure services to get the job done.
Note: Leave the transaction control to the client who presumably has the context to correctly initiate and commit units of work. Transaction management will be simpler if the REPOSITORY keeps its hands off.







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



Wednesday 6 January 2010

Beyond Technologies: Domain Driven Design - ENTITIES, VALUE OBJECTS, DOMAIN SERVICES AND AGGREGATES

Introduction
In this post I sum up concepts about Domain Driven Design:
§          Entities
§          Value Objects
§          Domain Services
§          Aggregates
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.
ENTITY
An object defined primarily by its identity and not by their attributes. ENTITIES have life cycles that can change their form and content, but a thread of continuity must be maintained. Their class definitions, responsibilities, attributes, and associations should resolve around who they are, rather than the particular attributes they carry.
VALUE OBJECT
An object that represents a descriptive aspect of the domain with no conceptual identity and we care about only for what they are, not who or which they are.
VALUE OBJECTS are often passed as parameters in messages between objects. They are frequently transient, created for an operation and then discarded.
VALUE OBJECTS are used as attributes of ENTITTIES (and other VALUES).
DOMAIN SERVICES
There are important domain operations that can not find a natural home in an ENTITY or VALUE OBJECT. Some of these are intrinsically activities or actions, not things. Forcing the required domain functionality to be responsibility of ENTITY or VALUE either distorts the definition of a model-based object or adds meaningless artificial objects.
The name service emphasizes the relationship with other objects. Unlike ENTITIES and VALUE OBJECTS, it is defined purely in terms of what it can do for a client. A SERVICE tends to be named for an activity. A SERVICE should still have defined responsibility, and that responsibility and the interface fulfilling it should be defined as part of the domain model. Operations should come from the UBIQUITOUS LANGUAGE or be introduced into it. Parameters and results should be domain objects.
A DOMAIN SERVICE has three characteristics:
1.     1. The operation relates to a domain concept that is not a natural part of an ENTITY or VALUE OBJECT.
2.     2. The interface is defined in terms of other elements of the domain model.
3.     3. The operation is stateless.
SERVICES IN LAYERS
Application services: are the interface used by the outside world. These services could map outside messages to internal operations and processes, communicating with services in the Domain and Infrastructure layers to provide cohesive operations for outside clients.
Domain services: Embeds business rules. These use the infrastructure services to do their tasks.
Infrastructure services: communication with external resources like databases, file systems, web service end points, etc.
AGGREGATES
An AGGREGATE is a set of associated objects that we treat as a unit for the purpose of data changes. Each AGGREGATE has a root and a boundary.
§          The boundary defines what is inside the AGGREATE.
§          The root is a single, specific ENTITY contained in the AGGREATE. The root is the only member that outside objects are allowed to hold references to, although objects within the boundary may hold references to each other.
It is difficult to guarantee the consistency of changes to objects in a model with complex associations. Invariants are consistency rules that must be maintained whenever data changes and will involve relationships between members of the AGGREGATE. The invariants applied within an AGGREAGATE will be enforced with the completion of each transaction.


Rules for implementing AGGREGATES:
1. The root ENTITY has global identity and is ultimately responsible for checking invariants. ENTITIES other than root inside the boundary have local identity, unique only within the AGGREGATE, because no outside object can ever see it out of the context of the root ENTITY.

2.     2. Nothing outside the AGGREGATE boundary can hold a reference to anything inside, except to the root ENTITY.

3.     3. The root ENTITY can hand references to internal ENTITIES to other objects, but those objects can use them only transiently, and they may not hold on to the reference. The root may hand a copy of a VALUE OBJECT to another object, and it does not matter what happens to it, because it is a VALUE and no longer will have any association with the AGGREGATE.

4.     4. Only AGGREGATE roots can be obtained directly with database queries. All other objects must be found by traversal of associations.

5.     5. Objects within the AGGREGATE can hold references to other AGGREGATE roots.

6.     6. A delete operation must remove everything within the AGGREGATE boundary at once.

7.     7. When a change to any object within the AGGREGATE boundary is committed, all invariants of the whole AGGREGATE must be satisfied.  

Example - Bank Customer








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