Ruby for Java Programmers, Part V

If you’ve been following the previous articles in this series (Part I, Part II, Part III and Part IV) but are not yet satisfied with the range of solutions I presented for calling Ruby code from Java, here’s another one for you.

This one involves running your Java code as a separate process and interacting with it using some form of Web service (XML-RPC, SOAP or a RESTful service). We’ll use XML-RPC for this sample, mainly because it’s very easy to set up and use. You’ll need Apache XML-RPC version 2 to make the code run. Here’s the java code:

public class RPCFetcher {
    public static void main(String args[]) throws Exception {
        WebServer server = new WebServer(8080);
        server.addHandler("$default", new RPCFetcher());
        server.start();
    }

    public Vector fetch(String url) throws Exception {
        URL feedUrl = new URL(url);
        FeedFetcherCache feedInfoCache = HashMapFeedInfoCache.getInstance();
        FeedFetcher fetcher = new HttpURLFeedFetcher(feedInfoCache);
        SyndFeed feed = fetcher.retrieveFeed(feedUrl);
        Vector items = new Vector();
        for (Iterator it = feed.getEntries().iterator() ; it.hasNext() ; ) {
            SyndEntry entry = (SyndEntry) it.next();
            Hashtable map = new Hashtable();
            map.put("link", entry.getLink());
            map.put("title", entry.getTitle());
            map.put("publishedDate", entry.getPublishedDate());
            items.add(map);
        }
        return items;
    }
}

Compared to the previous samples, there’s not much else you need to do, besides creating an instance of WebServer to handle incoming HTTP requests and dispatch them to the appropriate method. However, you need to convert your Java types to something that XML-RPC is able to understand, i.e. strings, numbers, dates, Vectors, Hashtables and little else.

The Ruby client code is much simpler:

require 'xmlrpc/client'
server = XMLRPC::Client.new 'localhost', '/', 8080
entries = server.call('fetch', 'http://agylen.com/feed')
entries.each do | entry |
  p "#{entry['publishedDate'].to_time} #{entry['title']}"
end

Possible drawbacks of this technique are the necessity of having a separate process running and the overhead of HTTP communication and XML-RPC protocol encoding and decoding.

Thanks to Nick Stuart and Erik Hatcher for laying down the basics.

Leave a Reply