Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

This page shows the basic steps required to create, build, and run an EJB and EJB client in its most minimum form. It does not hide steps or rely on special build tools or IDEs and is about the most stripped down you can get.

See the Examples page for a full list of examples that range from @Stateles and @Stateful beans, to Dependency Injection, JDBC DataSources, JPA EntityManagers and more.

A basic EJB example

...

Before starting

This example assumes you have already downloaded and installed OpenEJB in the directory c:\openejb. Refer to the Quickstart guide if you haven't yet installed OpenEJB.

We also assume that you are running your client from the directory c:\my\app.

The classes and interfaces

Create the package where we will place our ejb and application files, let's say "c:\my\app" for our example.

Windows

c:\my\app> mkdir org
c:\my\app> mkdir org\acme

Linux/Unix

user@host app# mkdir org
user@host app# mkdir org/acme

Create the files below in our new "c:\my\app\org\acme\" directory

Create the bean class

Here are some basic steps you need to perform to get started with OpenEJB

  1. Download and install OpenEJB
  2. Setup your development environment
  3. Write an EJB
  4. Write an EJB client
  5. Start the server
  6. Deploy the EJB
  7. Run the client
  8. Stop the server

Download and install OpenEJB

This example pertains to OpenEJB 3.0 which can be downloaded here. Once you have downloaded OpenEJB, you can then simply extract the contents of the downloaded file to whichever directory you want to install OpenEJB in.

After extracting the file contents, you should now see a directory named openejb-3.0. If you look under this directory, you will find a few more directories:

  • bin: Contains commands to start/stop the server (You can also do a lot of other stuff like deploy/undeploy, but we will just talk about things needed to get you started)
  • lib: Contains several jar files (you only need of few of these jars in your classpath to do EJB development)
  • apps: Once you create your EJB's and jar them up, you can place your jar file in this directory and start the server. The server will automatically deploy all the EJB's contained in this JAR.
  • conf: This directory contains all the configuration files. Although you may not see any file except for a README.txt file right now, but after you start the server, the required configuration files will be automatically created. It is highly recommeded to read the README.txt file under this directory
  • logs: Contains log files.

Setup your development environment

Create a working directory

Assuming you are in your home directory, create a directory named projects

Code Block

karan@poweredge:~$ mkdir projects

Go to the projects directory

Code Block

karan@poweredge:~$ cd projects

We will do all our work in this directory.

Install Java

Download and install Java (version 5 or higher). Also set it up so that you can run the java and javac commands from any directory

Set OPENEJB_HOME

We will setup this variable to refer to the openejb install location.

Code Block

karan@poweredge:~/projects$ export OPENEJB_HOME=/home/karan/install/openejb-3.0

Write an EJB

Whatever files you create should be placed under the projects directory

Create the Remote Interface

Using your favorite editor, create a file named Hello.java (shown below)

Code Block

package org.acme
Code Block
titleHelloBean.java

package org.acme;

import java.rmi.RemoteException;
import javax.ejb.*Remote;
@Remote
public class HelloBean implements SessionBean {
  private SessionContext sessionContext;
interface Hello{
        public voidString ejbCreatesayHello() {;
  }
  public void ejbRemove() {
  }
  public void ejbActivate() {
  }
  public void ejbPassivate() {
  }
  public void setSessionContext(SessionContext sessionContext) }

Create the Bean Class

Now create a file named HelloBean.java (shown below)

Code Block

package org.acme;
import javax.ejb.Stateless;
@Stateless
public class HelloBean implements Hello{
        public String sayHello(){
    this.sessionContext = sessionContext;
  }
  public String sayHello() throws java.rmi.RemoteException {
    return "Hello World!!!!!";
  }
}

Create the EJB Home interface

Code Block
titleHelloHome.java

package org.acme;

import java.rmi.*;
import javax.ejb.*;
import java.util.*;

public interface HelloHome extends EJBHome {
  public HelloObject create() throws RemoteException, CreateException;
}

Create the EJB Object interface

Code Block
titleHelloObject.java

package org.acme;

import java.rmi.*;
import javax.ejb.*;
import java.util.*;

public interface HelloObject extends EJBObject {
  public String sayHello() throws RemoteException;
}

The deployment descriptor

The deployment descriptor tells the EJB Container how to put together the classes above and run your component.
Fisrt, create a "META-INF" directory in the "c:\my\app" directory.

Windows

c:\my\app> mkdir META-INF

Linux/Unix

user@host app# mkdir META-INF

Now, create an ejb-jar.xml file in your META-INF directory.

...


<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar>
  <enterprise-beans>
    <session>
      <ejb-name>Hello</ejb-name>
      <home>org.acme.HelloHome</home>
      <remote>org.acme.HelloObject</remote>
      <ejb-class>org.acme.HelloBean</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
    </session>
  </enterprise-beans>
  <assembly-descriptor>
    <container-transaction>
      <method>
        <ejb-name>Hello</ejb-name>
        <method-name>*</method-name>
      </method>
      <trans-attribute>Required</trans-attribute>
    </container-transaction>
  </assembly-descriptor>
</ejb-jar>
 }
}

Compile the source code

Since we have imported the javax.ejb.Stateless and javax.ejb.Remote annotations, we need these in our classpath to compile our source code. These annotations can be found in the $OPENEJB_HOME/lib/javaee-5.0-1.jar.
Lets compile our source (make sure you are in the projects directory)

Code Block

karan@poweredge:~/projects$ javac -cp $OPENEJB_HOME/lib/javaee-5.0-1.jar -d . *.java

The above will compile all the .java files and also create the required packages. You should now see a package named org under the projects directory. All class files should be under org/acme directory.

Package the EJB

To package the EJB into a JAR, run the following command while you are in the projects directory

Code Block

karan@poweredge:~/projects$ jar cvf hello.jar org

The above command will package everything under the org directory (including the org directory itself) into a jar file named hello.jar. Below is the output from running the above command:

Code Block

karan@poweredge:~/projects$ jar cvf hello.jar org

Compile the EJB

Compile your bean.

Windows

c:\my\app> javac org\acme*.java

Linux/Unix

user@host app# javac org/acme/*.java

Make sure you don't make the mistake of trying to compile your classes while sitting inside the org/acme/ directory.

Warning

To compile an EJB, you need to have Sun's EJB library in your classpath. One has been included for you in the directory lib/ejb-1.0.jar

Package the EJB

Now, package your EJB classes and your META-INF directory into a jar.

Windows

C:\my\app> jar cvf myHelloEjb.jar org META-INF

Linux/Unix

user@host app# jar cvf myHelloEjb.jar org META-INF

That command should give you output like the following.

Code Block
added manifest
adding: org/(in = 0) (out= 0)(stored 0%)
adding: org/acme/(in = 0) (out= 0)(stored 0%)
adding: org/acme/HelloBeanHello.class(in = 946203) (out= 467168)(deflated 50%17%)
adding: org/acme/HelloObjectHelloBean.class(in = 234383) (out= 177275)(deflated 24%)
adding: org/acme/HelloHome.class(in = 263) (out= 188)(deflated 28%)
ignoring entry META-INF/
ignoring entry META-INF/MANIFEST.MF
adding: META-INF/ejb-jar.xml(in = 733) (out= 319)(deflated 56%)

Check to make sure at least the three classes are there and the ejb-jar.xml is there and that everything is in the directories you see above.

Deploy the EJB jar

Use the OpenEJB Deploy Tool to deploy your jar.

Windows

C:\my\app> cd C:\openejb

C:\openejb> openejb.bat deploy -a -m c:\my\app\myHelloEjb.jar

Linux/Unix

user@host app# cd /openejb

user@host openejb# ./openejb.sh deploy -a -m /my/app/myHelloEjb.jar

Warning

Since the OpenEJB deployment tool writes to your jar file, make sure that no other programs are using it when you deploy (i.e. if you use an editor such as Forte for Java to create the jar file, that editor may still be using it). If you get an error such as "Error in writing existing jar file" close any programs that may be using the jar and try deploying again.

A basic client application

Create a basic client application to access your HelloWorld bean.

28%)

Write an EJB Client

Now we will write a Client class which will lookup the EJB , invoke the sayHello() business method and print the value returned from the method.
While you are in the projects directory, create a new file named HelloClient.java . Add the following to this file:

HelloWorld.java
Code Block
Code Block
title
package org.acme;
import java.util.Properties;
import javax.rminaming.*InitialContext;
import javax.naming.*Context;
import javajavax.utilrmi.*PortableRemoteObject;

public class HelloWorld HelloClient{

        public static void main( String[] args[]) throws Exception{
        try{
    
    Properties pprops = new Properties();p
                props.put("java.naming.factory.initial", Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.client.RemoteInitialContextFactory");
        p        props.put("java.naming.provider.url", "Context.PROVIDER_URL,"ejbd://127.0.0.1:4201");
     p.put("java.naming.security.principal", "myuser");
      p.put("java.naming.security.credentials", "mypass");
    InitialContextContext ctx = new InitialContext( p props);

                Object objref = ctx.lookup("/HelloHelloBeanRemote");

            HelloHome ejbHome = (HelloHome)
 Hello h = (Hello)PortableRemoteObject.narrow(objref,HelloHomeHello.class);
      HelloObject    ejbObject = ejbHome.create();

    String messageresult = ejbObjecth.sayHello();
     System.out.println( message );
  } catch (Exception e){
    eSystem.out.printStackTraceprintln(result);
        }
 }
}

Compile HelloClient.java

Run the following command:JNDI properties for the Local Server would look like the following. Be sure to read the Local Server documentation if you run into any problems.

Code Block
Properties p = new Properties();

p.put("java.naming.factory.initial", 
    "org.openejb.client.LocalInitialContextFactory");
p.put("openejb.home", "c:\\openejb");
    
InitialContext ctx = new InitialContext(p);

JNDI properties for the Remote Server would look like the following. Be sure to start the Remote Server before running your application. See the Remote Server documentation for more information on using the Remote Server.

Code Block

Properties p = new Properties();
p.put("java.naming.factory.initial", "org.openejb.client.RemoteInitialContextFactory");
p.put("java.naming.provider.url", "127.0.0.1:4201");
p.put("java.naming.security.principal", "myuser");
p.put("java.naming.security.credentials", "mypass");
    
InitialContext ctx = new InitialContext(p);

Update the HelloWorld.java to contain the right JNDI properties.

Compile the application

Compile your client code. Don't forget to add your EJBs in the classpath!

Windows

C:\my\app> javac org\acme\HelloWorld.java

Linux/Unix

user@host app# javac org/acme/HelloWorld.java

Warning

To compile this application, you need to have Sun's JNDI library in your classpath. One has been included for you in the directory lib/jndi_1.2.1.jar

Run it!

When you run OpenEJB in embedded server mode, you need all the server libraries in your classpath along with your beans and client code. Here is a simple script that will add those classes automactically. Feel free to use this script, or add it's contents to you own scripts.

Example Windows Batch script.

Code Block
titleRunIt.bat

@echo off

set OPENEJB_HOME=C:\openejb
set PATH=%PATH%;%OPENEJB_HOME%\bin
set JAVA=%JAVA_HOME%\bin\java

set CP=
for %%i in (%OPENEJB_HOME%\lib\*.jar) do call cp.bat %%i 
for %%i in (%OPENEJB_HOME%\dist\*.jar) do call cp.bat %%i 
for %%i in (%OPENEJB_HOME%\beans\*.jar) do call cp.bat %%i 
set CLASSPATH=%JAVA_HOME%\lib\tools.jar;%CP%

%JAVA% %OPTIONS% -Dopenejb.home=%OPENEJB_HOME% org.acme.HelloWorld

Example Linux/Unix Batch script.

Code Block
titleRunIt.sh

#!/bin/sh

# Set OPENEJB_HOME to the full path where you 
# installed your OpenEJB distribution
export OPENEJB_HOME=/openejb

# Set JAVA_HOME to the full path where you 
# installed your JDK distribution
export JAVA_HOME=/usr/java/jdk1.3.1

export PATH=${PATH}:${OPENEJB_HOME}/bin
export JAVA=${JAVA_HOME}/bin/java

export CP=
CP=`echo $OPENEJB_HOME/lib/*.jar | tr ' ' ':'`:${CP}
CP=`echo $OPENEJB_HOME/dist/*.jar | tr ' ' ':'`:${CP}
CP=`echo $OPENEJB_HOME/beans/*.jar | tr ' ' ':'`:${CP}
export CLASSPATH=$JAVA_HOME/lib/tools.jar:${CP}

$JAVA -Dopenejb.home=$OPENEJB_HOME org.acme.HelloWorld

Now run the script!

Windows

C:\my\app> RunIt

Linux/Unix

user@host app# ./RunIt.sh

What if it didn't work

If you ran into any problems, first check your openejb.log file at c:\openejb\openejb.log. Look for any lines that begin with ** , ** , or ** .

karan@poweredge:~/projects$ javac  -d . HelloClient.java

Start the Server

Go to the OpenEJB install directory (i.e. OPENEJB_HOME) and run the following command:

Code Block

karan@poweredge:~/install/openejb-3.0$ bin/openejb start

Once the Server starts, you will see an output similar to the below in your console:

Code Block

karan@poweredge:~/install/openejb-3.0$ bin/openejb start
Apache OpenEJB 3.0    build: 20070926-12:34
http://openejb.apache.org/
OpenEJB ready.
[OPENEJB:init] OpenEJB Remote Server
  ** Starting Services **
  NAME                 IP              PORT  
  httpejbd             0.0.0.0         4204  
  telnet               0.0.0.0         4202  
  ejbd                 0.0.0.0         4201  
  hsql                 0.0.0.0         9001  
  admin thread         0.0.0.0         4200  
-------
Ready!

Take out a minute to browse through the conf and logs directories. You should now see some configuration and log files under the respective directories.

Deploy the EJB

We will now use the deploy command to deploy the EJB in hello.jar. While you are in the projects directory, run the following command:

Code Block

karan@poweredge:~/projects$ $OPENEJB_HOME/bin/openejb deploy hello.jar

The above command should give you the following output:

Code Block

karan@poweredge:~/projects$ $OPENEJB_HOME/bin/openejb deploy hello.jar
Application deployed successfully at "hello.jar"
App(id=/home/karan/projects/hello.jar)
    EjbJar(id=hello.jar, path=/home/karan/projects/hello.jar)
        Ejb(ejb-name=HelloBean, id=HelloBean)
            Jndi(name=HelloBeanRemote)

Notice how the output neatly lays out various deployment details. One thing you might want to note from the output is the JNDI name. This is the JNDI name we used in the client to lookup the EJB

Run the Client

While you are in the projects directory, run the following command to run the client:

Code Block

karan@poweredge:~/projects$ java -cp $OPENEJB_HOME/lib/openejb-client-3.0.jar:$OPENEJB_HOME/lib/javaee-5.0-1.jar:.  org.acme.HelloClient

The above should give you the following output:

Code Block

Hello World!!!!

Help! , it didn't work for me!!.

No problem, we are here to help. Just send us an email at users@openejb.apache.org. If possible, send us the contents of logs/openejb.log file in the email.

Looking for more?

More EJB 3.0 examples, sample applications, tutorials and howtos available hereIf the log file doesn't help you, email it to the OpenEJB user mailing list and let people know you are using the Hello World example.