Nov 20, 2011

EJB3 RMI-IIOP in JSF

Technologies used:
  • EJB 3.0
  • JSF 1.2
  • Tomcat 6.0
  • WebSphere 7.0.0.17

Considering that you have an EJB 3.0 project deployed on a WebSphere application server and you need to access it from a JSF 1.2 web application deployed on a Tomcat server, you will need to use the Remote Method Invocation (RMI) over Internet Inter-ORB Protocol (IIOP).

In order to accomplish this task, first, you will need to create a new InitialContext (in your JSF beans or in an utility singleton class):

try {
Hashtable<String,String> appContext = new Hashtable<String,String>();   
appContext.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.ibm.websphere.naming.WsnInitialContextFactory");
appContext.put(javax.naming.Context.PROVIDER_URL, "iiop://localhost:2809");
InitialContext ctx = new InitialContext(appContext);
} catch(NamingException e) {
 // your logic for handling the exception
}

Next would be to actually lookup for the desired EJB Interface:

Object ejbInterface = ctx.lookup(YourRemoteEJBInterface.class.getName());
YourRemoteEJBInterface yourRemoteEJBInterface = (YourRemoteEJBInterface)javax.rmi.PortableRemoteObject.narrow(ejbInterface, YourRemoteEJBInterface.class);

At this point you will be able to access any of your EJB remote interface's business methods.

In order not to get the following kind of errors:
  • java.lang.ClassCastException: org.omg.stub.java.rmi._Remote_Stub cannot be cast to yourpackage.YourRemoteEJBInterface
  • java.lang.ClassCastException: yourpackage._YourRemoteEJBInterface_Stub cannot be cast to yourpackage.YourRemoteEJBInterface
you must generate and include the stub classes for the remote interfaces in your "ejb-client.jar" (considering that this jar contains your EJB interfaces and it's a dependency for your JSF web application).

For this particular example you can create the stubs and inject them in to the "ejb-client.jar" with the WebSphere's createEJBStubs utility, located in the /bin folder, like this:

%WAS_HOME%/bin/createEJBStubs yourEJB.ear -updatefile ejb-client.jar

For more info regarding this IBM utility click here.

No comments:

Post a Comment