Java EE6 Decorators, decorating classes at injection time

A common design pattern in software is the decorator pattern. We take a class and we wrap another class around it. This way, when we call the class, we always pass trough the surrounding class before we reach the inner class
Java EE 6 lets us create decorators through CDI, as part of their AOP features. If we want to implement cross cutting concerns that are still close enough to the business, we can use this feature of Java EE 6.
Let’s say you have a ticket service that lets you order tickets for a certain event. The TicketService handles the registration etc, but we want to add catering. We don’t see this as part of the ticket ordering logic, so we created a decorator.
The decorator will call the TicketService and add catering for the number of tickets.
The interface

public interface TicketService {
    Ticket orderTicket(String name);
}

The implementation of the interface, creates a ticket and persists it.

@Stateless
public class TicketServiceImpl implements TicketService {

    @PersistenceContext
    private EntityManager entityManager;

    @TransactionAttribute
    @Override
    public Ticket orderTicket(String name) {
        Ticket ticket = new Ticket(name);
        entityManager.persist(ticket);
        return ticket;
    }
}

When we can’t use a decorator, we can create a new implementation of the same interface.

@Decorator
public class TicketServiceDecorator implements TicketService {

    @Inject
    @Delegate
    private TicketService ticketService;
    @Inject
    private CateringService cateringService;

    @Override
    public Ticket orderTicket(String name) {
        Ticket ticket = ticketService.orderTicket(name);
        cateringService.orderCatering(ticket);
        return ticket;
    }
}

Notice that we apply 2 CDI specific annotations here. The @Decorator marks the implementation as a decorator. A decorator should always have a delegate, a class we want to decorate, marked with the @Delegate annotation (at the injection point). Also take notice of the fact that we use the interface and not the implementation.
Just like the alternative example, when you inject this interface, the normal implementation will be used.

@Inject private TicketService ticketService;

Instead of using qualifiers, we just have to adjust our beans.xml to mark the TicketServiceDecorator as ‘Decorator’.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
    <decorators>
        <class>be.styledideas.blog.decorator.TicketServiceDecorator</class>
    </decorators>
</beans>

See this post for more advanced topics

Java EE6 CDI, Named Components and Qualifiers

One of the biggest promises java EE6 made, was to ease the use of dependency injection. They did, using CDI. CDI, which stands for Contexts and Dependency Injection for Java EE, offers a base set to apply dependency injection in your enterprise application.
Before CDI, EJB 3 also introduced dependency injection, but this was a bit basic. You could inject an EJB (statefull or stateless) into another EJB or Servlet (if you container supported this). Offcourse not every application needs EJB’s, that is why CDI is gaining so much popularity.
To start, I have made this example. There is a Payment interface, and 2 implementations. A cash payment and a visa payment.
I want to be able to choose witch type of payment I inject, still using the same interface.

public interface Payment {
    void pay(BigDecimal amount);
}

and the 2 implementations

public class CashPaymentImpl implements Payment {

    private static final Logger LOGGER = Logger.getLogger(CashPaymentImpl.class.toString());

    @Override
    public void pay(BigDecimal amount) {
        LOGGER.log(Level.INFO, "payed {0} cash", amount.toString());
    }
}
public class VisaPaymentImpl implements Payment {

    private static final Logger LOGGER = Logger.getLogger(VisaPaymentImpl.class.toString());

    @Override
    public void pay(BigDecimal amount) {
        LOGGER.log(Level.INFO, "payed {0} with visa", amount.toString());
    }
}

To inject the interface we use the @Inject annotation. The annotation does basically what it says. It injects a component, that is available in your application.

@Inject private Payment payment;

Off course, you saw this coming from a mile away, this won’t work. The container has 2 implementations of our Payment interface, so he does not know which one to inject.

Unsatisfied dependencies for type [Payment] with qualifiers [@Default] at injection point [[field] @Inject private be.styledideas.blog.qualifier.web.PaymentBackingAction.payment]

So we need some sort of qualifier to point out what implementation we want. CDI offers the @Named Annotation, allowing you to give a name to an implementation.

@Named("cash")
public class CashPaymentImpl implements Payment {

    private static final Logger LOGGER = Logger.getLogger(CashPaymentImpl.class.toString());

    @Override
    public void pay(BigDecimal amount) {
        LOGGER.log(Level.INFO, "payed {0} cash", amount.toString());
    }
}
@Named("visa")
public class VisaPaymentImpl implements Payment {

    private static final Logger LOGGER = Logger.getLogger(VisaPaymentImpl.class.toString());

    @Override
    public void pay(BigDecimal amount) {
        LOGGER.log(Level.INFO, "payed {0} with visa", amount.toString());
    }
}

When we now change our injection code, we can specify wich implementation we need.

@Inject private @Named("visa") Payment payment;

This works, but the flexibility is limited. When we want to rename our @Named parameter, we have to change it on everyplace where it is used. There is also no refactoring support.
There is a beter alternative using Custom made annotations using the @Qualifier annotation. Let us change the code a little bit.
First of all, we create new Annotation types.

@java.lang.annotation.Documented
@java.lang.annotation.Retention(RetentionPolicy.RUNTIME)
@javax.inject.Qualifier
public @interface CashPayment {}
@java.lang.annotation.Documented
@java.lang.annotation.Retention(RetentionPolicy.RUNTIME)
@javax.inject.Qualifier
public @interface VisaPayment {}

The @Qualifier annotation that is added to the annotation, makes this annotation discoverable by the container. We can now simply add these annotations to our implementations.

@CashPayment
public class CashPaymentImpl implements Payment {

    private static final Logger LOGGER = Logger.getLogger(CashPaymentImpl.class.toString());

    @Override
    public void pay(BigDecimal amount) {
        LOGGER.log(Level.INFO, "payed {0} cash", amount.toString());
    }
}
@VisaPayment
public class VisaPaymentImpl implements Payment {

    private static final Logger LOGGER = Logger.getLogger(VisaPaymentImpl.class.toString());

    @Override
    public void pay(BigDecimal amount) {
        LOGGER.log(Level.INFO, "payed {0} with visa", amount.toString());
    }
}

The only thing we now need to do, is change our injection code to

@Inject private @VisaPayment Payment payment;

When we now change something to our qualifier, we have nice compiler and refactoring support. This also adds extra flexibilty for API or Domain-specific language design.

Java EE6 Alternatives, A flexible configuration for enterprise applications

Another great feature of java ee 6 is the use of alternatives. The basic idea is to let you specify an alternative for an injected object. Take this case for example.
We are developing our front-end of our application. The screens depend on a database connection, but the database isn’t ready for development. We provide an ‘alternative’ implementation for this time being.
You can specify a mock and inject that. With this approach you need to change the wiring of your class.

public interface CustomerService {
    List findAllCustomers();
}

Your implementation would look something like this.

public class CustomerServiceImpl implements CustomerService {

    @PersistenceContext
    private EntityManager em;

    @Override
    public List findAllCustomers(){
        Query query = em.createNamedQuery("Customer.findAll", Customer.class);
        return query.getResultList();
    }
}

And the mock implementation like this.

public class CustomerServiceMock implements CustomerService {

    @Override
    public List findAllCustomers() {
        return Arrays.asList(new Customer("Geraldo"), new Customer("Scruffy"), new Customer("Haddock"));
    }

}

In your class that is using this service, you can just inject it.

@Inject private CustomerService customerService; 

When you try to run this, it will give an error:

‘Ambiguous dependencies for type [CustomerService] with qualifiers [@Default] at injection point [[field] @Inject private be.styledideas.blog.alternative.web.CustomerBackingBean.customerService]. Possible dependencies [[Managed Bean [class be.styledideas.blog.alternative.CustomerServiceMock] with qualifiers [@Any @Default], Managed Bean [class be.styledideas.blog.alternative.CustomerServiceImpl] with qualifiers [@Any @Default]]]. Please see server.log for more details.’

The container does not know what implementation should be injected. We will have to mark the mock implementation. We do this by adding the @Alternative annotation on top of it.

@Alternative
public class CustomerServiceMock implements CustomerService {

    @Override
    public List findAllCustomers() {
        return Arrays.asList(new Customer("Haddock"), new Customer("Geraldo"), new Customer("Scruffy"));
    }
}

When we now start our server, there is only one implementation that qualifies for this injection point, i.e. the CustomerServiceImpl class.
This isn’t what we want to achieve, we want to be able to inject our mock for the time we cannot connect to the database.
In our beans.xml file (CDI standard) we add this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
    <alternatives>
        <class>be.styledideas.blog.alternative.CustomerServiceMock</class>
    </alternatives>
</beans>

Whenever we run our code, we will have a mock implementation where we use the customer service. Due this is configured in an xml file, we can change this without having to do a recompile of our application.
Next up, decorators.

Java EE6 Events, a lightweight alternative to JMS

A few weeks ago I attended a bejug meeting about Java EE 6, Building next generation enterprise applications. Having read much about it, I did not expect to see much shocking hidden features. But there was one part of the demo I really found impressive. Due to its loose coupling, Enterprise possibilities and simplicity. The feature I’m going to talk about today is the event mechanism that is in java EE 6.
The general idea is to fire an event and let an eventlistener pick it up. I have created this example that is totally useless, but it simplicity helps me to focus on the important stuff. I’m going to fire a LogEvent from my backing action, that will log to the java.util.Logger.
The first thing I need is to create a pojo that contains my log message and my LogLevel.

public class LogMessage implements Serializable {

    private final String message;
    private final Level level;

    LogMessage(String message, Level level) {
        this.message = message;
        this.level = level;
    }

    public String getMessage() {
        return message;
    }

    public Level getLevel() {
        return level;
    }
} 

easy peasy.
Now that I have my data wrapper, I need something to fire the event and something to pick it up. The first thing I create is my method where I fire the event.
Due to CDI I can inject an event.

 @Inject Event<LogMessage> event;

So we just need to fire it.

 event.fire(new LogMessage("Log it baby!", Level.INFO));

Now the event is fired, If no one is registerd to pick it up, it disappears into oblivion, thus we create a listener. The listeners needs a method that has one parameter, the generic type that is given to the previous event. LogMessage.

public class LogListener {
    private static final Logger LOGGER = Logger.getAnonymousLogger();
    public void process(@Observes LogMessage message){
        LOGGER.log(message.getLevel(), message.getMessage());
    } 
}

The @Observes annotation listens to all events with a LogMessage. When the event is fired, this method will be triggered.
This is a very nice way to create a loosely coupled application, you can separate heavy operations or encapsulate less essential operations in these event listeners.
All of this all happens synchronously. When we want to replace the log statement with a slow database call to a logging table, we could make our operation heavier than it should be. What I’m looking for is to create an asynchronous call.
As long as we support EJB, we can transform our Listener to an EJB by adding the @Stateless annotation on top of it. Now it’s a statless enterprise bean. This changes nothing to our sync/async problem, but EJB 3.1 support async operations. So if we also add the @Asynchronous annotation on top of it. It will asynchronously execute our logging statement.

@Stateless
@Asynchronous
public class LogListener {
    private static final Logger LOGGER = Logger.getAnonymousLogger();
    public void process(@Observes LogMessage message){
        LOGGER.log(message.getLevel(), message.getMessage());
    }
}

If we would want to combine the database logging and the console logging, we can just create multiple methods that listen to the same event.
This is a great way to create a lightweight application with a very flexible components. The alternative solution to this problem is to use JMS, but you don’t want a heavyweight configuration for this kind of loosely coupling.
Java EE has worked hard to get rid of the stigma of being heavyweight, I think they are getting there :-)

this.life()

As a consultant working in a big city, I spend allot of time on the road. Is it in the car or in the train, I lose a lot of time. One of ways I try to make up for this lost time, is by listening to podcast. Most podcasts I listen to are technical, that way I can expand my knowledge. I listen to podcasts like The Java Posse,Stackoverflow podcast, IBM developer works, The Pragmatic programmer and so on.
But not all podcast should be technical, I discovered this podcast that puts the social aspect of a developer in the spotlight. This Developer life is a podcast based upon the popular podcast ‘This American life’. It’s a show with stories lived and told by developers. All these stories circle around a certain subject, like ‘Pressure’, ‘Being mean’, ‘Obsession’ and ‘Fame And Notoriety’.
I must say I really like the show, it is brought by Scott Hanselman and Rob Conery. They do a great job binding the stories together. If you don’t know it, check it out, it certainly worth it
This developers life podcast