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.

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

Parameterized Unit Test

When you are writing unit tests, you want to test all the border cases. You can create a method for every border case, but sometimes this is a very repetitive job.

JUnit has a more pragmatic approach for these sorts of tests, called Parameterized tests. The idea is simple. You create your testcase with your test methods. You define a list of parameters that is given to the constructor and all the tests inside the testcase are executed for every parameter.

See this example. A simple class: Calculator

package be.styledideas.blog;

public class Calculator {
    public Long add(Long a, Long b){
        return a+b;
    }
}

I want to test this method with more than one parameter. I have created this parameterized unit test.

package be.styledideas.blog;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.ArrayList;
import java.util.Collection;

@RunWith(Parameterized.class)
public class CalculatorAddTestCase {
    private Long a;
    private Long b;
    private Long expected;

    public CalculatorAddTestCase(Long a, Long b, Long expected) {
        this.a = a;
        this.b = b;
        this.expected = expected;
    }

    @Test
    public void add() {
        Long actual = new Calculator().add(a, b);
        Assert.assertEquals(expected, actual);
    }

    @Parameterized.Parameters
    public static Collection<Object[]> getParameters(){
        Collection<Object[]> parameters = new ArrayList<Object[]>();
        parameters.add(new Object[]{1L, 2L, 3L});
        parameters.add(new Object[]{-1L, 2L, 1L});
        parameters.add(new Object[]{2L, 2L, 3L});
        parameters.add(new Object[]{4L, 0L, 4L});
        return parameters;
    }
}

The first thing that is different about this test is the @RunWith annotation at the top. Instead of the Junit4 runner, we use the Parameterized runner. This annotations looks for a static method that is annotated with the @Parameters annotation.
When we look closer at the getParameters method, we see that every item in the List maps to the constructor of the TestCase, so every item represents a running test. This concrete example results in equal to 4 unit tests.

Now you can be wondering what is the added value of this annotation over a list that you pass to your test. If you are just giving a test method a List with parameters, and one parameter creates a failure in your test, you will have to search for the test that is failing. When you execute it this way, any modern IDE will point which parameter is incorrect.

Gmail habits in Jira 4

Some time ago I learned about the keyboard shortcuts of gmail. This was a tremendous win for me. I spend a day learning the most common shortcuts. Now I can check my email much faster. When you enable these shortcuts, you get to see a pointer in front of your mail you are on.

I noticed that when our version of jira was updated from 3 to 4 (v4.2.2), here were also pointers in my issue navigation frame.

I just tried j and k and it worked (navigating up and down). Then I tried g + i (goto inbox) and it brought me back to the ‘Find Issues’ page.
Allright, so my known gmail shortcuts help me navigate trough jira. Here’s a complete list of shortcuts for jira:

If your hotkeys are not enabled, goto the account dropdown in the corner and choose keyboard shortcuts.

At the bottom you can enable or disable them.

Smoketest Dogs

When working on a very large project, quality is of the essence. One key part of adding quality to a software project, is by testing.

You have several ways of testing an application. We used unit testing, integration testing, selenium testing. But due to a big difference between our local testing environment (tomcat server) and our test teams environment (websphere), we have to check our release when it is deployed on the test teams environment.
We used the principle of smoke testing. Doing some basic actions and see that the application is still stable. Only big failures are fixed in the release. When we discover a bug, we register it in our bug tracker and it is fixed in the next release.

I think we could also used Arquillian. Arquillian is a framework that wraps your integration test into the container you run them in. Unfortunately Arquillian wasn’t an option. We had to do the test manually.

We started with creating a checklist that is hosted on our local wiki.
checklist
This way, we make sure that everything is checked before we migrate our release to the testers. Simple, but very efficient.

We are using this checklist, but every release, everyone tests the same features. This leads into cases where someone always tests the same way. This way, some essential things could be forgotten.

We wanted to create a system where we cycle over test, so each group of test is executed by someone else, with enough rotation to make sure no testing habit is developed.

We wanted to keep this a bit fun, because no one really likes doing smoke tests.

The smoke test dogs came to life.
The idea is simple, the tests on the checklist have a certain color. there are as many colors as there are characters in Quentin Tarantino‘s movie, Reservoir dogs.

The day of the release, everyone picks a card in the scrum stand-up meeting. This indicates what test should be executed.
We have a placeholder in our office where the cards should hang when all the test are succeeded. When all the cards are back, we are ready to release to our testers.

This is a very simple way to keep testing fun for everyone. The only disclaimer, this could lead to some role playing 😉
Big thanks to my collegues @erwinravau, @jordanvermeir, @jaspervdm, Cindy and Maarten

And if you aren’t there, you’re mr. pink!
If you're not there, you're mr Pink!