Thursday, December 17, 2009

Access a Remote EJB From a Stand-Alone Client

Here, I will explain how you can access an EJB from outside a j2ee container or server. This could be a simple java-main application, or a unit test. The basic idea behind this process is application server agnostic, but these specific instructions will target Glassfish v2.1.

The Basics

In general, you always gain access to a jndi tree via the javax.naming.InitialContext. The no-arg constructor will by default look for a file on the classpath called 'jndi.properties'. This file specifies an application server-specific InitialContextFactory class, used to initialize the tree. You can also specify options such as the host and port to connect to.

The appserv-rt.jar that ships with glassfish contains a default jndi.properties file with the basic options already configured for you.

Ok, lets actually do something...

Assuming you have an EJB with a @Remote interface running on glassfish on localhost. The registered name in jndi for this ejb is 'my-ear/MyEjb/remote'. Create a new empty maven project. Add the following dependencies to your pom:
(I would recommend using my repository as Sun doesn't provide all the necessary dependencies for this in the core maven repositories.)


com.sun
appserv-rt
2.1


Now create a new class with a 'main' method. Here's an example:
public static void main(String[] args) throws Exception
{
InitialContext ctx = new InitialContext();
MyRemoteInterface service = (MyRemoteInterface)ctx.lookup("my-ear/MyEjb/remote");

Object result = service.getResult("john");

System.out.println(result);
}

You will also need to include MyRemoteInterface into your new project if you haven't already done so. Ok, thats it! Run your application and you should see the result object printed to your console.

Now, lets assume you want to connect to Glassfish on a server other than localhost

Create a new file called 'jndi.properties' and put it in your 'src/main/resources' directory. Add the following to this file:

org.omg.CORBA.ORBInitialHost=myhostname


We've just overriden the default host (provided by sun's jndi.properties') with a host of our own choosing. If you wanted to change the port to connect to:

org.omg.CORBA.ORBInitialHost=myhostname
org.omg.CORBA.ORBInitialPort=3700


Well, that's about it for now.

No comments:

Post a Comment