Saturday, January 17, 2009

XmlRpc with Clojure

I know, I know... I really should update this blog more often. Brief recap: last year I've made a fairly big Common Lisp project (funmv), and played quite a bit with both Haskell and Clojure. Today I want to share some experiences using XmlRpc with Clojure.

Clojure has the advantage of running on JVM, which means that it can use Java libraries. The problem is that, being a Lisp with a functional flavour, it sometimes doesn't mix well with the object-oriented programming style mandatory in Java development. I needed to implement a Xml-Rpc server in clojure, but my first attempts with apache xmlrpc and others ended in failure since their addHandler methods required an object, and would match the XmlRpc message methods with the name of the member functions. It is possible to instantiate Java-objects with the proxy special form in Clojure, but this only allows you to implement or subclass already declared methods, and creating an object completely from scratch seemed too complicated.

Finally I found an XmlRpc library from redstone (download, which allows you to define your own dispatch routine. This allows me to inspect the method name and call normal Clojure functions, rather than relying on Java reflection magic. The server code is short and sweet:

(def server (new redstone.xmlrpc.simple.Server 8080))
(def h (proxy [redstone.xmlrpc.XmlRpcInvocationHandler] []
(invoke [method-name arguments]
(= method-name "add") (+ (nth arguments 0) (nth arguments 1))
true (throw (new Exception "No such method"))))))
(doto (.getXmlRpcServer server) (.addInvocationHandler "test" h))
(.start server)

Here is a Java test client

import redstone.xmlrpc.XmlRpcClient;
public class SampleClient
public static void main( String[] args ) throws Exception
XmlRpcClient client = new XmlRpcClient( "http://localhost:8080", false );
Object reply = client.invoke( "test.add", new Object[] {1, 2} );
System.out.println (reply); // should be 3

You will need to add the jar files to the classpath:

javac -cp xmlrpc-1.1.1.jar
jar cf SampleClient.jar *class
java -cp SampleClient.jar:xmlrpc-1.1.1.jar SampleClient