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.OutputStreamWriter;
023import java.io.PrintWriter;
024import java.nio.charset.Charset;
025import java.nio.charset.StandardCharsets;
026
027import org.apache.turbine.pipeline.PipelineData;
028import org.apache.turbine.util.RunData;
029import org.slf4j.Logger;
030import org.slf4j.LoggerFactory;
031
032
033/**
034 * A Screen class for dealing with JSON requests.  Typically you would
035 * extend this class and override the doOutput() method to use it by setting the JSON output into
036 * rundata.setMessage( serialized ).
037 * As convenience you may use inject in your extended class the Turbine service JsonService
038 * Use {@link PlainJSONSecureAnnotatedScreen} if you need the user to be
039 * logged in or having a special role in prior to executing the functions you provide.
040 *
041 * <p>Here is an example from a subclass:
042 *
043 * <code>
044 *
045 *
046 * public void doOutput(PipelineData pipelineData) throws Exception
047 * {
048 *     RunData data = pipelineData.getRunData();
049 *     JSONStrategy strategy = null;
050 *
051 *     try
052 *     {
053 *        strategy = new XYStrategy();
054 *        // the result goes into rundata.message
055 *        strategy.execute(data, jsonService);
056 *     }
057 *       catch ( Exception e )
058 *       {
059 *          log.error( "init failed for "+strategy , e);
060 *          String msg = new JSONObject().put("error", e.getMessage()).toString();
061 *          data.setMessage( msg );
062 *       }
063 *
064 *     super.doOutput(data);
065 * }
066 * </code>
067 *
068 *
069 * @author gk
070 * @version $Id$
071 */
072public class PlainJSONScreen extends RawScreen
073{
074    protected static final String JSON_TYPE = "application/json;charset=utf-8";
075
076    protected final static int BUFFER_SIZE = 4096;
077
078    static final Logger log = LoggerFactory.getLogger(PlainJSONScreen.class);
079
080    /** Injected service instance */
081    //@TurbineService
082    //protected JsonService jsonService;
083
084    /**
085     * @see org.apache.turbine.modules.screens.RawScreen#getContentType(org.apache.turbine.pipeline.PipelineData)
086     */
087    @Override
088    protected String getContentType(PipelineData pipelineData)
089    {
090        return JSON_TYPE;
091    }
092
093    /**
094     * Output JSON content set into {@link RunData#getMessage()}.
095     *
096     * Encoding is UTF-8. @{@link #JSON_TYPE}: {@value #JSON_TYPE}.
097     *
098     * @param pipelineData The PipelineData object.
099     */
100    @Override
101    protected void doOutput(PipelineData pipelineData) throws Exception
102    {
103        RunData data = pipelineData.getRunData();
104        // read in json!
105        Charset charset = StandardCharsets.UTF_8; //request.getCharacterEncoding();
106
107        String json_res = data.getMessage();
108
109        log.debug( "json_res output: {}", json_res );
110        try (PrintWriter out = new PrintWriter(
111                new OutputStreamWriter(
112                    data.getResponse().getOutputStream(),charset)))
113        {
114            out.print(json_res.toString());
115            out.flush();
116        }
117    }
118}