Port of schuchert.wikispaces.com


EJB3_Tutorial_1_Getting_Started_with_JBoss_Embedded_Container

EJB3_Tutorial_1_Getting_Started_with_JBoss_Embedded_Container

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:

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


title: EJB3_Tutorial_1_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


title: EJB3_Tutorial_1_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


title: EJB3_Tutorial_1_Create_and_Configure —


title: Ejb3EclipseUserLibrarySetup —

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

  • Pull down Window:Preferences
  • Navigate to Java:Build Path:User Libraries
  • Click on New
  • 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:

  • Select EJB3_EMBEDDABLE
  • Click on Add JARs…
  • Navigate to C:/libs/jboss-EJB-3.0_Embeddable_ALPHA_9/lib/
  • Select all of the the jar files
  • 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 **** replace it with **Ejb3Tutorial1**.


title: Ejb3EclipseProjectSetupAndConfiguration —

Create the Project

  • Pull down the File menu and select new:project
  • Select Java Project
  • Click Next
  • Enter ****
  • Under Project Layout select create separate source and output folders
  • Click Finish
  • Select ****, right-click and select **new:Source Folder**
  • Enter conf for the name
  • Click on Finish
  • Select ****, right-click and select **new:Source Folder**
  • Enter test for the name
  • Click on Finish

Edit your project properties

Now that we have created a user library, we can add that user library to our project:

  • Select ****, and press alt-enter or right-click and select properties.
  • Select Java Build Path
  • Select the Libraries tab
  • Click on Add Library
  • Select User Library and click Next
  • Click on the box next to EJB3_EMBEDDABLE and click Finish
  • Click Add Library
  • Select JUnit and click Next
  • In the pull-down list, select JUnit 4 and click Finish
  • 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.

  • Select the conf folder under ****
  • Pull down the File menu and select Import
  • Expand General
  • Select File System and click on Next
  • Click on Browse and go to the following directory: C:/libs/jboss-EJB-3.0_Embeddable_ALPHA_9/conf
  • Click on OK
  • You’ll see conf in the left pane, select it
  • Verify that the Into folder: lists **/conf** (if not, just enter it or browse to it)
  • Click Finish
  • 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:

  • Select the conf folder
  • Pull down the File menu and select Import
  • Expand General
  • Select File System and click on Next
  • Click on Browse and go to the following directory: C:/libs/jboss-EJB-3.0_Embeddable_ALPHA_9/lib
  • Select jcainflow.rar and jms-ra.rar
  • 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.

  • Select the conf directory, right-click and select new then select File
  • Enter the name jndi.properties and click finish
  • Enter the following 2 lines then save and close the file:
<pre><code class="language-xml" data-lang="xml">java.naming.factory.initial=org.jnp.interfaces.LocalOnlyContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces</code></pre>

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.

  • Select your src directory
  • Right-click, select New:Folder
  • Enter META-INF
  • Click OK
  • Select META-INF
  • Right-lick, select New:File
  • Enter persistence.xml
  • Click Finish
  • Copy the following example into your new file then save it by pressing ctrl-s

persistence.xml

<pre><code class="language-xml" data-lang="xml"><span class="cp">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span> <span class="nt">&lt;persistence&gt;</span>    <span class="nt">&lt;persistence-unit</span> <span class="na">name=</span><span class="s">"custdb"</span><span class="nt">&gt;</span>
   
<span class="c">&lt;!-- This persistence unit uses the default data source that JBoss    --&gt;</span>
<span class="c">&lt;!-- defines called DefaultDS. If we wanted to use our own data       --&gt;</span>
<span class="c">&lt;!-- source, we'd need to define a custom data source somewhere.      --&gt;</span>
<span class="c">&lt;!-- That somewhere is vendor specific.                               --&gt;</span>

<span class="c">&lt;!-- In the case of JBoss, since we're using the embedded container,  --&gt;</span>
<span class="c">&lt;!-- we need to add two beans in a file called                        --&gt;</span>
<span class="c">&lt;!-- embedded-jboss-beans.xml. We name the first                      --&gt;</span>
<span class="c">&lt;!-- HypersonicLocalServerDSBootstrap and we name the second          --&gt;</span>
<span class="c">&lt;!-- HypersonicLocalServerDS. This two step process defines a data    --&gt;</span>
<span class="c">&lt;!-- source.                                                          --&gt;</span>

<span class="c">&lt;!-- In the first bean definition, we additionally bind it in Jndi    --&gt;</span>
<span class="c">&lt;!-- under some name. If we used the name                             --&gt;</span>
<span class="c">&lt;!-- java:/HypersonicLocalServerDS then we would use the following    --&gt;</span>
<span class="c">&lt;!-- entry to use that data source instead of the default one:        --&gt;</span>
<span class="c">&lt;!-- &lt;jta-data-source&gt;java:/HypersonicLocalServerDS&lt;/jta-data-source&gt; --&gt;</span>
 
  <span class="nt">&lt;jta-data-source&gt;</span>java:/DefaultDS<span class="nt">&lt;/jta-data-source&gt;</span>
  <span class="nt">&lt;properties&gt;</span>
     <span class="nt">&lt;property</span> <span class="na">name=</span><span class="s">"hibernate.hbm2ddl.auto"</span> <span class="na">value=</span><span class="s">"create-drop"</span><span class="nt">/&gt;</span>
  <span class="nt">&lt;/properties&gt;</span>    <span class="nt">&lt;/persistence-unit&gt;</span> <span class="nt">&lt;/persistence&gt;</span></code></pre>

Create a Local Stateless Session Bean


title: EJB3_Tutorial_1_Create_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,

  • select your src directory, right-click and select New:Interface.
  • For Name, enter HelloWorldService
  • For Package enter service
  • Click on Finish then enter the above code into the file
  • 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:

  • select your src directory, right-click and select New:Class
  • For Name, enter HelloWorldServiceImpl
  • For Package enter service.impl
  • Click on Finish then enter the above code into the file
  • Save your file (ctrl-s)

Container Initialization and Session Bean Lookup


title: EJB3_Tutorial_1_Initialization_and_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.


title: Ejb3JBossUtilJava —

JBossUtil.java

<pre><code class="language-java" data-lang="java"><span class="kn">package</span> <span class="nn">util</span><span class="o">;</span>

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. */</span> 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. */</span> 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. */</span> 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. */</span> public static void startDeployer() { if (!initialized) { redirectStreams();

       <span class="nc">EJB3StandaloneBootstrap</span><span class="o">.</span><span class="na">boot</span><span class="o">(</span><span class="kc">null</span><span class="o">);</span>
       <span class="nc">EJB3StandaloneBootstrap</span><span class="o">.</span><span class="na">scanClasspath</span><span class="o">();</span>
      
       <span class="n">initialized</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span>
      
       <span class="n">restoreStreams</span><span class="o">();</span>  <span class="o">}</span>  <span class="o">}</span>
      

    /**

    • 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. */</span> 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); } }

     <span class="k">return</span> <span class="n">ctx</span><span class="o">;</span>  <span class="o">}</span>
    

    /**

    • 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. */</span> @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)); }
     <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">NamingException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
         <span class="k">throw</span> <span class="k">new</span> <span class="nf">RuntimeException</span><span class="o">(</span><span class="nc">String</span><span class="o">.</span><span class="na">format</span><span class="o">(</span>
                 <span class="s">"Unable to find ejb for %s"</span><span class="o">,</span> <span class="n">clazz</span><span class="o">.</span><span class="na">getName</span><span class="o">()),</span> <span class="n">e</span><span class="o">);</span>
     <span class="o">}</span>  <span class="o">}</span> <span class="o">}</span></code></pre>
    

EqualsUtil.java

<pre><code class="language-java" data-lang="java"><span class="kn">package</span> <span class="nn">util</span><span class="o">;</span>

/**

  • We typically need to compare two object and also perform null checking. This
  • class provides a simple wrapper to accomplish doing so. */</span>

public class EqualsUtil { private EqualsUtil() { // I’m a utility class, do not instantiate me }

<span class="kd">public</span> <span class="kd">static</span> <span class="kt">boolean</span> <span class="nf">equals</span><span class="o">(</span><span class="kd">final</span> <span class="nc">Object</span> <span class="n">lhs</span><span class="o">,</span> <span class="kd">final</span> <span class="nc">Object</span> <span class="n">rhs</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">return</span> <span class="n">lhs</span> <span class="o">==</span> <span class="kc">null</span> <span class="o">&amp;&amp;</span> <span class="n">rhs</span> <span class="o">==</span> <span class="kc">null</span>
            <span class="o">||</span> <span class="o">(</span><span class="n">lhs</span> <span class="o">!=</span> <span class="kc">null</span> <span class="o">&amp;&amp;</span> <span class="n">rhs</span> <span class="o">!=</span> <span class="kc">null</span> <span class="o">&amp;&amp;</span> <span class="n">lhs</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="n">rhs</span><span class="o">));</span>

<span class="o">}</span> <span class="o">}</span></code></pre>

To create this file,

  • Select your src directory
  • Right-click and select New::Class
  • For Class Name enter JBossUtil
  • For Package enter util
  • Click Finish
  • 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:

  • Select your test source folder
  • Right-click, select New:Class
  • Enter HelloWorldServiceImplTest for the name
  • Enter ervice.impl for the package
  • Click Finish
  • Copy the text below into the file (replacing the entire contents)
  • 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


title: EJB3_Tutorial_1_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.


Comments

" Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.