Calling All EJBs — From Ruby?
After installing and playing with JRuby a few days ago, I started wondering if it would be possible to access an EJB from a JRuby script. After all, the Java code to call an EJB is purely client code, only communicating with an application server over an HTTP-like protocol (HTTP-like in BEA’s case, anyway). At my current project, the OptimalJ team generates all their domain code and delivers business services around that in the form of session EJBs to us, the web frontend team. We’re using BEA WebLogic Portal to code the frontend. Now if we’d have EJB access from JRuby, and Rails on JRuby (which seems to be only a matter of time), I guess we would be able to build a frontend like this in Rails. There’s just the tiny matter of convincing the company’s enterprise architect, who’s already sick of hearing me talk about Ruby and Rails.
Anyway, to the code! To my surprise (after 6 years of experience with EJBs, anything EJB-related working instantly comes as a great surprise) it was just a matter of JRubyfying the Java code that you would write to use an EJB. It just works, there’s nothing more to it. Here’s an example of the magic code:
require 'java' include_class 'java.util.Properties' include_class 'javax.naming.Context' include_class 'javax.naming.InitialContext' properties = Properties.new properties.put(Context::INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory") properties.put(Context::PROVIDER_URL, "t3://localhost:7001") context = InitialContext.new(properties) home = context.lookup("business-ejb-jndi-name") business_ejb = home.create result = business_ejb.someBusinessMethod(parameters)
Okay, here’s some small print. The example works on a BEA WebLogic application server. For another JEE application server you’ll need to fill in the correct InitialContextFactory class name. Fill in the JNDI name for the EJB after the lookup call. Also, before running the script, you’ll have to put the right libraries in the CLASSPATH environment variable. For example, for the BEA server I had to include weblogic.jar and the EJB client jar containing the home interface to the EJB. But once you’ve figured that out, it should work; I got it to work on JBoss as well as BEA. Consult your local Java guru if necessary.
I’ve put all this in a JRuby module (to be downloaded here), which enables you to write just this to call your favourite EJB:
require 'rejb' business_ejb = Rejb::ejb("business-ejb-jndi-name") result = business_ejb.someBusinessMethod(parameters)
I’ve been feeling very happy over the last few days, even though there’s no Spring in sight. Must be the summer of Ruby that’s coming…
2006-04-13. 4 responses.