    001package org.apache.turbine.services.jsonrpc;
    002
    003import java.io.CharArrayWriter;
    004
    005import javax.servlet.http.HttpServletRequest;
    006
    007import org.apache.commons.logging.Log;
    008import org.apache.commons.logging.LogFactory;
    009import org.jabsorb.JSONRPCBridge;
    010import org.jabsorb.JSONRPCResult;
    011import org.json.JSONArray;
    012import org.json.JSONException;
    013import org.json.JSONObject;
    014
    015/**
    016 * Process a JSON RPC call
    017 *
    018 * @author <a href="mailto:seade@backstagetech.com.au">Scott Eade</a>
    019 */
    020public class JSONProcessor
    021{
    022    /** Log. */
    023    private static Log log = LogFactory.getLog(JSONProcessor.class);
    024
    025    /**
    026     * Process a JSON RPC call
    027     * @param cdata the JSON data
    028     * @param json_bridge the {@link JSONRPCBridge} object
    029     * @param request the request
    030     * @return the return object of the JSON RPC call
    031     */
    032    public static Object processCall(CharArrayWriter cdata, JSONRPCBridge json_bridge, HttpServletRequest request)
    033    {
    034        // Process the request
    035        JSONObject json_req = null;
    036        Object json_res = null;
    037        try
    038        {
    039            json_req = new JSONObject(cdata.toString());
    040            if (log.isDebugEnabled())
    041            {
    042                String methodName = json_req.getString("method");
    043                JSONArray arguments = json_req.getJSONArray("params");
    044
    045                // If this a CallableReference it will have a non-zero objectID
    046                int object_id = json_req.optInt("objectID");
    047                StringBuilder sb = new StringBuilder(".doprocessCall(): call ");
    048                if (object_id != 0)
    049                {
    050                    sb.append("objectID=").append(object_id).append(" ");
    051                }
    052                sb.append(methodName).append("(").append(arguments).append(")");
    053                log.debug(sb.toString());
    054            }
    055            //json_res = json_bridge.call(new Object[] {request}, object_id, methodName, arguments);
    056            json_res = json_bridge.call(new Object[] {request}, json_req);
    057        }
    058        catch (JSONException e)
    059        {
    060            log.error(".processCall(): can't parse call: " + cdata, e);
    061            json_res = JSONRPCResult.MSG_ERR_PARSE;
    062        }
    063        // Write the response
    064        if (log.isDebugEnabled())
    065        {
    066            log.debug(".processCall():  returns " + json_res.toString());
    067        }
    068        return json_res;
    069    }
    070
    071}