Java EE6 in the Cloud – Getting started with Red Hat Openshift

OpenShift For a while now I’m looking into ‘the cloud’. Looking into its features, what it can do, why we should switch to ‘ the cloud’, going to talks, talking to people like @maartenballiauw, who is a cloud specialist at RealDolmen. I’ve already deployed an application on google app engine (for java) and I really liked the experience. Some new concepts come into play like distributed data and so on.
But in the recent chain of events, being more interested in the future of java EE, I looked into OpenShift.
OpenShift is a PaaS offerd by Red Hat. The basic idea is to run Java EE 6 in the cloud and that is exactly what we want to do. I’m using Ubuntu for this, so all my commands are based upon the Ubuntu distro. Be sure to register for an account on openshift.redhat.com, you will need it to create a domain and application.

Starting of we have to install ruby gems. The ruby gems are the interface to manage our cloud domain. So first we install the gems.

$ sudo apt-get install git ruby rubygems ruby1.8-dev

We need git to checkout the code, the ruby packages is to install the gems. Now we install the gems.

$ sudo gem install rhc

The rhc (red hat cloud I presume) is the base for all the commands that will be used to manipulate our openshift domain. So first we need to create a domain.
The gems are standard deployed installed in the /var/lib/gems/1.8/gems/bin folder. We best add it to our $PATH variable for easy access. Now everything is ready to start working with openshift.

Now we want to create a domain. The domain is your work directory on OpenShift. Choose something unique and you will be able to access your applications via http://projectname-domainname.rhcloud.com. To create your domain we need the ‘rhc-create-domain’ command.

$ ./rhc-create-domain -n domainname -l loginid

Now you will be promted for you password, just type it and you are done. Your domain is created.
Your domain is setup, we now want to create an application.

$ ./rhc-create-app -a applicationName -t jbossas-7.0

The -t parameter indicates we will be running the application on a jbossas-7.0. The cool thing about creating an application on OpenShift is that we now have a fully setup git repository. When we push, the application is pushed to OpenShift.
To start of I forked the seambooking example on github (https://github.com/openshift/seambooking-example). I did not really need to fork it, but it offers a good basic setup for OpenShift project. Once I’ve added the code to my OpenShift git repository, I can simply do a git push.

$ git push

The sample app is running, running in the cloud…

More information on http://openshift.redhat.com and https://github.com/openshift/seambooking-example

Java EE6 Decorators, advanced usage

After I published my first article about Java EE6 decorators, it got some attention on dzone. I got some comments telling me the example isn’t exposing the true power of the decorator feature.
The first thing I did not mention in my previous post is that we can combine a number of decorators and choose the order we want them executed.
If you have a use case for it, you can easily define 2 decorators, by just defining them in the beans.xml file like this.

    <decorators>
        <class>be.styledideas.blog.decorator.HighDecorator</class>
        <class>be.styledideas.blog.decorator.LowDecorator</class>
    </decorators>

So when we call our decorated class, we get the highdecorator entry, low decorator entry, actual decorated class, low decorator exit, highdecorator exit. So the decorator sequence in the file does matter.
The second feature is more compelling than the first, it exposes the true power of the Decorator feature in java EE6. That is the ability to combine it with CDI annotations. As example I’ll use an Social media feed processor.
So I have created an interface

public interface SocialFeedProcessor {
    Feed process(String feed);
}

and provided 2 implementations, twitter and google+

public class TwitterFeedProcessor implements SocialFeedProcessor{

    @Override
    public Feed process(String feed) {
        System.out.println("processing this twitter feed");
        // processing logics
        return new Feed(feed);
    }
    
}
public class GooglePlusFeedProcessor implements SocialFeedProcessor {

    @Override
    public Feed process(String feed) {
        System.out.println("processing this google+ feed");
        // processing logics
        return new Feed(feed);
    }
    
}

I’ll annotate these 2 beans by a custom Qualifier as described here

@javax.inject.Qualifier
@java.lang.annotation.Retention(RUNTIME)
@java.lang.annotation.Target({FIELD, PARAMETER, TYPE})
@java.lang.annotation.Documented
public @interface FeedProcessor {
}

and I annotate my 2 processors with it.

@FeedProcessor
public class TwitterFeedProcessor implements SocialFeedProcessor{

    @Override
    public Feed process(String feed) {
        System.out.println("processing this twitter feed");
        // processing logics
        return new Feed(feed);
    }
    
}
@FeedProcessor
public class GooglePlusFeedProcessor implements SocialFeedProcessor {

    @Override
    public Feed process(String feed) {
        System.out.println("processing this google+ feed");
        // processing logics
        return new Feed(feed);
    }
    
}

Nothing really special, but now when we write our decorator we use the power of CDI to only decorate the classes with the @FeedProcessor annotation.

@Decorator
public class SocialFeedDecorator implements SocialFeedProcessor {
    @Delegate
    private @FeedProcessor SocialFeedProcessor processor;

    @Override
    public Feed process(String feed) {
        System.out.println("our decorator is decorating");
        return processor.process(feed);
    }
}

the only thing that is left is registering our decorator in our beans.xml

    <decorators>
        <class>be.styledideas.blog.decorator.SocialFeedDecorator</class>
    </decorators>

By using the annotation, we automatically decorate all our implementations of the SocialfeedProcessor with this decorator. When we add an extra implementation of the SocialFeedProcessor without the annotation, the bean will not be decorated.

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.