View Javadoc
1   package org.apache.turbine.modules.screens;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.io.OutputStreamWriter;
23  import java.io.PrintWriter;
24  import java.nio.charset.Charset;
25  import java.nio.charset.StandardCharsets;
26  
27  import org.apache.turbine.pipeline.PipelineData;
28  import org.apache.turbine.util.RunData;
29  import org.slf4j.Logger;
30  import org.slf4j.LoggerFactory;
31  
32  
33  /**
34   * A Screen class for dealing with JSON requests.  Typically you would
35   * extend this class and override the doOutput() method to use it by setting the JSON output into
36   * rundata.setMessage( serialized ).
37   * As convenience you may use inject in your extended class the Turbine service JsonService
38   * Use {@link PlainJSONSecureAnnotatedScreen} if you need the user to be
39   * logged in or having a special role in prior to executing the functions you provide.
40   *
41   * <p>Here is an example from a subclass:
42   *
43   * <code>
44   *
45   *
46   * public void doOutput(PipelineData pipelineData) throws Exception
47   * {
48   *     RunData data = pipelineData.getRunData();
49   *     JSONStrategy strategy = null;
50   *
51   *     try
52   *     {
53   *        strategy = new XYStrategy();
54   *        // the result goes into rundata.message
55   *        strategy.execute(data, jsonService);
56   *     }
57   *       catch ( Exception e )
58   *       {
59   *          log.error( "init failed for "+strategy , e);
60   *          String msg = new JSONObject().put("error", e.getMessage()).toString();
61   *          data.setMessage( msg );
62   *       }
63   *
64   *     super.doOutput(data);
65   * }
66   * </code>
67   *
68   *
69   * @author gk
70   * @version $Id$
71   */
72  public class PlainJSONScreen extends RawScreen
73  {
74      protected static final String JSON_TYPE = "application/json;charset=utf-8";
75  
76      protected final static int BUFFER_SIZE = 4096;
77  
78      static final Logger log = LoggerFactory.getLogger(PlainJSONScreen.class);
79  
80      /** Injected service instance */
81      //@TurbineService
82      //protected JsonService jsonService;
83  
84      /**
85       * @see org.apache.turbine.modules.screens.RawScreen#getContentType(org.apache.turbine.pipeline.PipelineData)
86       */
87      @Override
88      protected String getContentType(PipelineData pipelineData)
89      {
90          return JSON_TYPE;
91      }
92  
93      /**
94       * Output JSON content set into {@link RunData#getMessage()}.
95       *
96       * Encoding is UTF-8. @{@link #JSON_TYPE}: {@value #JSON_TYPE}.
97       *
98       * @param pipelineData The PipelineData object.
99       */
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 }