Sunday, January 31, 2016

Setup for a simple EJB demo on Glassfish 4

I reviewed recently a very good serie of tutorials on JavaEE on the Coreservlet site. Though they all are excellent, they are a bit outdated, and I had to try a bit to get the simple example running.

I took the EJB 3 and Web Services tutorial, which describes setup for JBoss 5 and Glassfish. Using Eclipse Mars, I had no trouble to get the EJB - project deployed on Glassfish, and the Web client accessing this EJB.

The standalone client was missing a library, so I kept getting  javax.naming.NamingException: Lookup failed Exceptions when trying to access the remote service.

I searche the correct jndi configuration, but everything looked ok.

Finally, I found in this post in the Glassfish doc something that rang a bell: client libraries : my setup did not include the client libraries for Glassfish, so I added gf-client-module.jar from the Glassfish Libraries (under %GLASSFISH_HOME%/modules). Everything ran like a breeze.

My setup in short:

My client program consist of a single java file, where an initial context is initialized with a jndi.properties in the classpath (under ../src ).

java code for the context and service access:

...  
InitialContext context = new InitialContext();
  NumberService service = (NumberService)context.lookup("NumberCreator"); 
...

Content of jdni.properties:

java.naming.factory.initial=com.sun.enterprise.naming.SerialInitContextFactory
java.naming.factory.url.pkgs=com.sun.enterprise.naming
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl
org.omg.CORBA.ORBInitialHost=localhost
org.omg.CORBA.ORBInitialPort=3700

 Beware that jndi.properties is specific to the server flavor: it is not the same for accessing a service on a JBoss server.

Of course, the service remote interfaces must also be accessible to the client program. Here is an example of one such interface:


package coreservlets.bean;

import javax.ejb.*;

@Remote
public interface NumberService {
  public double getNumber(double range);

}