Tuesday, August 14, 2007

EJB : Running a command line client to a JBoss EJB

The EJB example running on JBoss is taken from the WTP (Web Tools Project) tutorials here plus XDoclet - all inside Eclipse.

Call the package ejbs.

We have an EJBTestBean:


/**
*
*
* @ejb.interface-method view-type="remote"
*
* @generated
*
* //TODO: Must provide implementation for bean method stub
*/
public String greet(String param) {
return "Hi dude " + param;
}


XDoclet creates all the Home and Util stubs.

Now we want to test this from a Java command line client.

So we create a Java class with a main() method (called CLTestClient):


try
{
EJBTestHome home = ejbs.EJBTestUtil.getHome();
EJBTest service = home.create();
String result = service.greet("Tom");
System.out.println();
System.out.println("Result is " + result);
}

catch (Exception e)
{
System.out.println();
System.out.println("Exception " + e.getMessage());
}


and we want to test from the command line:

java CLTestClient

and we get ClassNotDefined all over the place.

So we add the EJB files to the CLASSPATH:

set CLASSPATH=C:\JBoss-4.0.5.GA\
server\default\lib\jboss-j2ee.jar;C:\your path\EJBTestClient\build\classes;C:\your path\EJBTestClient\build\classes\ejbs;%CLASSPATH%

Then we get this error:

Need to specify class name in environment or system property, or as an
applet parameter, or in an application resource file: java.naming.factory.initial


The solution is to add a path to the jndi.properties file:

set CLASSPATH=C:\JBoss-4.0.5.GA\server\default\conf;%CLASSPATH%

More ClassNotDefined errors:

set CLASSPATH=C:\JBoss-4.0.5.GA\client\jbossall-client.jar;C:\JBoss-4.0.5.GA\lib\jboss-common.jar;C:\JBoss-4.0.5.GA\server\default\lib\jboss.jar;C:\JBoss-4.0.5.GA\client\jnp-client.jar;C:\JBoss-4.0.5.GA\client\jboss-client.jar;%CLASSPATH%

and finally:

java CLTestClient

returns:

Result is Hi dude Tom

By the way, if you wanted to do this from a browser inside a jsp page:


LT%@page import="ejbs.EJBTestUtil"%GT
LThtmlGT
LTheadGT
LTtitleGTEJBWebTestLT/titleGT
LT/headGT
LTbodyGT
LT%
ejbs.EJBTest tb = null;

try
{
ejbs.EJBTestHome home = EJBTestUtil.getHome();
tb = home.create();
}

catch(Exception exception)
{

}

%GT

LTbGTLT%= tb.greet("Tom") %GTLT/bGT

LT/bodyGT
LT/htmlGT




Where LT = "less than" and GT = "greater than".

Enjoy!

No comments: