View Javadoc

1   /*
2    * $Id: PortletVelocityResult.java 651946 2008-04-27 13:41:38Z apetrelli $
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  package org.apache.struts2.portlet.result;
23  
24  import java.io.OutputStreamWriter;
25  import java.io.Writer;
26  
27  import javax.portlet.ActionResponse;
28  import javax.servlet.Servlet;
29  import javax.servlet.ServletContext;
30  import javax.servlet.http.HttpServletRequest;
31  import javax.servlet.http.HttpServletResponse;
32  import javax.servlet.jsp.JspFactory;
33  import javax.servlet.jsp.PageContext;
34  
35  import org.apache.struts2.ServletActionContext;
36  import org.apache.struts2.StrutsConstants;
37  import org.apache.struts2.dispatcher.StrutsResultSupport;
38  import org.apache.struts2.portlet.PortletActionConstants;
39  import org.apache.struts2.portlet.context.PortletActionContext;
40  import org.apache.struts2.views.JspSupportServlet;
41  import org.apache.struts2.views.velocity.VelocityManager;
42  import org.apache.velocity.Template;
43  import org.apache.velocity.app.VelocityEngine;
44  import org.apache.velocity.context.Context;
45  
46  import com.opensymphony.xwork2.ActionContext;
47  import com.opensymphony.xwork2.ActionInvocation;
48  import com.opensymphony.xwork2.inject.Inject;
49  import com.opensymphony.xwork2.util.ValueStack;
50  import com.opensymphony.xwork2.util.logging.Logger;
51  import com.opensymphony.xwork2.util.logging.LoggerFactory;
52  
53  /***
54   * <!-- START SNIPPET: description -->
55   *
56   * Using the Servlet container's {@link JspFactory}, this result mocks a JSP
57   * execution environment and then displays a Velocity template that will be
58   * streamed directly to the servlet output.
59   *
60   * <!-- END SNIPPET: description --> <p/><b>This result type takes the
61   * following parameters: </b>
62   *
63   * <!-- START SNIPPET: params -->
64   *
65   * <ul>
66   *
67   * <li><b>location (default) </b>- the location of the template to process.
68   * </li>
69   *
70   * <li><b>parse </b>- true by default. If set to false, the location param
71   * will not be parsed for Ognl expressions.</li>
72   *
73   * </ul>
74   * <p>
75   * This result follows the same rules from {@link StrutsResultSupport}.
76   * </p>
77   *
78   * <!-- END SNIPPET: params -->
79   *
80   * <b>Example: </b>
81   *
82   * <pre>
83   * &lt;!-- START SNIPPET: example --&gt;
84   *  &lt;result name=&quot;success&quot; type=&quot;velocity&quot;&gt;
85   *    &lt;param name=&quot;location&quot;&gt;foo.vm&lt;/param&gt;
86   *  &lt;/result&gt;
87   *  &lt;!-- END SNIPPET: example --&gt;
88   * </pre>
89   *
90   */
91  public class PortletVelocityResult extends StrutsResultSupport {
92  
93      private static final long serialVersionUID = -8241086555872212274L;
94  
95      private static final Logger LOG = LoggerFactory.getLogger(PortletVelocityResult.class);
96      
97      private String defaultEncoding;
98      private VelocityManager velocityManager;
99      public PortletVelocityResult() {
100         super();
101     }
102 
103     public PortletVelocityResult(String location) {
104         super(location);
105     }
106     
107     @Inject
108     public void setVelocityManager(VelocityManager mgr) {
109         this.velocityManager = mgr;
110     }
111     
112     @Inject(StrutsConstants.STRUTS_I18N_ENCODING)
113     public void setDefaultEncoding(String encoding) {
114         this.defaultEncoding = encoding;
115     }
116 
117     /* (non-Javadoc)
118      * @see org.apache.struts2.dispatcher.StrutsResultSupport#doExecute(java.lang.String, com.opensymphony.xwork2.ActionInvocation)
119      */
120     public void doExecute(String location, ActionInvocation invocation)
121             throws Exception {
122         if (PortletActionContext.isEvent()) {
123             executeActionResult(location, invocation);
124         } else if (PortletActionContext.isRender()) {
125             executeRenderResult(location, invocation);
126         }
127     }
128 
129     /***
130      * Executes the result
131      *
132      * @param location The location string
133      * @param invocation The action invocation
134      */
135     private void executeActionResult(String location,
136             ActionInvocation invocation) {
137         ActionResponse res = PortletActionContext.getActionResponse();
138         // View is rendered outside an action...uh oh...
139         res.setRenderParameter(PortletActionConstants.ACTION_PARAM,
140                 "freemarkerDirect");
141         res.setRenderParameter("location", location);
142         res.setRenderParameter(PortletActionConstants.MODE_PARAM, PortletActionContext
143                 .getRequest().getPortletMode().toString());
144 
145     }
146 
147     /***
148      * Creates a Velocity context from the action, loads a Velocity template and
149      * executes the template. Output is written to the servlet output stream.
150      *
151      * @param finalLocation the location of the Velocity template
152      * @param invocation an encapsulation of the action execution state.
153      * @throws Exception if an error occurs when creating the Velocity context,
154      *         loading or executing the template or writing output to the
155      *         servlet response stream.
156      */
157     public void executeRenderResult(String finalLocation,
158             ActionInvocation invocation) throws Exception {
159         ValueStack stack = ActionContext.getContext().getValueStack();
160 
161         HttpServletRequest request = ServletActionContext.getRequest();
162         HttpServletResponse response = ServletActionContext.getResponse();
163         JspFactory jspFactory = null;
164         ServletContext servletContext = ServletActionContext
165                 .getServletContext();
166         Servlet servlet = JspSupportServlet.jspSupportServlet;
167 
168         velocityManager.init(servletContext);
169 
170         boolean usedJspFactory = false;
171         PageContext pageContext = (PageContext) ActionContext.getContext().get(
172                 ServletActionContext.PAGE_CONTEXT);
173 
174         if (pageContext == null && servlet != null) {
175             jspFactory = JspFactory.getDefaultFactory();
176             pageContext = jspFactory.getPageContext(servlet, request, response,
177                     null, true, 8192, true);
178             ActionContext.getContext().put(ServletActionContext.PAGE_CONTEXT,
179                     pageContext);
180             usedJspFactory = true;
181         }
182 
183         try {
184             String encoding = getEncoding(finalLocation);
185             String contentType = getContentType(finalLocation);
186 
187             if (encoding != null) {
188                 contentType = contentType + ";charset=" + encoding;
189             }
190             response.setContentType(contentType);
191             Template t = getTemplate(stack,
192                     velocityManager.getVelocityEngine(), invocation,
193                     finalLocation, encoding);
194 
195             Context context = createContext(velocityManager, stack, request,
196                     response, finalLocation);
197             Writer writer = new OutputStreamWriter(response.getOutputStream(),
198                     encoding);
199 
200             t.merge(context, writer);
201 
202             // always flush the writer (we used to only flush it if this was a
203             // jspWriter, but someone asked
204             // to do it all the time (WW-829). Since Velocity support is being
205             // deprecated, we'll oblige :)
206             writer.flush();
207         } catch (Exception e) {
208             LOG.error("Unable to render Velocity Template, '" + finalLocation
209                     + "'", e);
210             throw e;
211         } finally {
212             if (usedJspFactory) {
213                 jspFactory.releasePageContext(pageContext);
214             }
215         }
216 
217         return;
218     }
219 
220     /***
221      * Retrieve the content type for this template. <p/>People can override
222      * this method if they want to provide specific content types for specific
223      * templates (eg text/xml).
224      *
225      * @return The content type associated with this template (default
226      *         "text/html")
227      */
228     protected String getContentType(String templateLocation) {
229         return "text/html";
230     }
231 
232     /***
233      * Retrieve the encoding for this template. <p/>People can override this
234      * method if they want to provide specific encodings for specific templates.
235      *
236      * @return The encoding associated with this template (defaults to the value
237      *         of 'struts.i18n.encoding' property)
238      */
239     protected String getEncoding(String templateLocation) {
240         String encoding = defaultEncoding;
241         if (encoding == null) {
242             encoding = System.getProperty("file.encoding");
243         }
244         if (encoding == null) {
245             encoding = "UTF-8";
246         }
247         return encoding;
248     }
249 
250     /***
251      * Given a value stack, a Velocity engine, and an action invocation, this
252      * method returns the appropriate Velocity template to render.
253      *
254      * @param stack the value stack to resolve the location again (when parse
255      *        equals true)
256      * @param velocity the velocity engine to process the request against
257      * @param invocation an encapsulation of the action execution state.
258      * @param location the location of the template
259      * @param encoding the charset encoding of the template
260      * @return the template to render
261      * @throws Exception when the requested template could not be found
262      */
263     protected Template getTemplate(ValueStack stack,
264             VelocityEngine velocity, ActionInvocation invocation,
265             String location, String encoding) throws Exception {
266         if (!location.startsWith("/")) {
267             location = invocation.getProxy().getNamespace() + "/" + location;
268         }
269 
270         Template template = velocity.getTemplate(location, encoding);
271 
272         return template;
273     }
274 
275     /***
276      * Creates the VelocityContext that we'll use to render this page.
277      *
278      * @param velocityManager a reference to the velocityManager to use
279      * @param stack the value stack to resolve the location against (when parse
280      *        equals true)
281      * @param location the name of the template that is being used
282      * @return the a minted Velocity context.
283      */
284     protected Context createContext(VelocityManager velocityManager,
285             ValueStack stack, HttpServletRequest request,
286             HttpServletResponse response, String location) {
287         return velocityManager.createContext(stack, request, response);
288     }
289 }