Hello World! -- A basic EJB example

|  |  |  | OpenEJB OpenJMS OpenORB Castor Tyrex |

Main
Welcome!
Download
Mailing Lists
The Team

Users
Quickstart
Hello World!
CMP Example
CMP Guide
Deploy
Startup
Validation
Configuration
Support
Request Feature
FAQ

Servers
Local Server
Remote Server
Tomcat

Integrators
Why OpenEJB
Overview
Design
Specification
Presentation

Developers
Custom Services
Release Plan
Source Code
SourceForge

Hello World! 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.

## Create the bean class

First, create the package where we will place our ejb and application files.

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

In your favorite editor, create the file below.

c:\my\app\org\acme\HelloBean.java

    package org.acme;

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

    public class HelloBean implements SessionBean {
      private SessionContext sessionContext;
      public void ejbCreate() {
      }
      public void ejbRemove() {
      }
      public void ejbActivate() {
      }
      public void ejbPassivate() {
      }
      public void setSessionContext(SessionContext sessionContext) {
        this.sessionContext = sessionContext;
      }
      public String sayHello() throws java.rmi.RemoteException {
        return "Hello World!!!!!";
      }
    }

## Create the EJB Home interface

c:\my\app\org\acme\HelloHome.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

c:\my\app\org\acme\HelloObject.java

    package org.acme;

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

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

## Create the ejb-jar.xml

Create a META-INF directory to put your ejb-jar.xml into.

Windows

c:\my\app> mkdir META-INF

Linux/Unix

[user@host app]# mkdir META-INF

Create am ejb-jar.xml file in your META-INF directory.

c:\my\app\META-INF\ejb-jar.xml

    <?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 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.

NOTE

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.

    added manifest
    adding: org/(in = 0) (out= 0)(stored 0%)
    adding: org/acme/(in = 0) (out= 0)(stored 0%)
    adding: org/acme/HelloBean.class(in = 946) (out= 467)(deflated 50%)
    adding: org/acme/HelloObject.class(in = 234) (out= 177)(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

NOTE

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.

c:\my\app\org\acme\HelloWorld.java

    package org.acme;

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

    public class HelloWorld {

     public static void main( String args[]) {
      try{

        Properties p = new Properties();

        //The JNDI properties you set depend
        //on which server you are using.
        //These properties are for the Remote Server.
        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");

        //Now use those properties to create
        //a JNDI InitialContext with the server.
        InitialContext ctx = new InitialContext( p );

        //Lookup the bean using it's deployment id
        Object obj = ctx.lookup("/Hello");

        //Be good and use RMI remote object narrowing
        //as required by the EJB specification.
        HelloHome ejbHome = (HelloHome)
            PortableRemoteObject.narrow(obj,HelloHome.class);

        //Use the HelloHome to create a HelloObject
        HelloObject ejbObject = ejbHome.create();

        //The part we've all been wainting for...
        String message = ejbObject.sayHello();

        //A drum roll please.
        System.out.println( message );

      } catch (Exception e){
        e.printStackTrace();
      }
     }
    }

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.

    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.

    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

NOTE

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.

c:\my\app\RunIt.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.

/my/app/RunIt.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 "WARN", "ERROR", or "FATAL".

If 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.

Java, EJB, JDBC, JNDI, JTA, Sun, Sun Microsystems are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and in other countries. XML, XML Schema, XSLT and related standards are trademarks or registered trademarks of MIT, INRIA, Keio or others, and a product of the World Wide Web Consortium. All other product names mentioned herein are trademarks of their respective owners.