This is the second part of the blog I wrote about EJB2.0 with OpenEJB. In the first part, we created a stateless session bean and deployed it in OpenEJB. In this part, we write and test a simple Java class that remotely uses the deployed session bean.
The link to the first part: EJB2.0 with OpenEJB: Stateless Session Bean in Action
One of the cardinal rules in writing EJB2.0 clients is to always include the interface types in the client project. The image below shows the EJB bean and client projects. Notice that the client project also has the same interfaces as the EJB project (ejb2test). To successfully build and run the client application, the two jar files are needed to be in the classpath:
- javaee-api-5.0-3.jar
- openejb-client-3.1.4.jar.
EJB2.0 bean and client projects
The client class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import java.util.Properties; import javax.naming.InitialContext; import javax.rmi.PortableRemoteObject; import com.ejb2.Advice; import com.ejb2.AdviceHome; public class Ejb2TestClient { public static void main(String... a) throws Exception { Properties p = new Properties(); p.put("java.naming.factory.initial", "org.apache.openejb.client.RemoteInitialContextFactory"); p.put("java.naming.provider.url", "ejbd://192.168.1.2:4201"); InitialContext ctx = new InitialContext(p); Object ref = ctx.lookup("AdviceBeanRemoteHome"); AdviceHome home = (AdviceHome) PortableRemoteObject.narrow(ref, AdviceHome.class); Advice remote = home.create(); System.out.print(remote.getAdvice()); } } |
Notice a JNDI name “AdviceBeanRemoteHome” is used instead of “AdviceBean.” This is an OpenEJB EJB-JNDI naming convention. The EJB server appended “RemoteHome” to our original EJB name during start-up.
After building the client project, copy the classes and jar files to a remote machine (or virtual machine).
Client app in Ubuntu
Then, open a terminal from which the execute the client application.