Bserver.java

import org.apache.xmlrpc.*;
import java.util.*; // for Vector
import java.io.*; // for IOException

/**
Simple XML-RPC server with several handlers.

@author Walt Leipold
*/
public class Bserver
{
    public static void main(String[] argv)
    {
        HashMap m = new HashMap(); // Storage available to all clients.
        try {
            WebServer ws = new WebServer(9090);
            // Default handler handles put(), get(), and die().
            ws.addHandler("$default",new BHandler(m,ws));
            // Second handler has only a reverse() method.
            ws.addHandler("other",new RHandler());
            // Start the Web server thread.
            ws.start();
            System.out.println("Running...");
            }
        catch (Exception e) {
            System.out.println("Exception!");
            e.printStackTrace();
            }
        // And the Webserver thread keeps running...
    }
}


/**
Handler implements a shared associative array with methods
<code>put(name,value)</code> and <code>get(name)</code>.
Also responsible for shutting down the Web server when a special
request (<code>die()</code>) is received.
*/
class BHandler implements XmlRpcHandler
{
    public BHandler(HashMap m,WebServer ws)
    {
        mymap = m;
        myserver = ws;
    }

    public Object execute(String method,Vector params)
        throws Exception
    {
        if (method.endsWith("put")) {
            mymap.put(params.get(0),params.get(1));
            return "OK";
            }
        else if (method.endsWith("get")) {
            // (Note that a missing key is not handled gracefully.)
            return mymap.get(params.get(0));
            }
        else if (method.endsWith("die")) {
            myserver.shutdown();
            System.out.println("Aarrrgggghhhhh!");
            return "Dying...";
            }
        return "Unknown method name: " + method;
    }

    private HashMap mymap;
    private WebServer myserver;
}


/**
Handler with a reverse() method.
*/
class RHandler implements XmlRpcHandler
{
    public Object execute(String method,Vector params)
        throws Exception
    {
        if (method.endsWith("reverse")) {
            return (new StringBuffer((String)(params.get(0)))).
                reverse().toString();
            }
        return "Unknown method name: " + method;
    }
}