001package org.apache.turbine.services.jsp;
002
003
004/*
005 * Licensed to the Apache Software Foundation (ASF) under one
006 * or more contributor license agreements.  See the NOTICE file
007 * distributed with this work for additional information
008 * regarding copyright ownership.  The ASF licenses this file
009 * to you under the Apache License, Version 2.0 (the
010 * "License"); you may not use this file except in compliance
011 * with the License.  You may obtain a copy of the License at
012 *
013 *   http://www.apache.org/licenses/LICENSE-2.0
014 *
015 * Unless required by applicable law or agreed to in writing,
016 * software distributed under the License is distributed on an
017 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
018 * KIND, either express or implied.  See the License for the
019 * specific language governing permissions and limitations
020 * under the License.
021 */
022
023
024import java.io.File;
025import java.io.IOException;
026import java.util.Arrays;
027
028import javax.servlet.RequestDispatcher;
029import javax.servlet.http.HttpServletRequest;
030
031import org.apache.commons.configuration2.Configuration;
032import org.apache.commons.lang3.StringUtils;
033import org.apache.logging.log4j.LogManager;
034import org.apache.logging.log4j.Logger;
035import org.apache.turbine.Turbine;
036import org.apache.turbine.pipeline.PipelineData;
037import org.apache.turbine.services.InitializationException;
038import org.apache.turbine.services.pull.ApplicationTool;
039import org.apache.turbine.services.pull.tools.TemplateLink;
040import org.apache.turbine.services.template.BaseTemplateEngineService;
041import org.apache.turbine.util.RunData;
042import org.apache.turbine.util.TurbineException;
043
044/**
045 * This is a Service that can process JSP templates from within a Turbine
046 * screen.
047 *
048 * @author <a href="mailto:john.mcnally@clearink.com">John D. McNally</a>
049 * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
050 * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
051 * @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a>
052 */
053public class TurbineJspService
054        extends BaseTemplateEngineService
055        implements JspService
056{
057    /** The base path[s] prepended to filenames given in arguments */
058    private String[] templatePaths;
059
060    /** The relative path[s] prepended to filenames */
061    private String[] relativeTemplatePaths;
062
063    /** The buffer size for the output stream. */
064    private int bufferSize;
065
066    /** Logging */
067    private static Logger log = LogManager.getLogger(TurbineJspService.class);
068
069    /**
070     * Load all configured components and initialize them. This is
071     * a zero parameter variant which queries the Turbine Servlet
072     * for its config.
073     *
074     * @throws InitializationException Something went wrong in the init
075     *         stage
076     */
077    @Override
078    public void init()
079        throws InitializationException
080    {
081        try
082        {
083            initJsp();
084            registerConfiguration(JspService.JSP_EXTENSION);
085            setInit(true);
086        }
087        catch (Exception e)
088        {
089            throw new InitializationException(
090                "TurbineJspService failed to initialize", e);
091        }
092    }
093
094    /**
095     * Adds some convenience objects to the request.  For example an instance
096     * of TemplateLink which can be used to generate links to other templates.
097     *
098     * @param pipelineData the Turbine PipelineData object
099     */
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}