View Javadoc
1   package org.apache.turbine.services.jsp;
2   
3   
4   /*
5    * Licensed to the Apache Software Foundation (ASF) under one
6    * or more contributor license agreements.  See the NOTICE file
7    * distributed with this work for additional information
8    * regarding copyright ownership.  The ASF licenses this file
9    * to you under the Apache License, Version 2.0 (the
10   * "License"); you may not use this file except in compliance
11   * with the License.  You may obtain a copy of the License at
12   *
13   *   http://www.apache.org/licenses/LICENSE-2.0
14   *
15   * Unless required by applicable law or agreed to in writing,
16   * software distributed under the License is distributed on an
17   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
18   * KIND, either express or implied.  See the License for the
19   * specific language governing permissions and limitations
20   * under the License.
21   */
22  
23  
24  import java.io.File;
25  import java.io.IOException;
26  import java.util.Arrays;
27  
28  import javax.servlet.RequestDispatcher;
29  import javax.servlet.http.HttpServletRequest;
30  
31  import org.apache.commons.configuration2.Configuration;
32  import org.apache.commons.lang3.StringUtils;
33  import org.apache.logging.log4j.LogManager;
34  import org.apache.logging.log4j.Logger;
35  import org.apache.turbine.Turbine;
36  import org.apache.turbine.pipeline.PipelineData;
37  import org.apache.turbine.services.InitializationException;
38  import org.apache.turbine.services.pull.ApplicationTool;
39  import org.apache.turbine.services.pull.tools.TemplateLink;
40  import org.apache.turbine.services.template.BaseTemplateEngineService;
41  import org.apache.turbine.util.RunData;
42  import org.apache.turbine.util.TurbineException;
43  
44  /**
45   * This is a Service that can process JSP templates from within a Turbine
46   * screen.
47   *
48   * @author <a href="mailto:john.mcnally@clearink.com">John D. McNally</a>
49   * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
50   * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
51   * @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a>
52   */
53  public class TurbineJspService
54          extends BaseTemplateEngineService
55          implements JspService
56  {
57      /** The base path[s] prepended to filenames given in arguments */
58      private String[] templatePaths;
59  
60      /** The relative path[s] prepended to filenames */
61      private String[] relativeTemplatePaths;
62  
63      /** The buffer size for the output stream. */
64      private int bufferSize;
65  
66      /** Logging */
67      private static Logger log = LogManager.getLogger(TurbineJspService.class);
68  
69      /**
70       * Load all configured components and initialize them. This is
71       * a zero parameter variant which queries the Turbine Servlet
72       * for its config.
73       *
74       * @throws InitializationException Something went wrong in the init
75       *         stage
76       */
77      @Override
78      public void init()
79          throws InitializationException
80      {
81          try
82          {
83              initJsp();
84              registerConfiguration(JspService.JSP_EXTENSION);
85              setInit(true);
86          }
87          catch (Exception e)
88          {
89              throw new InitializationException(
90                  "TurbineJspService failed to initialize", e);
91          }
92      }
93  
94      /**
95       * Adds some convenience objects to the request.  For example an instance
96       * of TemplateLink which can be used to generate links to other templates.
97       *
98       * @param pipelineData the Turbine PipelineData object
99       */
100     @Override
101     public void addDefaultObjects(PipelineData pipelineData)
102     {
103         HttpServletRequest req = pipelineData.get(Turbine.class, HttpServletRequest.class);
104 
105         //
106         // This is a place where an Application Pull Tool is used
107         // in a regular Java Context. We have no Pull Service with the
108         // Jsp Paging stuff, but we can run our Application Tool by Hand:
109         //
110         ApplicationTool templateLink = new TemplateLink();
111         templateLink.init(pipelineData);
112 
113         req.setAttribute(LINK, templateLink);
114         req.setAttribute(PIPELINE_DATA, pipelineData);
115     }
116 
117     /**
118      * Returns the default buffer size of the JspService
119      *
120      * @return The default buffer size.
121      */
122     @Override
123     public int getDefaultBufferSize()
124     {
125         return bufferSize;
126     }
127 
128     /**
129      * executes the JSP given by templateName.
130      *
131      * @param pipelineData A PipelineData Object
132      * @param templateName The template to execute
133      * @param isForward whether to perform a forward or include.
134      *
135      * @throws TurbineException If a problem occurred while executing the JSP
136      */
137     @Override
138     public void handleRequest(PipelineData pipelineData, String templateName, boolean isForward)
139         throws TurbineException
140     {
141         if(!(pipelineData instanceof RunData))
142         {
143             throw new RuntimeException("Can't cast to rundata from pipeline data.");
144         }
145 
146         RunData data = (RunData)pipelineData;
147 
148         /** template name with relative path */
149         String relativeTemplateName = getRelativeTemplateName(templateName);
150 
151         if (StringUtils.isEmpty(relativeTemplateName))
152         {
153             throw new TurbineException(
154                 "Template " + templateName + " not found in template paths");
155         }
156 
157         // get the RequestDispatcher for the JSP
158         RequestDispatcher dispatcher = data.getServletContext()
159             .getRequestDispatcher(relativeTemplateName);
160 
161         try
162         {
163             if (isForward)
164             {
165                 // forward the request to the JSP
166                 dispatcher.forward(data.getRequest(), data.getResponse());
167             }
168             else
169             {
170                 data.getResponse().getWriter().flush();
171                 // include the JSP
172                 dispatcher.include(data.getRequest(), data.getResponse());
173             }
174         }
175         catch (Exception e)
176         {
177             // Let's try hard to send the error message to the browser, to speed up debugging
178             try
179             {
180                 data.getResponse().getWriter().print("Error encountered processing a template: "
181                     + templateName);
182                 e.printStackTrace(data.getResponse().getWriter());
183             }
184             catch (IOException ignored)
185             {
186                 // ignore
187             }
188 
189             // pass the exception to the caller according to the general
190             // contract for templating services in Turbine
191             throw new TurbineException(
192                 "Error encountered processing a template: " + templateName, e);
193         }
194     }
195 
196     /**
197      * executes the JSP given by templateName.
198      *
199      * @param pipelineData A PipelineData Object
200      * @param templateName The template to execute
201      *
202      * @throws TurbineException If a problem occurred while executing the JSP
203      */
204     @Override
205     public void handleRequest(PipelineData pipelineData, String templateName)
206         throws TurbineException
207     {
208         handleRequest(pipelineData, templateName, false);
209     }
210 
211     /**
212      * This method sets up the template cache.
213      */
214     private void initJsp()
215         throws Exception
216     {
217         Configuration config = getConfiguration();
218 
219         // Set relative paths from config.
220         // Needed for javax.servlet.RequestDispatcher
221         relativeTemplatePaths = config.getStringArray(TEMPLATE_PATH_KEY);
222 
223         // Use Turbine Servlet to translate the template paths.
224         templatePaths = new String [relativeTemplatePaths.length];
225         for (int i=0; i < relativeTemplatePaths.length; i++)
226         {
227             relativeTemplatePaths[i] = warnAbsolute(relativeTemplatePaths[i]);
228 
229             templatePaths[i] = Turbine.getRealPath(relativeTemplatePaths[i]);
230         }
231 
232         bufferSize = config.getInt(JspService.BUFFER_SIZE_KEY,
233             JspService.BUFFER_SIZE_DEFAULT);
234     }
235 
236     /**
237      * Determine whether a given template is available on the
238      * configured template pathes.
239      *
240      * @param template The name of the requested Template
241      * @return True if the template is available.
242      */
243     @Override
244     public boolean templateExists(String template)
245     {
246         return Arrays.stream(templatePaths).anyMatch(templatePath -> templateExists(templatePath, template));
247     }
248 
249     /**
250      * Determine whether a given template exists on the supplied
251      * template path. This service ATM only supports file based
252      * templates so it simply checks for file existence.
253      *
254      * @param path The absolute (file system) template path
255      * @param template The name of the requested Template
256      * @return True if the template is available.
257      */
258     private boolean templateExists(String path, String template)
259     {
260         return new File(path, template).exists();
261     }
262 
263     /**
264      * Searches for a template in the default.template path[s] and
265      * returns the template name with a relative path which is
266      * required by <a href="http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContext.html#getRequestDispatcher(java.lang.String)">
267      * javax.servlet.RequestDispatcher</a>
268      *
269      * @param template the name of the template
270      * @return String
271      */
272     @Override
273     public String getRelativeTemplateName(String template)
274     {
275         String relativeTemplate = warnAbsolute(template);
276 
277         // Find which template path the template is in
278         // We have a 1:1 match between relative and absolute
279         // pathes so we can use the index for translation.
280         for (int i = 0; i < templatePaths.length; i++)
281         {
282             if (templateExists(templatePaths[i], relativeTemplate))
283             {
284                 return relativeTemplatePaths[i] + "/" + relativeTemplate;
285             }
286         }
287         return null;
288     }
289 
290     /**
291      * Warn if a template name or path starts with "/".
292      *
293      * @param template The template to test
294      * @return The template name with a leading / stripped off
295      */
296     private String warnAbsolute(String template)
297     {
298         if (template.startsWith("/"))
299         {
300             log.warn("Template {} has a leading /, which is wrong!", template);
301             return template.substring(1);
302         }
303         return template;
304     }
305 }