Author: seade
Date: Wed May  9 19:30:09 2007
New Revision: 536735

URL: http://svn.apache.org/viewvc?view=rev&rev=536735
Log:
Added JSON-RPC Service to support JavaScript to Java AJAX communications.

Added:
    
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/modules/screens/JSONScreen.java
    
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/modules/screens/JSONSecureScreen.java
    
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/
    
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/JSONProcessor.java
    
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/JsonRpcService.java
    
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/TurbineJsonRpc.java
    
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/TurbineJsonRpcService.java
    
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/package.html
    
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/test/org/apache/turbine/services/jsonrpc/
    
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/test/org/apache/turbine/services/jsonrpc/JsonrpcServicelTest.java
    
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/services/jsonrpc-service.xml
Modified:
    
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/conf/test/TurbineResources.properties
    jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/project.xml
    jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/changes.xml
    jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/navigation.xml
    jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/services/index.xml

Modified: 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/conf/test/TurbineResources.properties
URL: 
http://svn.apache.org/viewvc/jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/conf/test/TurbineResources.properties?view=diff&rev=536735&r1=536734&r2=536735
==============================================================================
--- 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/conf/test/TurbineResources.properties
 (original)
+++ 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/conf/test/TurbineResources.properties
 Wed May  9 19:30:09 2007
@@ -292,6 +292,7 @@
 
services.VelocityService.classname=org.apache.turbine.services.velocity.TurbineVelocityService
 
services.UploadService.classname=org.apache.turbine.services.upload.TurbineUploadService
 
services.SecurityService.classname=org.apache.turbine.services.security.torque.TorqueSecurityService
+services.JsonRpcService.classname=org.apache.turbine.services.jsonrpc.TurbineJsonRpcService
 
 # -------------------------------------------------------------------
 #

Modified: jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/project.xml
URL: 
http://svn.apache.org/viewvc/jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/project.xml?view=diff&rev=536735&r1=536734&r2=536735
==============================================================================
--- jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/project.xml (original)
+++ jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/project.xml Wed May  9 
19:30:09 2007
@@ -643,6 +643,16 @@
       </properties>
     </dependency>
     <dependency>
+      <groupId>com.metaparadigm</groupId>
+      <artifactId>json-rpc</artifactId>
+      <version>1.0</version>
+      <url>http://oss.metaparadigm.com/jsonrpc/</url>
+      <type>jar</type>
+      <properties>
+      <war.bundle>true</war.bundle>
+      </properties>
+    </dependency> 
+    <dependency>
       <groupId>log4j</groupId>
       <artifactId>log4j</artifactId>
       <version>1.2.12</version>

Added: 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/modules/screens/JSONScreen.java
URL: 
http://svn.apache.org/viewvc/jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/modules/screens/JSONScreen.java?view=auto&rev=536735
==============================================================================
--- 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/modules/screens/JSONScreen.java
 (added)
+++ 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/modules/screens/JSONScreen.java
 Wed May  9 19:30:09 2007
@@ -0,0 +1,140 @@
+package org.apache.turbine.modules.screens;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.BufferedReader;
+import java.io.PrintWriter;
+import java.io.CharArrayWriter;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.turbine.modules.screens.RawScreen;
+import org.apache.turbine.services.jsonrpc.TurbineJsonRpc;
+import org.apache.turbine.util.RunData;
+
+import com.metaparadigm.jsonrpc.JSONRPCBridge;
+
+/**
+ * A Screen class for dealing with JSON-RPC requests.  Typically you would
+ * extend this class and override the doOutput() method to use TurbineJsonRpc
+ * to register the POJOs that will provide the functions you are making
+ * available via JSON-RPC.  Use JSONSecureScreen if you need the user to be
+ * logged in prior to executing the functions you provide.
+ *
+ * <p>Here is an example from a superclass:
+ * <code>
+ * public void doOutput(RunData data) throws Exception
+ * {
+ *     User user = data.getUser();
+ *
+ *     MyJsonFunctions myFunctions = new MyJsonFunctions(user.getName());
+ *
+ *     // Session specific
+ *     TurbineJsonRpc.registerObject(data.getSession(), "myFunctions", 
myFunctions);
+ *
+ *     // Global
+ *     //TurbineJsonRpc.registerObjectGlobal("testGlobal", testObject);
+ *
+ *     super.doOutput(data);
+ * }
+ * </code>
+ * 
+ * <p>The class MyFunctions would be something like:
+ * <code>
+ * public class MyJsonFunctions
+ * {
+ *     private String getHello(String clientParameter)
+ *     {
+ *         return "Hello " + clientParameter;
+ *     }
+ * }
+ * </code>
+ *
+ * <p>This code is derived from the com.metaparadigm.jsonrpc.JSONRPCServlet
+ *
+ * @author [EMAIL PROTECTED]
+ * @author <a href="mailto:[EMAIL PROTECTED]">Scott Eade</a>
+ * @version $Id$
+ */
+public class JSONScreen extends RawScreen
+{
+    protected static final String JSONRPC_CONTENT_TYPE = "text/plain";
+
+    protected final static int BUFFER_SIZE = 4096;
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see 
org.apache.turbine.modules.screens.RawScreen#getContentType(org.apache.turbine.util.RunData)
+     */
+    protected String getContentType(RunData data)
+    {
+        return JSONRPC_CONTENT_TYPE;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see 
org.apache.turbine.modules.screens.RawScreen#doOutput(org.apache.turbine.util.RunData)
+     */
+    
+    /**
+     * Output the dynamic content.
+     *
+     * @param data The RunData object.
+     */
+    protected void doOutput(RunData data) throws Exception
+    {
+        data.declareDirectResponse();
+        HttpServletRequest request = data.getRequest();
+        
+        //String charset = request.getCharacterEncoding();
+        //if(charset == null)
+        //{
+        //    charset = "UTF-8";
+        //}
+        //BufferedReader in = new BufferedReader(new 
InputStreamReader(request.getInputStream(), charset));
+        BufferedReader in = new BufferedReader(new 
InputStreamReader(request.getInputStream()));
+
+        // Read the request
+        CharArrayWriter cdata = new CharArrayWriter();
+        char buf[] = new char[BUFFER_SIZE];
+        int ret;
+        while ((ret = in.read(buf, 0, BUFFER_SIZE)) != -1)
+        {
+            cdata.write(buf, 0, ret);
+        }
+
+        // Find the JSONRPCBridge for this session or create one
+        // if it doesn't exist
+        JSONRPCBridge json_bridge = 
TurbineJsonRpc.getBridge(data.getSession());
+
+        // Process the request
+        Object json_res = TurbineJsonRpc.processCall(cdata, json_bridge, 
request);
+
+        PrintWriter out = new PrintWriter(
+                new OutputStreamWriter(data.getResponse().getOutputStream()));
+        out.print(json_res.toString());
+        out.flush();
+        out.close();
+    }
+}

Added: 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/modules/screens/JSONSecureScreen.java
URL: 
http://svn.apache.org/viewvc/jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/modules/screens/JSONSecureScreen.java?view=auto&rev=536735
==============================================================================
--- 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/modules/screens/JSONSecureScreen.java
 (added)
+++ 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/modules/screens/JSONSecureScreen.java
 Wed May  9 19:30:09 2007
@@ -0,0 +1,104 @@
+package org.apache.turbine.modules.screens;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.turbine.modules.screens.JSONScreen;
+import org.apache.turbine.util.RunData;
+
+/**
+ * An extension to JSONScreen that performs a Security Check before invoking
+ * doBuildTemplate().  You should extend this class and add the specific
+ * security check needed.  If you have a number of screens that need to perform
+ * the same check, you could make a base screen by extending this class and
+ * implementing the isAuthorized().  Then each screen that needs to perform the
+ * same check could extend your base screen.
+ * 
+ * <p>Typically you would extend this class and override the doOutput() method
+ * to use TurbineJsonRpc to register the POJOs that will provide the functions
+ * you are making available via JSON-RPC.  Use JSONScreen if you <p>do not</b>
+ * need the user to be logged in prior to executing the functions you provide.
+ *
+ * <p>Here is an example from a superclass:
+ * <code>
+ * public void doOutput(RunData data) throws Exception
+ * {
+ *     User user = data.getUser();
+ *
+ *     MySecureJsonFunctions myFunctions
+ *             = new MySecureJsonFunctions(user.getName());
+ *
+ *     // Session specific
+ *     TurbineJsonRpc.registerObject(data.getSession(), "myFunctions", 
myFunctions);
+ *
+ *     // Global
+ *     //TurbineJsonRpc.registerObjectGlobal("testGlobal", testObject);
+ *
+ *     super.doOutput(data);
+ * }
+ * </code>
+ * 
+ * <p>The class MyFunctions would be something like:
+ * <code>
+ * public class MySecureJsonFunctions
+ * {
+ *     private final String name;
+ *
+ *     public MySecureJsonFunctions(String name)
+ *     {
+ *         this.name = name;
+ *     }
+ *
+ *     private String getName(String clientParameter)
+ *     {
+ *         return "Client " + clientParameter + " says Hello World to " + name;
+ *     }
+ * }
+ * </code>
+ *
+ * @author <a href="mailto:[EMAIL PROTECTED]">Scott Eade</a>
+ * @version $Id$
+ */
+public abstract class JSONSecureScreen extends JSONScreen
+{
+    /**
+     * This method overrides the method in JSONScreen to perform a security
+     * check prior to producing the output.
+     *
+     * @param data Turbine information.
+     * @exception Exception, a generic exception.
+     */
+    protected void doOutput(RunData data) throws Exception
+    {
+        if (isAuthorized(data))
+        {
+            super.doOutput(data);
+        }
+    }
+
+    /**
+     * Override this method to perform the necessary security checks.
+     *
+     * @param data Turbine information.
+     * @return <code>true</code> if the user is authorized to access the 
screen.
+     * @exception Exception A generic exception.
+     */
+    protected abstract boolean isAuthorized(RunData data)
+            throws Exception;
+}

Added: 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/JSONProcessor.java
URL: 
http://svn.apache.org/viewvc/jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/JSONProcessor.java?view=auto&rev=536735
==============================================================================
--- 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/JSONProcessor.java
 (added)
+++ 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/JSONProcessor.java
 Wed May  9 19:30:09 2007
@@ -0,0 +1,60 @@
+package org.apache.turbine.services.jsonrpc;
+
+import java.io.CharArrayWriter;
+import java.text.ParseException;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.json.JSONArray;
+import org.json.JSONObject;
+
+import com.metaparadigm.jsonrpc.JSONRPCBridge;
+import com.metaparadigm.jsonrpc.JSONRPCResult;
+
+public class JSONProcessor
+{
+    /** Log. */
+    private static Log log = LogFactory.getLog(JSONProcessor.class);
+
+    public static Object processCall(CharArrayWriter cdata, JSONRPCBridge 
json_bridge, HttpServletRequest request)
+    {
+        // Process the request
+        JSONObject json_req = null;
+        Object json_res = null;
+        try
+        {
+            json_req = new JSONObject(cdata.toString());
+            if (log.isDebugEnabled())
+            {
+                String methodName = (String) json_req.getString("method");
+                JSONArray arguments = json_req.getJSONArray("params");
+                
+                // If this a CallableReference it will have a non-zero objectID
+                int object_id = json_req.optInt("objectID");
+                StringBuffer sb = new StringBuffer(".doprocessCall(): call ");
+                if (object_id != 0)
+                {
+                    sb.append("objectID=").append(object_id).append(" ");
+                }
+                
sb.append(methodName).append("(").append(arguments).append(")");
+                log.debug(sb.toString());
+            }
+            //json_res = json_bridge.call(new Object[] {request}, object_id, 
methodName, arguments);
+            json_res = json_bridge.call(new Object[] {request}, json_req);
+        }
+        catch (ParseException e)
+        {
+            log.error(".processCall(): can't parse call: " + cdata, e);
+            json_res = JSONRPCResult.MSG_ERR_PARSE;
+        }
+        // Write the response
+        if (log.isDebugEnabled())
+        {
+            log.debug(".processCall():  returns " + json_res.toString());
+        }
+        return json_res;
+    }
+
+}

Added: 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/JsonRpcService.java
URL: 
http://svn.apache.org/viewvc/jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/JsonRpcService.java?view=auto&rev=536735
==============================================================================
--- 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/JsonRpcService.java
 (added)
+++ 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/JsonRpcService.java
 Wed May  9 19:30:09 2007
@@ -0,0 +1,53 @@
+package org.apache.turbine.services.jsonrpc;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import java.io.CharArrayWriter;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.apache.turbine.services.Service;
+
+import com.metaparadigm.jsonrpc.JSONRPCBridge;
+
+/**
+ * The interface an JsonRpcService implements.
+ *
+ * @author <a href="mailto:[EMAIL PROTECTED]">Scott Eade</a>
+ * @version $Id$
+ */
+public interface JsonRpcService
+        extends Service
+{
+    /** TurbineJsonRpcService. */
+    public static final String SERVICE_NAME = "JsonRpcService";
+
+    public Object processCall(CharArrayWriter cdata,
+            JSONRPCBridge json_bridge, HttpServletRequest request);
+
+    public void registerObject(HttpSession session, String key, Object value);
+
+    public void registerObjectGlobal(String key, Object value);
+
+    public JSONRPCBridge getBridge(HttpSession session);
+
+    public void clearBridge(HttpSession session);
+}

Added: 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/TurbineJsonRpc.java
URL: 
http://svn.apache.org/viewvc/jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/TurbineJsonRpc.java?view=auto&rev=536735
==============================================================================
--- 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/TurbineJsonRpc.java
 (added)
+++ 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/TurbineJsonRpc.java
 Wed May  9 19:30:09 2007
@@ -0,0 +1,75 @@
+package org.apache.turbine.services.jsonrpc;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import java.io.CharArrayWriter;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.apache.turbine.services.TurbineServices;
+
+import com.metaparadigm.jsonrpc.JSONRPCBridge;
+
+/**
+ * This is a static accessor class for [EMAIL PROTECTED] JsonRpcService}.
+ *
+ * @author <a href="mailto:[EMAIL PROTECTED]">Scott Eade</a>
+ * @version $Id$
+ */
+public abstract class TurbineJsonRpc
+{
+    /**
+     * Returns system's configured implementation of [EMAIL PROTECTED] 
JsonRpcService}.
+     *
+     * @return an implementation of <code>JsonRpcService</code>
+     */
+    public static JsonRpcService getService()
+    {
+        return (JsonRpcService) TurbineServices.getInstance()
+                .getService(JsonRpcService.SERVICE_NAME);
+    }
+
+    public static Object processCall(CharArrayWriter cdata, 
+            JSONRPCBridge json_bridge, HttpServletRequest request)
+    {
+        return getService().processCall(cdata, json_bridge, request);
+    }
+
+    public static void registerObject(HttpSession session, String key, Object 
value)
+    {
+        getService().registerObject(session, key, value);
+    }
+
+    public static void registerObjectGlobal(String key, Object value)
+    {
+        getService().registerObjectGlobal(key, value);
+    }
+
+    public static JSONRPCBridge getBridge(HttpSession session)
+    {
+        return getService().getBridge(session);
+    }
+
+    public static void clearBridge(HttpSession session)
+    {
+        getService().clearBridge(session);
+    }
+}

Added: 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/TurbineJsonRpcService.java
URL: 
http://svn.apache.org/viewvc/jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/TurbineJsonRpcService.java?view=auto&rev=536735
==============================================================================
--- 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/TurbineJsonRpcService.java
 (added)
+++ 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/TurbineJsonRpcService.java
 Wed May  9 19:30:09 2007
@@ -0,0 +1,109 @@
+package org.apache.turbine.services.jsonrpc;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import java.io.CharArrayWriter;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.turbine.services.TurbineBaseService;
+
+import com.metaparadigm.jsonrpc.JSONRPCBridge;
+
+/**
+ * This is a service that will respond to JSON-RPC calls.
+ *
+ * @author <a href="mailto:[EMAIL PROTECTED]">Scott Eade</a>
+ * @version $Id$
+ */
+public class TurbineJsonRpcService
+        extends TurbineBaseService
+        implements JsonRpcService
+{
+    /** Log. */
+    private static Log log = LogFactory.getLog(TurbineJsonRpcService.class);
+
+    /** The key used to store the bridge in the session. */
+    public static final String JSON_BRIDGE_KEY = "JSONRPCBridge";
+    /**
+     * The debug option for the bridge can be enabled by enabling debug level
+     * logging for this class.
+     */
+    private static final boolean DEBUG = log.isDebugEnabled();
+
+    public Object processCall(CharArrayWriter cdata,
+            JSONRPCBridge json_bridge, HttpServletRequest request)
+    {
+        return JSONProcessor.processCall(cdata, json_bridge, request);
+    }
+
+    public void registerObjectGlobal(String key, Object value)
+    {
+        JSONRPCBridge.getGlobalBridge().setDebug(DEBUG);
+        JSONRPCBridge.getGlobalBridge().registerObject(key, value);
+    }
+
+    public void registerObject(HttpSession session, String key, Object value)
+    {
+        JSONRPCBridge json_bridge = getBridge(session);
+        json_bridge.setDebug(DEBUG);
+        json_bridge.registerObject(key, value);
+    }
+
+    public JSONRPCBridge getBridge(HttpSession session)
+    {
+        JSONRPCBridge json_bridge = (JSONRPCBridge) 
session.getAttribute(JSON_BRIDGE_KEY);
+        if (json_bridge == null)
+        {
+            json_bridge = new JSONRPCBridge();
+            session.setAttribute(JSON_BRIDGE_KEY, json_bridge);
+        }
+        return json_bridge;
+    }
+
+    public void clearBridge(HttpSession session)
+    {
+        session.removeAttribute(JSON_BRIDGE_KEY);
+    }
+
+// The following is modeled on XmlRpcSercice. 
+//    /**
+//     * Initialize the JsonRpcService.
+//     *
+//     * @throws InitializationException Something went wrong in the init 
stage.
+//     */
+//    public void init() throws InitializationException
+//    {
+//        //Configuration conf = getConfiguration();
+//        setInit(true);
+//    }
+//
+//    /**
+//     * Shuts down this service, stopping running threads.
+//     */
+//    public void shutdown()
+//    {
+//        setInit(false);
+//    }
+
+}

Added: 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/package.html
URL: 
http://svn.apache.org/viewvc/jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/package.html?view=auto&rev=536735
==============================================================================
--- 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/package.html
 (added)
+++ 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/java/org/apache/turbine/services/jsonrpc/package.html
 Wed May  9 19:30:09 2007
@@ -0,0 +1,29 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements.  See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership.  The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License.  You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied.  See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+<html>
+<head>
+<!-- head part is ignored -->
+</head>
+
+<body>
+The JSON-RPC Service supports JavaScript to Java AJAX communications between
+browsers and Turbine applications.<br />
+<font size="-2">$Id$</font>
+</body>
+</html>

Added: 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/test/org/apache/turbine/services/jsonrpc/JsonrpcServicelTest.java
URL: 
http://svn.apache.org/viewvc/jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/test/org/apache/turbine/services/jsonrpc/JsonrpcServicelTest.java?view=auto&rev=536735
==============================================================================
--- 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/test/org/apache/turbine/services/jsonrpc/JsonrpcServicelTest.java
 (added)
+++ 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/src/test/org/apache/turbine/services/jsonrpc/JsonrpcServicelTest.java
 Wed May  9 19:30:09 2007
@@ -0,0 +1,50 @@
+package org.apache.turbine.services.jsonrpc;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.apache.turbine.test.BaseTurbineTest;
+
+import com.metaparadigm.jsonrpc.JSONRPCBridge;
+
+
+public class JsonrpcServicelTest
+        extends BaseTurbineTest
+{
+    public JsonrpcServicelTest(String name)
+            throws Exception
+    {
+        super(name, "conf/test/TurbineResources.properties");
+    }
+
+    public static Test suite()
+    {
+        return new TestSuite(JsonrpcServicelTest.class);
+    }
+
+    public void testBridgeAccess()
+    {
+        JSONRPCBridge bridge = new JSONRPCBridge();
+        assertNotNull(bridge);
+    }
+
+}

Modified: jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/changes.xml
URL: 
http://svn.apache.org/viewvc/jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/changes.xml?view=diff&rev=536735&r1=536734&r2=536735
==============================================================================
--- jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/changes.xml 
(original)
+++ jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/changes.xml Wed May  
9 19:30:09 2007
@@ -29,8 +29,15 @@
 <body>
   <release version="2.3.3-dev" date="in Subversion">
     <action type="add" dev="seade">
+      Added JSON-RPC Service to support JavaScript to Java AJAX communications
+      using <a href="http://oss.metaparadigm.com/jsonrpc/";>JSON-RPC-Java</a>.
+      For further details see <a href="services/jsonrpc-service.html">JSON-RPC
+      Service</a>.
+    </action>
+    <action type="add" dev="seade">
       Added UI Service as a replacement for the UIManager pull tool (now
       deprecated in favor of the backwards compatible UITool).
+      For further details see <a href="services/ui-service.html">UI 
Service</a>.
     </action>
     <action type="update" dev="tv">
       Deprecated the DBSecurityService and its associated classes. It has been

Modified: jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/navigation.xml
URL: 
http://svn.apache.org/viewvc/jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/navigation.xml?view=diff&rev=536735&r1=536734&r2=536735
==============================================================================
--- jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/navigation.xml 
(original)
+++ jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/navigation.xml Wed 
May  9 19:30:09 2007
@@ -49,6 +49,7 @@
         <!-- item name="Component Service"   
href="/services/component-service.html"/ -->
         <item name="Factory Service"     
href="/services/factory-service.html"/>
         <item name="Intake Service"      href="/services/intake-service.html"/>
+        <item name="JSON-RPC Service"    
href="/services/jsonrpc-service.html"/>
         <item name="JSP Service"         href="/services/jsp-service.html"/>
         <item name="Localization Service" 
href="/services/localization-service.html"/>
         <item name="Logging Service"     
href="/services/logging-service.html"/>

Modified: 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/services/index.xml
URL: 
http://svn.apache.org/viewvc/jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/services/index.xml?view=diff&rev=536735&r1=536734&r2=536735
==============================================================================
--- jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/services/index.xml 
(original)
+++ jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/services/index.xml 
Wed May  9 19:30:09 2007
@@ -112,6 +112,13 @@
 </li>
 
 <li>
+<a href="jsonrpc-service.html">JSON-RPC Service</a>
+<br/>
+The JSON-RPC Service supports JavaScript to Java AJAX communications using
+<a href="http://oss.metaparadigm.com/jsonrpc/";>JSON-RPC-Java</a>.
+</li>
+
+<li>
 <a href="jsp-service.html">JSP Service</a>
 <br/>
 The JSP Service is the set of classes that process JSP files inside the

Added: 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/services/jsonrpc-service.xml
URL: 
http://svn.apache.org/viewvc/jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/services/jsonrpc-service.xml?view=auto&rev=536735
==============================================================================
--- 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/services/jsonrpc-service.xml
 (added)
+++ 
jakarta/turbine/core/branches/TURBINE_2_3_BRANCH/xdocs/services/jsonrpc-service.xml
 Wed May  9 19:30:09 2007
@@ -0,0 +1,199 @@
+<?xml version="1.0"?>
+
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements.  See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership.  The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License.  You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied.  See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+<document>
+
+ <properties>
+  <title>Turbine Services - JSON-RPC Service</title>
+  <author email="[EMAIL PROTECTED]">Scott Eade</author>
+ </properties>
+
+<body>
+
+<section name="JSON-RPC Service">
+
+<p>
+The JSON-RPC Service supports JavaScript to Java AJAX communications using
+<a href="http://oss.metaparadigm.com/jsonrpc/";>JSON-RPC-Java</a>.
+</p>
+
+</section>
+
+<section name="Configuration">
+
+<source><![CDATA[
+# -------------------------------------------------------------------
+#
+#  S E R V I C E S
+#
+# -------------------------------------------------------------------
+...
+services.JsonRpcService.classname=org.apache.turbine.services.jsonrpc.TurbineJsonRpcService
+...
+]]></source>
+
+</section>
+
+<section name="Usage">
+
+<p>
+There are a number of things you need to do in order to add AJAX functionality
+to your webapp.  First you implement the functions:
+</p>
+
+<source><![CDATA[
+public class MyJsonFunctions
+{
+    private String getHello(String clientParameter)
+    {
+        return "Hello " + clientParameter;
+    }
+    private String getGoodbye(String clientParameter)
+    {
+        return "Goodbye " + clientParameter;
+    }
+}
+]]></source>
+
+<p>
+Next you implement your Screen class to make your functions available:
+</p>
+
+<source><![CDATA[
+public class MyJsonScreen extends JSONScreen
+{
+    public void doOutput(RunData data) throws Exception
+    {
+        User user = data.getUser();
+
+        MyJsonFunctions myFunctions = new MyJsonFunctions(user.getName());
+
+        // Session specific
+        TurbineJsonRpc.registerObject(data.getSession(), "myFunctions", 
myFunctions);
+
+        // Global
+        //TurbineJsonRpc.registerObjectGlobal("testGlobal", testObject);
+
+        super.doOutput(data);
+    }
+}
+]]></source>
+
+<p>
+Now we shift focus to your template classes.  Firstly, there are a few useful
+utility functions that you need to make sure are available to the pages that
+will include AJAX functionality:
+</p>
+
+<source><![CDATA[
+// Body onload utility (supports multiple onload functions)
+function SafeAddOnload(func) {
+       var oldonload = window.onload;
+       if (typeof window.onload != 'function') {
+               window.onload = func;
+       } else {
+               window.onload = function() {
+                       oldonload();
+                       func();
+               };
+       }
+}
+
+// Prepare for possible JSON-RPC requests.
+// jsonurl must be set before calling this function.
+function jsonOnLoad() {
+       try {
+               jsonrpc = new JSONRpcClient(jsonurl);
+       }
+       catch(e) {
+               if(e.message) {
+                       alert(e.message);
+               }
+               else {
+                       alert(e);
+               }
+       }
+}
+
+// Process a JSON-RPC request.
+function jsonEval(evalStr) {
+       try     {
+               return eval(evalStr);
+       }
+       catch(e) {
+               if(e.javaStack) {
+                       alert("Exception: \n\n" + e.javaStack);
+               }
+               else {
+                       alert("Exception: \n\n" + e);
+               }
+       }
+       return null;
+}
+]]></source>
+
+<p>
+In these pages you also need to include the JavaScript necessary to process the
+JSON calls - this file is available as part of the JSON-RPC-Java distribution
+(it is included in the <code>webapps\jaonrpc</code> directory):
+</p>
+
+<source><![CDATA[
+$page.addScript($content.getURI('scripts/jsonrpc.js'))
+]]></source>
+
+<p>
+Then you need to set up the specific handler for the page:
+</p>
+
+<source><![CDATA[
+<script type="text/javascript">
+<!--
+  ## Set up the JSON-RPC handler.
+  var jsonurl = '$link.setScreen("MyJsonScreen")';
+  SafeAddOnload(jsonOnLoad);
+  ## myArg below would be provided when you call this function from your
+  ## web page (usually you would retrieve something via the DOM or your
+  ## favorite JavaScript DOM wrapper library).
+  function retrieveHello(myArg) {
+    ## This is a synchronous call.
+    var helloResult = jsonEval("jsonrpc.myFunctions.getHello(" + myArg + ")");
+    if(null == helloResult) {
+      alert('Something went wrong!');
+      return;
+    }
+    ## Here you would again use the DOM to include the result somewhere on your
+    ## page.
+  }
+//-->
+</script>
+]]></source>
+
+<p>
+The above code is executable by users that are not logged into your 
application.
+Your Screen class can extend JSONSecureScreen to require that users be logged 
in
+before allowing execution.
+</p>
+
+</section>
+
+</body>
+</document>



---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to