001package org.apache.turbine.modules.screens;
002
003/*
004 * Licensed to the Apache Software Foundation (ASF) under one
005 * or more contributor license agreements.  See the NOTICE file
006 * distributed with this work for additional information
007 * regarding copyright ownership.  The ASF licenses this file
008 * to you under the Apache License, Version 2.0 (the
009 * "License"); you may not use this file except in compliance
010 * with the License.  You may obtain a copy of the License at
011 *
012 *   http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing,
015 * software distributed under the License is distributed on an
016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017 * KIND, either express or implied.  See the License for the
018 * specific language governing permissions and limitations
019 * under the License.
020 */
021
022import java.io.BufferedReader;
023import java.io.CharArrayWriter;
024import java.io.InputStreamReader;
025import java.io.OutputStreamWriter;
026import java.io.PrintWriter;
027import java.nio.charset.Charset;
028import java.nio.charset.StandardCharsets;
029
030import javax.servlet.http.HttpServletRequest;
031
032import org.apache.turbine.annotation.TurbineService;
033import org.apache.turbine.pipeline.PipelineData;
034import org.apache.turbine.services.jsonrpc.JsonRpcService;
035import org.apache.turbine.util.RunData;
036import org.jabsorb.JSONRPCBridge;
037
038
039/**
040 * A Screen class for dealing with JSON-RPC requests.  Typically you would
041 * extend this class and override the doOutput() method to use TurbineJsonRpc
042 * to register the POJOs that will provide the functions you are making
043 * available via JSON-RPC.  Use JSONSecureScreen if you need the user to be
044 * logged in prior to executing the functions you provide.
045 *
046 * <p>Here is an example from a superclass:
047 * <code>
048 * public void doOutput(PipelineData data) throws Exception
049 * {
050 *     User user = data.getUser();
051 *
052 *     MyJsonFunctions myFunctions = new MyJsonFunctions(user.getName());
053 *
054 *     // Session specific
055 *     TurbineJsonRpc.registerObject(data.getSession(), "myFunctions", myFunctions);
056 *
057 *     // Global
058 *     //TurbineJsonRpc.registerObjectGlobal("testGlobal", testObject);
059 *
060 *     super.doOutput(data);
061 * }
062 * </code>
063 *
064 * <p>The class MyFunctions would be something like:
065 * <code>
066 * public class MyJsonFunctions
067 * {
068 *     private String getHello(String clientParameter)
069 *     {
070 *         return "Hello " + clientParameter;
071 *     }
072 * }
073 * </code>
074 *
075 * <p>This code is derived from the com.metaparadigm.jsonrpc.JSONRPCServlet and (after upgrade) checked against
076 * org.jabsorb.JSONRPCServlet.
077 *
078 * @author brad@folkens.com
079 * @author <a href="mailto:seade@backstagetech.com.au">Scott Eade</a>
080 * @version $Id$
081 */
082public class JSONScreen extends RawScreen
083{
084    protected static final String JSONRPC_CONTENT_TYPE = "application/json;charset=utf-8";
085
086    protected final static int BUFFER_SIZE = 4096;
087
088    /** Injected service instance */
089    @TurbineService
090    protected JsonRpcService jsonRpcService;
091
092    /**
093     * @see org.apache.turbine.modules.screens.RawScreen#getContentType(org.apache.turbine.pipeline.PipelineData)
094     */
095    @Override
096    protected String getContentType(PipelineData pipelineData)
097    {
098        return JSONRPC_CONTENT_TYPE;
099    }
100
101    /**
102     * Output the dynamic content.
103     *
104     * Encoding is UTF-8. @{@link #JSONRPC_CONTENT_TYPE}: {@value #JSONRPC_CONTENT_TYPE}.
105     *
106     * @param pipelineData The PipelineData object.
107     */
108    @Override
109    protected void doOutput(PipelineData pipelineData) throws Exception
110    {
111        RunData data = pipelineData.getRunData();
112        data.declareDirectResponse();
113        HttpServletRequest request = data.getRequest();
114
115        // we require utf-8, cft
116        Charset charset =  StandardCharsets.UTF_8; //request.getCharacterEncoding();
117        BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset));
118
119        // Read the request
120        CharArrayWriter cdata = new CharArrayWriter();
121        char buf[] = new char[BUFFER_SIZE];
122        int ret;
123        while ((ret = in.read(buf, 0, BUFFER_SIZE)) != -1)
124        {
125            cdata.write(buf, 0, ret);
126        }
127
128        // Find the JSONRPCBridge for this session or create one
129        // if it doesn't exist
130        JSONRPCBridge json_bridge = jsonRpcService.getBridge(data.getSession());
131
132        // Process the request
133        Object json_res = jsonRpcService.processCall(cdata, json_bridge, request);
134
135        try (PrintWriter out = new PrintWriter(
136                new OutputStreamWriter(
137                    data.getResponse().getOutputStream(), charset)))
138        {
139            out.print(json_res.toString());
140            out.flush();
141        }
142    }
143}