All posts by marcus

CDI Transaction Interceptor

If you use EJB transaction you know that every method could be wrapped in a transaction. But if you use CDI you have to manage the transactions yourself. To make this easy I created a Interceptor that wraps a UserTransaction and will join the EntityManager in the Transaction. I’ll show you how.
First you have to define an annotation for the interceptor, so that CDI knows when to use what interceptor (kind of qualifier).

In this post I will use @UseTransaction annotation.
First define a annotation, it have to look like this:

* Annotation to use {@link TransactionInterceptor}
* @author marcus
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface UseTransaction {


After that you have to implement the interceptor.
The Interceptor will looks like this.

 * JTA Transaction interceptor.
 * @author marcus
@UseTransaction @Interceptor
public class TransactionInterceptor {

  private static final Logger LOG = LoggerFactory.getLogger(TransactionInterceptor.class);
  private static final String TRANSACTION_JNDI = "java:comp/UserTransaction";

  * Wrap method
  * @param ctx InvocationContext from Interceptor.
  * @return result
  * @throws Exception if something goes wrong.
  public Object wrapTransaction(InvocationContext ctx) throws Exception {

    LOG.trace("Intercepting method");
    UserTransaction tx = getTransaction();
    if (tx == null) {
      // We are in a EJB transaction or no UserTransaction available. Don't wrap
      return ctx.proceed();
    // Check nested transaction
    if (tx.getStatus() != Status.STATUS_ACTIVE) {
      // Start transaction
      LOG.trace("Starting UserTransaction");
      // Join EntityManager in this transaction
      // Proceed intercepted method and store result.
      Object result = ctx.proceed();
      // Commit transaction
      LOG.trace("UserTransaction committed");
      // Return result
      return result;
    } else {
      return ctx.proceed();

  * @return Current active entity manager or null if none is found.
  protected EntityManager getEntityManager() {

    try {
      // Get EntityManager by CDI producer (you have to define a Producer for EntityManager.
      BeanManager manager = CDI.current().getBeanManager();
      Bean<?> bean = manager.resolve(manager.getBeans(EntityManager.class));
      Object obj = manager.getReference(bean, EntityManager.class, manager.createCreationalContext(bean));

      return (EntityManager)obj;
    } catch (Exception e) {
      // Error while retrieving EntityManager.
      return null;

  protected UserTransaction getTransaction() {
    try {
      Context context = new InitialContext();
      Object obj = context.lookup(TRANSACTION_JNDI);
      if (obj instanceof UserTransaction) {
        return (UserTransaction)obj;
    } catch (Exception e) {
      // Ignore and return null
    return null;

  private void joinEntityManagerTransaction() {
    EntityManager em = getEntityManager();
    if (em != null) {


Interceptors have to be registered, to do this you have to edit the beans.xml and add the Interceptor. Please setup to the correct package of what you use. is just for this example.
The complete beans.xml


To use the interceptor annotate with @UseTransaction any method that have some logic that needs transactions.
For example:

public void doFancyDbStuff(Entity entity) {

This will only work in CDI beans, other places won’t work (and this is not visible because the method is just executed without interceptor)

Have fun!

Wicket with Java EE 7

I’m currently working on a quite big Java EE project. Started on Java EE 6 I decided to switch to Java EE 7 when it was released. I got the question on Twitter how we used Wicket with Java EE 7. Long story short. We use CDI to glue all parts together of EE. To get Wicket working with Java EE is the wicket-cdi module the most important module.

I will show you here an example.

First download Glassfish 4 server.

Now we can create a project. We will use Wicket Quickstart archetype. Run the following command

mvn archetype:generate -DarchetypeGroupId=org.apache.wicket -DarchetypeArtifactId=wicket-archetype-quickstart -DarchetypeVersion=6.10.0 -DartifactId=wicket-javaee -DarchetypeRepository= -DinteractiveMode=false

After we created the project we can add wicket-cdi and Java EE 7 api dependencies. Add following block to dependencies in pom.xml


Add the wicket-cdi-1.1 dependency to the project to support CDI 1.1 which is used in Java EE 7, I’ve started this project, this project is a fork of wicket-cdi-1.1 in wicket, but I ported it to Wicket 6.x. I’m planning to change some parts to make it more lightweight again. I’ve found some issues if you’re using the beans (share a module (jar library) over different projects and deploy these web project to same Glassfish instance. I’m not sure if this is a Weld or Glassfish or wicket-cdi bug. I’m figuring it out.


I’ll post another blog post for some advanced features of the wicket-cdi-1.1 plugin.

To make the plugin work you have to change the web.xml, open src/main/resources/webapp/WEB-INF/web.xml. You have to change the filter class. Change




Now you can deploy to Glassfish 4. Any component (page, panel etc) will be injected by wicket-cdi-1.1. You can use the @Inject annotations. For objects that are constructed manually (like models etc) you have to put


in the constructor to make injection work.

From this CDI context (CDI beans) you can access other Java EE API’s like JMS easily.

I’m working on more parts of how to integrate Wicket in Java EE container.