Dienstag, April 03, 2007

Use Burlap to build a simple Java-Ruby bridge

Yes, I know, there is this great tool JRuby which will hopefully be an essential part of the JDK in the near future, and yes there is REST where Restlet seems to be the most promising framework, but all I wanted is to speak with a very simple Java Interface from a Rails application. So I thought there must be an easier way, but it has to deal with ongoing changes to the interface. The answer for me was the Burlap protocol which you get with Spring for free. All you have to do is to expose your Java bean with the Burlap exporter:

<bean id="fooService"

<bean name="/FooService"
<property name="service" ref="fooService"/>
<property name="serviceInterface"

. Thats it for the Java side. Burlap is a very simple protocol where you dont map classes, what you get is a map with key, value pairs. But thats fine for me.

But also the Ruby side is easy to implement. I am still a newby with Ruby but that was relativly quick done (though its still not as easy to get information like you get for J2EE for instance, where you get too much information).
Because the Burlap protocol just supports the POST method you need the low level Ruby methods for Http:

Net::HTTP.start('localhost', 8080) do |request|
response = request.post('/backendservice/FooService',

And here we go. All you have to do is to parse this XML:

vals = []
XPath.each( Document.new(response.body),
{|p| vals << p.text }

And as I said, what you get are key-value pairs with the exception of the first element which descripes the original type (classname).
I converted it to a map skipping the first element in the array:

@bashvals = {}
1.step(vals.length-1, 2)
{ |i| @bashvals[vals[i]] = vals[i+1] }