Monday, January 31, 2011

A simple EJB 3 application hand made


This is a simple EJB 3 app that is written, deployed and run from command line and vim, with no IDE, no ant, no maven, no admin console. The target appserver is glassfish.

1. project directory structure:

C:\simple-ejb3> tree /A /F
+---classes
|   \---foo
\---src
    \---foo
           Client.java
           FooBean.java
           FooRemote.java
2. create java src files under src\foo:
package foo;
import javax.ejb.*;

@Remote
public interface FooRemote {
public String echo(String s);
}
------------
package foo;
import javax.ejb.*;

@Stateless
public class FooBean implements FooRemote {
public String echo(String s) {
  return s;
}
}
------------
package foo;
import javax.ejb.*;
import javax.naming.*;

public class Client {
public static void main(String[] args) throws Exception {
  Context ic = new InitialContext();
  Object obj = ic.lookup(FooRemote.class.getName());
  System.out.println("lookup returned " + obj);

  FooRemote foo = (FooRemote) obj;
  String input = (args.length > 0) ? args[0] :
              "No application arg specified.";
  String s = foo.echo(input);
  System.out.println("foo.echo returned " + s);
}
}
3. Compile java src. An environment variable JAVAEE_HOME is set for convenience but it's not required.

C:\simple-ejb3\classes> set JAVAEE_HOME=C:\glassfish
C:\simple-ejb3\classes> javac -d . -classpath %JAVAEE_HOME%\lib\javaee.jar;. ..\src\foo\*.java

4. start the appserver:
C:\simple-ejb3\classes> %JAVAEE_HOME%\bin\asadmin.bat start-domain

5. package and autodeploy ejb-jar. We can combine the 2 steps in 1 by using %JAVAEE_HOME%\domains\domain1\autodeploy as the destdir:
C:\simple-ejb3\classes> jar cvf %JAVAEE_HOME%\domains\domain1\autodeploy\foo-ejb.jar foo\FooBean.class foo\FooRemote.class

6. run the standalone java client:
C:\simple-ejb3\classes> java -cp %JAVAEE_HOME%\lib\javaee.jar;%JAVAEE_HOME%\lib\appserv-rt.jar;. foo.Client lookup returned foo._FooRemote_Wrapper@e9738564
foo.echo returned No application arg specified.

7. undeploy the ejb module:
del %JAVAEE_HOME%\domains\domain1\autodeploy\*.jar

No comments:

Post a Comment