<--Back

Getting Started with the JBoss Embedded Container


This tutorial is a derivative (simplification really) of work done by JBoss. For the original material, look here. This tutorial's goals are:
  • Download and install the JBoss Embeddable EJB3 Container
  • Create and configure an Eclipse project to be able to use the container
  • Create a simple "hello world" style local stateless session bean
  • Look up that local stateless session bean and use it

Most of this tutorial is about configuration and utility methods. We will use those items for the remainder of the tutorials using the Embeddable EJB3 Container.

Background

A Session Bean provides an interface to a service, wraps business logic or might simply act to hide the details of using JPA. The design pattern that comes to mind is facade.

Creating a Session Bean using EJB3 is comparatively painless compared to previous versions of the EJB specification. In the simplest configuration, a session bean only needs to implement an interface and then be denoted as a session bean with meta-information. EJB3 uses configuration by exception to keep the requirements to a minimum.

EJB meta-information comes in two forms: Annotations or XML files. As with JPA, XML files take precedence over annotations. These tutorials use annotations.

Download and Install

This tutorial assumes you already have Eclipse 3.2 and a Java 5 JDK installed. If not, please review this.

Download

Download the JBoss EJB3 Embeddable Container from here. The version used for this tutorial is jboss-EJB-3.0_Embeddable_ALPHA_9.zip.

Install

Extract this zip file anywhere, for this tutorial I used C:\libs, which makes the following directory: C:\libs\jboss-EJB-3.0_Embeddable_ALPHA_9

You'll find the following directories under the install directory:
  • conf
  • docs
  • lib

We'll be using the files from conf and lib.

Create and Configure the Eclipse Project

Define User Library

We need to add several jar files to the class path. We created a user library in these steps and we're going to do the same thing with a different set of jar files.

Create User Library
  1. Pull down Window:Preferences
  2. Navigate to Java:Build Path:User Libraries
  3. Click on New
  4. Enter EJB3_EMBEDDABLE for the name and click on OK

Add Jars to User Library
Now we need to add all of the jar files from the lib directory under the JBoss Embeddable container directory we unzipped earlier:
  1. Select EJB3_EMBEDDABLE
  2. Click on Add JARs...
  3. Navigate to C:/libs/jboss-EJB-3.0_Embeddable_ALPHA_9/lib/
  4. Select all of the the jar files
  5. Click on Open

You need to add all of the jar files from the lib directory under the JBoss Embeddable container directory. If you used the same directory as the tutorial, then you need add all of the jar files from C:/libs/jboss-EJB-3.0_Embeddable_ALPHA_9/lib/ (there are 5). Here is the complete list of jar files:
  • C:/libs/jboss-EJB-3.0_Embeddable_ALPHA_9/lib/thirdparth-all.jar
  • C:/libs/jboss-EJB-3.0_Embeddable_ALPHA_9/lib/hibernate-all.jar
  • C:/libs/jboss-EJB-3.0_Embeddable_ALPHA_9/lib/jboss-ejb3-all.jar
  • C:/libs/jboss-EJB-3.0_Embeddable_ALPHA_9/lib/jcainflow.jar
  • C:/libs/jboss-EJB-3.0_Embeddable_ALPHA_9/lib/jms-ra.jar

Create and Setup Project

For the rests of this tutorial, when you see <project> replace it with Ejb3Tutorial1.

Create the Project

  1. Pull down the File menu and select new:project
  2. Select Java Project
  3. Click Next
  4. Enter <project>
  5. Under Project Layout select create separate source and output folders
  6. Click Finish
  7. Select <project>, right-click and select new:Source Folder
  8. Enter conf for the name
  9. Click on Finish
  10. Select <project>, right-click and select new:Source Folder
  11. Enter test for the name
  12. Click on Finish

Edit your project properties

Now that we have created a user library, we can add that user library to our project:
  1. Select <project>, and press alt-enter or right-click and select properties.
  2. Select Java Build Path
  3. Select the Libraries tab
  4. Click on Add Library
  5. Select User Library and click Next
  6. Click on the box next to EJB3_EMBEDDABLE and click Finish
  7. Click Add Library
  8. Select JUnit and click Next
  9. In the pull-down list, select JUnit 4 and click Finish
  10. Click on OK to make the change to your project's classpath

Setup the configuration files

The JBoss Embeddable container looks for several files in the classpath. To keep all of these in one place, we'll add another source directory to our project and then import several files into that directory.
  1. Select the conf folder under <project>
  2. Pull down the File menu and select Import
  3. Expand General
  4. Select File System and click on Next
  5. Click on Browse and go to the following directory: C:/libs/jboss-EJB-3.0_Embeddable_ALPHA_9/conf
  6. Click on OK
  7. You'll see conf in the left pane, select it
  8. Verify that the Into folder: lists <project>/conf (if not, just enter it or browse to it)
  9. Click Finish
  10. Expand the conf directory and verify that the files are now there

Add Resource Adapter Archive(RAR)

The Java Connector system defines Resource Adapter Archive files (RAR files). We need to add a few RAR files into the class path. We will import two more files into the conf directory:
  1. Select the conf folder
  2. Pull down the File menu and select Import
  3. Expand General
  4. Select File System and click on Next
  5. Click on Browse and go to the following directory: C:/libs/jboss-EJB-3.0_Embeddable_ALPHA_9/lib
  6. Select jcainflow.rar and jms-ra.rar
  7. Click Finish

Create a jndi.properties file

Note, depending on the version of the embeddable container you download, you might already have a file called jndi.properties. If you do, skip to the next section.
  1. Select the conf directory, right-click and select new then select File
  2. Enter the name jndi.properties and click finish
  3. Enter the following 2 lines then save and close the file:
java.naming.factory.initial=org.jnp.interfaces.LocalOnlyContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces

Create a persistence.xml

This example presents a utility class we'll be using later. The container needs a persistence.xml file to operate. This file must be found under a META-INF directory somewhere in the classpath or the embeddable container will not start. The file's name is persistence.xml with a lower-case 'p'. On a Unix system, this will make a difference. On a PC, this won't make a difference and it is one of those things that might work on your machine but not on the linux build box.

  1. Select your src directory
  2. Right-click, select New:Folder
  3. Enter META-INF
  4. Click OK
  5. Select META-INF
  6. Right-lick, select New:File
  7. Enter persistence.xml
  8. Click Finish
  9. Copy the following example into your new file then save it by pressing ctrl-s

persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence>
   <persistence-unit name="custdb">
 
    <!-- This persistence unit uses the default data source that JBoss    -->
    <!-- defines called DefaultDS. If we wanted to use our own data       -->
    <!-- source, we'd need to define a custom data source somewhere.      -->
    <!-- That somewhere is vendor specific.                               -->
 
    <!-- In the case of JBoss, since we're using the embedded container,  -->
    <!-- we need to add two beans in a file called                        -->
    <!-- embedded-jboss-beans.xml. We name the first                      -->
    <!-- HypersonicLocalServerDSBootstrap and we name the second          -->
    <!-- HypersonicLocalServerDS. This two step process defines a data    -->
    <!-- source.                                                          -->
 
    <!-- In the first bean definition, we additionally bind it in Jndi    -->
    <!-- under some name. If we used the name                             -->
    <!-- java:/HypersonicLocalServerDS then we would use the following    -->
    <!-- entry to use that data source instead of the default one:        -->
    <!-- <jta-data-source>java:/HypersonicLocalServerDS</jta-data-source> -->
 
      <jta-data-source>java:/DefaultDS</jta-data-source>
      <properties>
         <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
      </properties>
   </persistence-unit>
</persistence>


Create a Local Stateless Session Bean

Now that we have all the preliminary setup of the environment we next need to create a session bean.

The Session Bean

The basic requirement for a session bean is that it must implement an interface and be either annotated with @Stateless or be registered in an XML file. We are sticking strictly to using annotations. The annotation goes on the class and not the interface, so here's the interface.

The Interface
First we create a session bean. Here is one such example:
package service;
 
/**
 * A requirement for EJB3 Session beans is that they implement an interface.
 * This interface does not specify whether it is local or remote so we won't
 * know until it is used which way to treat it. One convention is to include the
 * name "Local" or "Remote" in the name of the service.
 */
public interface HelloWorldService {
    void sayHelloTo(final String name);
}

To create this file,
  1. select your src directory, right-click and select New:Interface.
  2. For Name, enter HelloWorldService
  3. For Package enter service
  4. Click on Finish then enter the above code into the file
  5. Save your file (ctrl-s)

The Session Bean
Next, we need to create a session bean. Here's the code for it:
package service.impl;
 
import javax.ejb.Stateless;
 
import service.HelloWorldService;
 
/**
 * I'm a stateless session because of the -at- Stateless annotation. I only
 * implement one interface and that interface does not explicitly declare itself
 * to be either -at- Local or -at- Remote. Therefore, I am a Stateless session
 * bean with a local interface.
 */
@Stateless
public class HelloWorldServiceImpl implements HelloWorldService {
 
    public void sayHelloTo(final String name) {
        System.out.printf("Hello to %s\n", name);
    }
 
}

Notice that this class has the @Stateless annotation. The container will find this class and register it automatically under JNDI using the (non-package qualifited) class name plus "/local". In this example, that means we'll need to lookup "HelloWorldServiceImpl/local".

This class is obviously stateless because of the annotation. This is the default behavior. However, using the annotation will get it automatically available from JNDI. (We could put this information in an XML file and get the same results.)

This class is also local. By default, session beans are local (no RMI-IIOP to call them) unless:
  • They implement more that one interface (ignoring common interfaces like Serializable and Comparable).
  • There is a @Remote annotation

If you still want a local session bean where there is more than one interface, you can use @Local.

To create this file:
  1. select your src directory, right-click and select New:Class
  2. For Name, enter HelloWorldServiceImpl
  3. For Package enter service.impl
  4. Click on Finish then enter the above code into the file
  5. Save your file (ctrl-s)


Container Initialization and Session Bean Lookup

There's a bit of boilerplate code to get the JBoss EJB3 Embeddable Container initialized before we can look up our session bean. For now we'll just use this code so we won't describe it in any detail here.

By the way, I recommend you cut and past this code rather than type it.

JBossUtil.java


package util;
 
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.logging.Logger;
 
import javax.naming.InitialContext;
import javax.naming.NamingException;
 
import org.jboss.ejb3.embedded.EJB3StandaloneBootstrap;
 
/**
 * This class was originally necessary when using the ALPHA 5 version of the
 * embeddable container. With the alpha 9 release, initialization is quite
 * simple, you need just 2 lines to initialize your JBoss Embeddable EJB3
 * Container Environment. Unfortunately, the one that is available for download
 * uses System.out.println() in a few places, so this simple utility hides that
 * output and also provides a simple lookup mechanism.
 */
public class JBossUtil {
    private static PrintStream originalOut;
 
    private static PrintStream originalErr;
 
    private static OutputStream testOutputStream;
 
    private static PrintStream testOuputPrintStream;
 
    static boolean initialized;
 
    static InitialContext ctx;
 
    private JBossUtil() {
        // I'm a utility class, do not instantiate me
    }
 
    /**
     * JBoss EJB3 Embeddable Container uses System.out. Redirect that output to
     * keep the console output clean.
     */
    private static void redirectStreams() {
        // configure the console to get rid of hard-coded System.out's in
        // the JBoss libraries
        testOutputStream = new ByteArrayOutputStream(2048);
        testOuputPrintStream = new PrintStream(testOutputStream);
 
        originalOut = System.out;
        originalErr = System.err;
 
        System.setOut(testOuputPrintStream);
        System.setErr(testOuputPrintStream);
    }
 
    /**
     * Restore the System.out and System.err streams to their original state.
     * Close the temporary stream created for the purpose of redirecting I/O
     * while the initializing is going on.
     */
    private static void restoreStreams() {
        System.setOut(originalOut);
        System.setErr(originalErr);
        testOuputPrintStream.close();
        try {
            testOutputStream.close();
        } catch (IOException e) {
            Logger.getLogger(JBossUtil.class.getName()).info(
                    "Unable to close testoutstream");
        }
    }
 
    /**
     * This method starts and initializes the embeddable container. We do not
     * offer a method to properly clean up the container since this is really
     * meant for testing only.
     * 
     * This method may freely be called as often as you'd like since it lazily
     * initializes the container only once.
     */
    public static void startDeployer() {
        if (!initialized) {
            redirectStreams();
 
            EJB3StandaloneBootstrap.boot(null);
            EJB3StandaloneBootstrap.scanClasspath();
 
            initialized = true;
 
            restoreStreams();
        }
    }
 
    /**
     * This is for symmetry. Given how we are using this class, there's little
     * need to actually shutdown the container since we run a quick application
     * and then stop the JVM.
     */
    public static void shutdownDeployer() {
        EJB3StandaloneBootstrap.shutdown();
    }
 
    private static InitialContext getContext() {
        /**
         * We only keep one context around, so lazily initialize it
         */
        if (ctx == null) {
            try {
                ctx = new InitialContext();
            } catch (NamingException e) {
                throw new RuntimeException("Unable to get initial context", e);
            }
        }
 
        return ctx;
    }
 
    /**
     * The lookup method on InitialContext returns Object. This simple wrapper
     * asks first for the expected type and the for the name to find. It gets
     * the name out of JNDI and performs a simple type-check. It then casts to
     * the type provided as the first parameter.
     * 
     * This isn't strictly correct since the cast uses the expression (T), where
     * T is the generic parameter and the type is erased at run-time. However,
     * since we first perform a type check, we know this cast is safe. The -at-
     * SuppressWarnings lets the Java Compiler know that we think we know what
     * we are doing.
     * 
     * @param <T>
     *            Type type provided as the first parameter
     * @param clazz
     *            The type to cast to upon return
     * @param name
     *            The name to find in Jndi, e.g. XxxDao/local or, XxxDao/Remote
     * @return Something out of Jndi cast to the type provided as the first
     *         parameter.
     */
    @SuppressWarnings("unchecked")
    public static <T> T lookup(Class<T> clazz, String name) {
        final InitialContext ctx = getContext();
        /**
         * Perform the lookup, verify that it is type-compatible with clazz and
         * cast the return type (using the erased type because that's all we
         * have) so the client does not need to perform the cast.
         */
        try {
            final Object object = ctx.lookup(name);
            if (clazz.isAssignableFrom(object.getClass())) {
                return (T) object;
            } else {
                throw new RuntimeException(String.format(
                        "Class found: %s cannot be assigned to type: %s",
                        object.getClass(), clazz));
            }
 
        } catch (NamingException e) {
            throw new RuntimeException(String.format(
                    "Unable to find ejb for %s", clazz.getName()), e);
        }
    }
}

EqualsUtil.java
package util;
 
/**
 * We typically need to compare two object and also perform null checking. This
 * class provides a simple wrapper to accomplish doing so.
 */
 
public class EqualsUtil {
    private EqualsUtil() {
        // I'm a utility class, do not instantiate me
    }
 
    public static boolean equals(final Object lhs, final Object rhs) {
        return lhs == null && rhs == null
                || (lhs != null && rhs != null && lhs.equals(rhs));
 
    }
}


To create this file,
  1. Select your src directory
  2. Right-click and select New::Class
  3. For Class Name enter JBossUtil
  4. For Package enter util
  5. Click Finish
  6. Type or copy the code from above into the new file then save it by pressing ctrl-s

Using JUnit

Now we need to enter basic system setup and then execute a test. The following unit test performs basic setup and initialization, looks up a session bean and sends it a message.

To create this test:
  1. Select your test source folder
  2. Right-click, select New:Class
  3. Enter HelloWorldServiceImplTest for the name
  4. Enter ervice.impl for the package
  5. Click Finish
  6. Copy the text below into the file (replacing the entire contents)
  7. Save the file
package service.impl;
 
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
 
import service.HelloWorldService;
import util.JBossUtil;
 
public class HelloWorldServiceImplTest {
    private HelloWorldService service;
 
    @BeforeClass
    public static void startDeployer() {
        // Note, we could stop the deployer when we are done but we do not since
        // the JVM will shut down and stop the deployer for us.
        JBossUtil.startDeployer();
    }
 
    @Before
    public void lookupService() {
        service = JBossUtil.lookup(HelloWorldService.class,
                "HelloWorldServiceImpl/local");
    }
 
    @Test
    public void sayHello() {
        service.sayHelloTo("Brett");
    }
}

Execute your "Unit Test"

Run this JUnit "test" and make sure it runs successfully. (Right-click on the class, select Run As:JUnit Test.

You will see the following output:
Hello to Brett

Note that this example produces output to the console. This example service is not really very testable. How might you "fix" this?

Nice

Congratulations, you've created your first EJB3 Session bean and executed it.

Exercises

Track Usage
Add support in your service implementation class to track the number of times the service has been used. Add two support methods to get the count of the number of times the service has been used and a second method to reset the count back to zero.

Keep a Historical Record
Remember the names of all the people your service has tracked avoiding duplicates. Add two methods to your service: one to report all the names your service has printed, one to clear the list of names.

Note, you'll either want to use synchronized for this assignment or better yet, look at the package java.util.concurrent and pay attention to the class CopyOnWriteArraySet.

Advanced
Update your service to keep track of the number of times each name has been used. You might want to have a look at the class java.util.concurrent.ConcurrentHashmap.

<--Back