FreemarkerServlet.java

Index Score
freemarker.ext.servlet
FreeMarker

View: Reasons, Metrics, Source Code

These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.

MetricDescription
JAVA0173JAVA0173 Unused method parameter
SIZESize of the file in bytes
EXEC_COMMENTSComments in executable code
JAVA0160JAVA0160 Method does not throw specified exception
LINE_COMMENTNumber of line comments
JAVA0115JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
COMMENTSComment lines
EXITSProcedure exits
DOC_COMMENTNumber of javadoc comment lines
BLOCKSNumber of blocks
LINESNumber of lines in the source file
UNIQUE_OPERANDSNumber of unique operands
JAVA0150JAVA0150 java.lang.Error (or subclass) thrown
ELOCEffective lines of code
PROGRAM_VOCABHalstead program vocabulary
LOCLines of code
JAVA0233JAVA0233 Definition of serialVersionUID other than 'private static final long serialVersionUID'
CYCLOMATICCyclomatic complexity
OPERANDSNumber of operands
PROGRAM_LENGTHHalstead program length
OPERATORSNumber of operators
JAVA0116JAVA0116 Missing javadoc: field 'field'
LOGICAL_LINESNumber of statements
RETURNSNumber of return points from functions
INTERFACE_COMPLEXITYInterface complexity
COMPARISONSNumber of comparison operators
JAVA0075JAVA0075 Method parameter hides field
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0034JAVA0034 Missing braces in if statement
UNIQUE_OPERATORSNumber of unique operators
JAVA0166JAVA0166 Generic exception caught
PARAMSNumber of formal parameter declarations
PROGRAM_VOLUMEHalstead program volume
JAVA0126JAVA0126 Method declares unchecked exception in throws
JAVA0179JAVA0179 Local variable hides visible field
NEST_DEPTHMaximum nesting depth
JAVA0145JAVA0145 Tab character used in source file
/* * Copyright (c) 2003 The Visigoth Software Society. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowledgement: * "This product includes software developed by the * Visigoth Software Society (http://www.visigoths.org/)." * Alternately, this acknowledgement may appear in the software itself, * if and wherever such third-party acknowledgements normally appear. * * 4. Neither the name "FreeMarker", "Visigoth", nor any of the names of the * project contributors may be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact visigoths@visigoths.org. * * 5. Products derived from this software may not be called "FreeMarker" or "Visigoth" * nor may "FreeMarker" or "Visigoth" appear in their names * without prior written permission of the Visigoth Software Society. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE VISIGOTH SOFTWARE SOCIETY OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Visigoth Software Society. For more * information on the Visigoth Software Society, please see * http://www.visigoths.org/ */ package freemarker.ext.servlet; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Enumeration; import java.util.GregorianCalendar; import java.util.List; import java.util.StringTokenizer; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import freemarker.cache.ClassTemplateLoader; import freemarker.cache.FileTemplateLoader; import freemarker.cache.MultiTemplateLoader; import freemarker.cache.TemplateLoader; import freemarker.cache.WebappTemplateLoader; import freemarker.core.Configurable; import freemarker.ext.jsp.TaglibFactory; import freemarker.log.Logger; import freemarker.template.Configuration; import freemarker.template.ObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import freemarker.template.utility.StringUtil; import java.util.Locale; /** * <p>This is a general-purpose FreeMarker view servlet.</p> * * <p>The main features are: * * <ul> * * <li>It makes all request, request parameters, session, and servlet * context attributes available to templates through <code>Request</code>, * <code>RequestParameters</code>, <code>Session</code>, and <code>Application</code> * variables. * * <li>The scope variables are also available via automatic scope discovery. That is, * writing <code>Application.attrName</code>, <code>Session.attrName</code>, * <code>Request.attrName</code> is not mandatory; it's enough to write <code>attrName</code>, * and if no such variable was created in the template, it will search the * variable in <code>Request</code>, and then in <code>Session</code>, * and finally in <code>Application</code>. * * <li>It creates a variable with name <code>JspTaglibs</code>, that can be used * to load JSP taglibs. For example:<br> * <code>&lt;#assign tiles=JspTaglibs["/WEB-INF/struts-tiles.tld"]></code> * * </ul> * * <p>The servlet will rethrow the errors occurring during template processing, * wrapped into <code>ServletException</code>, except if the class name of the * class set by the <code>template_exception_handler</code> contains the * substring <code>"Debug"</code>. If it contains <code>"Debug"</code>, then it * is assumed that the template exception handler prints the error message to the * page, thus <code>FreemarkerServlet</code> will suppress the exception, and * logs the problem with the servlet logger * (<code>javax.servlet.GenericServlet.log(...)</code>). * * <p>Supported init-params are:</p> * * <ul> * * <li><strong>TemplatePath</strong> specifies the location of the templates. * By default, this is interpreted as web application directory relative URI.<br> * Alternatively, you can prepend it with <tt>file://</tt> to indicate a literal * path in the file system (i.e. <tt>file:///var/www/project/templates/</tt>). * Note that three slashes were used to specify an absolute path.<br> * Also, you can prepend it with <tt>class://path/to/template/package</tt> to * indicate that you want to load templates from the specified package * accessible through the classloader of the servlet.<br> * Default value is <tt>class://</tt> (that is, the root of the class hierarchy). * <i>Note that this default is different than the default in FreeMarker 1.x, when * it defaulted <tt>/</tt>, that is to loading from the webapp root directory.</i> * Note also that you can specify multiple locations, by separating the individual * locations with a comma.</li> * * <li><strong>NoCache</strong> if set to true, generates headers in the response * that advise the HTTP client not to cache the returned page. * The default is <tt>false</tt>.</li> * * <li><strong>ContentType</strong> if specified, response uses the specified * Content-type HTTP header. The value may include the charset (e.g. * <tt>"text/html; charset=ISO-8859-1"</tt>). If not specified, <tt>"text/html"</tt> * is used. If the charset is not specified in this init-param, then the charset * (encoding) of the actual template file will be used (in the response HTTP header * and for encoding the output stream). Note that this setting can be overridden * on a per-template basis by specifying a custom attribute named * <tt>content_type</tt> in the <tt>attributes</tt> parameter of the * <tt>&lt;#ftl></tt> directive. * </li> * * <li>The following init-params are supported only for backward compatibility, and * their usage is discouraged: TemplateUpdateInterval, DefaultEncoding, * ObjectWrapper, TemplateExceptionHandler. Use setting init-params such as * object_wrapper instead. * * <li>Any other init-param will be interpreted as <code>Configuration</code> * level setting. See {@link Configuration#setSetting}</li> * * </ul> * * @author Attila Szegedi * @version $Id: FreemarkerServlet.java,v 1.82 2005/06/13 20:52:56 szegedia Exp $ */ public class FreemarkerServlet extends HttpServlet { private static final Logger logger = Logger.getLogger("freemarker.servlet"); public static final long serialVersionUID = -2440216393145762479L; private static final String INITPARAM_TEMPLATE_PATH = "TemplatePath"; private static final String INITPARAM_NOCACHE = "NoCache"; private static final String INITPARAM_CONTENT_TYPE = "ContentType"; private static final String DEFAULT_CONTENT_TYPE = "text/html"; private static final String INITPARAM_DEBUG = "Debug"; private static final String DEPR_INITPARAM_TEMPLATE_DELAY = "TemplateDelay"; private static final String DEPR_INITPARAM_ENCODING = "DefaultEncoding"; private static final String DEPR_INITPARAM_OBJECT_WRAPPER = "ObjectWrapper"; private static final String DEPR_INITPARAM_WRAPPER_SIMPLE = "simple"; private static final String DEPR_INITPARAM_WRAPPER_BEANS = "beans"; private static final String DEPR_INITPARAM_WRAPPER_JYTHON = "jython"; private static final String DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER = "TemplateExceptionHandler"; private static final String DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER_RETHROW = "rethrow"; private static final String DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER_DEBUG = "debug"; private static final String DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER_HTML_DEBUG = "htmlDebug"; private static final String DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER_IGNORE = "ignore"; private static final String DEPR_INITPARAM_DEBUG = "debug"; public static final String KEY_REQUEST = "Request"; public static final String KEY_REQUEST_PRIVATE = "__FreeMarkerServlet.Request__"; public static final String KEY_REQUEST_PARAMETERS = "RequestParameters"; public static final String KEY_SESSION = "Session"; public static final String KEY_APPLICATION = "Application"; public static final String KEY_APPLICATION_PRIVATE = "__FreeMarkerServlet.Application__"; public static final String KEY_JSP_TAGLIBS = "JspTaglibs"; // Note these names start with dot, so they're essentially invisible from // a freemarker script. private static final String ATTR_REQUEST_MODEL = ".freemarker.Request"; private static final String ATTR_REQUEST_PARAMETERS_MODEL = ".freemarker.RequestParameters"; private static final String ATTR_SESSION_MODEL = ".freemarker.Session"; private static final String ATTR_APPLICATION_MODEL = ".freemarker.Application"; private static final String ATTR_JSP_TAGLIBS_MODEL = ".freemarker.JspTaglibs"; private static final String EXPIRATION_DATE; static { // Generate expiration date that is one year from now in the past GregorianCalendar expiration = new GregorianCalendar(); expiration.roll(Calendar.YEAR, -1); SimpleDateFormat httpDate = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss z", java.util.Locale.US); EXPIRATION_DATE = httpDate.format(expiration.getTime()); } private String templatePath; private boolean nocache; protected boolean debug; private Configuration config; private ObjectWrapper wrapper; private String contentType; private boolean noCharsetInContentType; public void init() throws ServletException { try { config = createConfiguration(); // Set defaults: config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER); contentType = DEFAULT_CONTENT_TYPE; // Process object_wrapper init-param out of order: wrapper = createObjectWrapper(); if (logger.isDebugEnabled()) { logger.debug("Using object wrapper of class " + wrapper.getClass().getName()); } config.setObjectWrapper(wrapper); // Process TemplatePath init-param out of order: templatePath = getInitParameter(INITPARAM_TEMPLATE_PATH); if (templatePath == null) templatePath = "class://"; StringTokenizer tok = new StringTokenizer(templatePath, ","); List<TemplateLoader> loaders = new ArrayList<TemplateLoader>(); while(tok.hasMoreTokens()) { loaders.add(createTemplateLoader(tok.nextToken())); } if(loaders.size() == 1) { config.setTemplateLoader(loaders.get(0)); } else { config.setTemplateLoader(new MultiTemplateLoader( loaders.toArray(new TemplateLoader[loaders.size()]))); } // Process all other init-params: Enumeration initpnames = getServletConfig().getInitParameterNames(); while (initpnames.hasMoreElements()) { String name = (String) initpnames.nextElement(); String value = getInitParameter(name); if (name == null) { throw new ServletException( "init-param without param-name. " + "Maybe the web.xml is not well-formed?"); } if (value == null) { throw new ServletException( "init-param without param-value. " + "Maybe the web.xml is not well-formed?"); } if (name.equals(DEPR_INITPARAM_OBJECT_WRAPPER) || name.equals(Configurable.OBJECT_WRAPPER_KEY) || name.equals(INITPARAM_TEMPLATE_PATH)) { // ignore: we have already processed these } else if (name.equals(DEPR_INITPARAM_ENCODING)) { // BC if (getInitParameter(Configuration.DEFAULT_ENCODING_KEY) != null) { throw new ServletException( "Conflicting init-params: " + Configuration.DEFAULT_ENCODING_KEY + " and " + DEPR_INITPARAM_ENCODING); } config.setDefaultEncoding(value); } else if (name.equals(DEPR_INITPARAM_TEMPLATE_DELAY)) { // BC if (getInitParameter(Configuration.TEMPLATE_UPDATE_DELAY_KEY) != null) { throw new ServletException( "Conflicting init-params: " + Configuration.TEMPLATE_UPDATE_DELAY_KEY + " and " + DEPR_INITPARAM_TEMPLATE_DELAY); } try { config.setTemplateUpdateDelay(Integer.parseInt(value)); } catch (NumberFormatException e) { // Intentionally ignored } } else if (name.equals(DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER)) { // BC if (getInitParameter(Configurable.TEMPLATE_EXCEPTION_HANDLER_KEY) != null) { throw new ServletException( "Conflicting init-params: " + Configurable.TEMPLATE_EXCEPTION_HANDLER_KEY + " and " + DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER); } if (DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER_RETHROW.equals(value)) { config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); } else if (DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER_DEBUG.equals(value)) { config.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER); } else if (DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER_HTML_DEBUG.equals(value)) { config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER); } else if (DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER_IGNORE.equals(value)) { config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); } else { throw new ServletException( "Invalid value for servlet init-param " + DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER + ": " + value); } } else if (name.equals(INITPARAM_NOCACHE)) { nocache = StringUtil.getYesNo(value); } else if (name.equals(DEPR_INITPARAM_DEBUG)) { // BC if (getInitParameter(INITPARAM_DEBUG) != null) { throw new ServletException( "Conflicting init-params: " + INITPARAM_DEBUG + " and " + DEPR_INITPARAM_DEBUG); } debug = StringUtil.getYesNo(value); } else if (name.equals(INITPARAM_DEBUG)) { debug = StringUtil.getYesNo(value); } else if (name.equals(INITPARAM_CONTENT_TYPE)) { contentType = value; } else { config.setSetting(name, value); } } // while initpnames noCharsetInContentType = true; int i = contentType.toLowerCase().indexOf("charset="); if (i != -1) { char c = ' '; i--; while (i >= 0) { c = contentType.charAt(i); if (!Character.isWhitespace(c)) break; i--; } if (i == -1 || c == ';') { noCharsetInContentType = false; } } } catch (ServletException e) { throw e; } catch (Exception e) { throw new ServletException(e); } } /** * Create the template loader. The default implementation will create a * {@link ClassTemplateLoader} if the template path starts with "class://", * a {@link FileTemplateLoader} if the template path starts with "file://", * and a {@link WebappTemplateLoader} otherwise. * @param templatePath the template path to create a loader for * @return a newly created template loader * @throws IOException */ protected TemplateLoader createTemplateLoader(String templatePath) throws IOException { if (templatePath.startsWith("class://")) { // substring(7) is intentional as we "reuse" the last slash return new ClassTemplateLoader(getClass(), templatePath.substring(7)); } else { if (templatePath.startsWith("file://")) { templatePath = templatePath.substring(7); return new FileTemplateLoader(new File(templatePath)); } else { return new WebappTemplateLoader(this.getServletContext(), templatePath); } } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { process(request, response); } public void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { process(request, response); } private void process( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Give chance to subclasses to perform preprocessing if (preprocessRequest(request, response)) { return; } String path = requestUrlToTemplatePath(request); if (debug) { log("Requested template: " + path); } Template template = null; try { template = config.getTemplate( path, deduceLocale(path, request, response)); } catch (FileNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Object attrContentType = template.getCustomAttribute("content_type"); if(attrContentType != null) { response.setContentType(attrContentType.toString()); } else { if (noCharsetInContentType) { response.setContentType( contentType + "; charset=" + template.getEncoding()); } else { response.setContentType(contentType); } } // Set cache policy setBrowserCachingPolicy(response); ServletContext servletContext = getServletContext(); try { TemplateModel model = createModel(wrapper, servletContext, request, response); // Give subclasses a chance to hook into preprocessing if (preTemplateProcess(request, response, template, model)) { try { // Process the template template.process(model, response.getWriter()); } finally { // Give subclasses a chance to hook into postprocessing postTemplateProcess(request, response, template, model); } } } catch (TemplateException te) { if (config.getTemplateExceptionHandler() .getClass().getName().indexOf("Debug") != -1) { this.log("Error executing FreeMarker template", te); } else { ServletException e = new ServletException( "Error executing FreeMarker template", te); // Attempt to set init cause, but don't freak out if the method // is not available (i.e. pre-1.4 JRE). This is required as the // constructor-passed throwable won't show up automatically in // stack traces. try { e.getClass().getMethod("initCause", new Class[] { Throwable.class }).invoke(e, new Object[] { te }); } catch (Exception ex) { // Can't set init cause, we're probably running on a pre-1.4 // JDK, oh well... } throw e; } } } /** * Returns the locale used for the * {@link Configuration#getTemplate(String, Locale)} call. * The base implementation simply returns the locale setting of the * configuration. Override this method to provide different behaviour, i.e. * to use the locale indicated in the request. */ protected Locale deduceLocale( String templatePath, HttpServletRequest request, HttpServletResponse response) { return config.getLocale(); } protected TemplateModel createModel(ObjectWrapper wrapper, ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws TemplateModelException { try { AllHttpScopesHashModel params = new AllHttpScopesHashModel(wrapper, servletContext, request); // Create hash model wrapper for servlet context (the application) ServletContextHashModel servletContextModel = (ServletContextHashModel) servletContext.getAttribute( ATTR_APPLICATION_MODEL); if (servletContextModel == null) { servletContextModel = new ServletContextHashModel(this, wrapper); servletContext.setAttribute( ATTR_APPLICATION_MODEL, servletContextModel); TaglibFactory taglibs = new TaglibFactory(servletContext); servletContext.setAttribute( ATTR_JSP_TAGLIBS_MODEL, taglibs); initializeServletContext(request, response); } params.putUnlistedModel(KEY_APPLICATION, servletContextModel); params.putUnlistedModel(KEY_APPLICATION_PRIVATE, servletContextModel); params.putUnlistedModel(KEY_JSP_TAGLIBS, (TemplateModel)servletContext.getAttribute(ATTR_JSP_TAGLIBS_MODEL)); // Create hash model wrapper for session HttpSessionHashModel sessionModel; HttpSession session = request.getSession(false); if(session != null) { sessionModel = (HttpSessionHashModel) session.getAttribute(ATTR_SESSION_MODEL); if (sessionModel == null || sessionModel.isZombie()) { sessionModel = new HttpSessionHashModel(session, wrapper); session.setAttribute(ATTR_SESSION_MODEL, sessionModel); if(!sessionModel.isZombie()) { initializeSession(request, response); } } } else { sessionModel = new HttpSessionHashModel(this, request, response, wrapper); } params.putUnlistedModel(KEY_SESSION, sessionModel); // Create hash model wrapper for request HttpRequestHashModel requestModel = (HttpRequestHashModel) request.getAttribute(ATTR_REQUEST_MODEL); if (requestModel == null || requestModel.getRequest() != request) { requestModel = new HttpRequestHashModel(request, response, wrapper); request.setAttribute(ATTR_REQUEST_MODEL, requestModel); request.setAttribute( ATTR_REQUEST_PARAMETERS_MODEL, createRequestParametersHashModel(request)); } params.putUnlistedModel(KEY_REQUEST, requestModel); params.putUnlistedModel(KEY_REQUEST_PRIVATE, requestModel); // Create hash model wrapper for request parameters HttpRequestParametersHashModel requestParametersModel = (HttpRequestParametersHashModel) request.getAttribute( ATTR_REQUEST_PARAMETERS_MODEL); params.putUnlistedModel(KEY_REQUEST_PARAMETERS, requestParametersModel); return params; } catch (ServletException e) { throw new TemplateModelException(e); } catch (IOException e) { throw new TemplateModelException(e); } } /** * Maps the request URL to a template path that is passed to * {@link Configuration#getTemplate(String, Locale)}. You can override it * (i.e. to provide advanced rewriting capabilities), but you are strongly * encouraged to call the overridden method first, then only modify its * return value. * @param request the currently processed request * @return a String representing the template path */ protected String requestUrlToTemplatePath(HttpServletRequest request) { // First, see if it is an included request String includeServletPath = (String) request.getAttribute("javax.servlet.include.servlet_path"); if(includeServletPath != null) { // Try path info; only if that's null (servlet is mapped to an // URL extension instead of to prefix) use servlet path. String includePathInfo = (String) request.getAttribute("javax.servlet.include.path_info"); return includePathInfo == null ? includeServletPath : includePathInfo; } // Seems that the servlet was not called as the result of a // RequestDispatcher.include(...). Try pathInfo then servletPath again, // only now directly on the request object: String path = request.getPathInfo(); if (path != null) return path; path = request.getServletPath(); if (path != null) return path; // Seems that it is a servlet mapped with prefix, and there was no extra path info. return ""; } /** * Called as the first step in request processing, before the templating mechanism * is put to work. By default does nothing and returns false. This method is * typically overridden to manage serving of non-template resources (i.e. images) * that reside in the template directory. * @param request the HTTP request * @param response the HTTP response * @return true to indicate this method has processed the request entirely, * and that the further request processing should not take place. */ protected boolean preprocessRequest( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { return false; } /** * This method is called from {@link #init()} to create the * FreeMarker configuration object that this servlet will use * for template loading. This is a hook that allows you * to custom-configure the configuration object in a subclass. * The default implementation returns a new {@link Configuration} * instance. */ protected Configuration createConfiguration() { return new Configuration(); } /** * This method is called from {@link #init()} to create the * FreeMarker object wrapper object that this servlet will use * for adapting request, session, and servlet context attributes into * template models.. This is a hook that allows you * to custom-configure the wrapper object in a subclass. * The default implementation returns a wrapper that depends on the value * of <code>ObjectWrapper</code> init parameter. If <code>simple</code> is * specified, {@link ObjectWrapper#SIMPLE_WRAPPER} is used; if <code>jython</code> * is specified, {@link freemarker.ext.jython.JythonWrapper} is used. In * every other case {@link ObjectWrapper#DEFAULT_WRAPPER} is used. */ protected ObjectWrapper createObjectWrapper() { String wrapper = getServletConfig().getInitParameter(DEPR_INITPARAM_OBJECT_WRAPPER); if (wrapper != null) { // BC if (getInitParameter(Configurable.OBJECT_WRAPPER_KEY) != null) { throw new RuntimeException("Conflicting init-params: " + Configurable.OBJECT_WRAPPER_KEY + " and " + DEPR_INITPARAM_OBJECT_WRAPPER); } if (DEPR_INITPARAM_WRAPPER_BEANS.equals(wrapper)) { return ObjectWrapper.BEANS_WRAPPER; } if(DEPR_INITPARAM_WRAPPER_SIMPLE.equals(wrapper)) { return ObjectWrapper.SIMPLE_WRAPPER; } if(DEPR_INITPARAM_WRAPPER_JYTHON.equals(wrapper)) { // Avoiding compile-time dependency on Jython package try { return (ObjectWrapper) Class.forName("freemarker.ext.jython.JythonWrapper") .newInstance(); } catch (InstantiationException e) { throw new InstantiationError(e.getMessage()); } catch (IllegalAccessException e) { throw new IllegalAccessError(e.getMessage()); } catch (ClassNotFoundException e) { throw new NoClassDefFoundError(e.getMessage()); } } // return BeansWrapper.getDefaultInstance(); return ObjectWrapper.DEFAULT_WRAPPER; } else { wrapper = getInitParameter(Configurable.OBJECT_WRAPPER_KEY); if (wrapper == null) { // return BeansWrapper.getDefaultInstance(); return ObjectWrapper.DEFAULT_WRAPPER; } else { try { config.setSetting(Configurable.OBJECT_WRAPPER_KEY, wrapper); } catch (TemplateException e) { throw new RuntimeException(e.toString()); } return config.getObjectWrapper(); } } } protected ObjectWrapper getObjectWrapper() { return wrapper; } protected final String getTemplatePath() { return templatePath; } protected HttpRequestParametersHashModel createRequestParametersHashModel(HttpServletRequest request) { return new HttpRequestParametersHashModel(request); } /** * Called when servlet detects in a request processing that * application-global (that is, ServletContext-specific) attributes are not yet * set. * This is a generic hook you might use in subclasses to perform a specific * action on first request in the context. By default it does nothing. * @param request the actual HTTP request * @param response the actual HTTP response */ protected void initializeServletContext( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } /** * Called when servlet detects in a request processing that session-global * (that is, HttpSession-specific) attributes are not yet set. * This is a generic hook you might use in subclasses to perform a specific * action on first request in the session. By default it does nothing. It * is only invoked on newly created sessions; it is not invoked when a * replicated session is reinstantiated in another servlet container. * * @param request the actual HTTP request * @param response the actual HTTP response */ protected void initializeSession( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } /** * Called before the execution is passed to template.process(). * This is a generic hook you might use in subclasses to perform a specific * action before the template is processed. By default does nothing. * A typical action to perform here is to inject application-specific * objects into the model root * * <p>Example: Expose the Serlvet context path as "baseDir" for all templates: * *<pre> * ((SimpleHash) data).put("baseDir", request.getContextPath() + "/"); * return true; *</pre> * * @param request the actual HTTP request * @param response the actual HTTP response * @param template the template that will get executed * @param data the data that will be passed to the template. By default this will be * an {@link AllHttpScopesHashModel} (which is a {@link freemarker.template.SimpleHash} subclass). * Thus, you can add new variables to the data-model with the * {@link freemarker.template.SimpleHash#put(String, Object)} subclass) method. * @return true to process the template, false to suppress template processing. */ protected boolean preTemplateProcess( HttpServletRequest request, HttpServletResponse response, Template template, TemplateModel data) throws ServletException, IOException { return true; } /** * Called after the execution returns from template.process(). * This is a generic hook you might use in subclasses to perform a specific * action after the template is processed. It will be invoked even if the * template processing throws an exception. By default does nothing. * @param request the actual HTTP request * @param response the actual HTTP response * @param template the template that was executed * @param data the data that was passed to the template */ protected void postTemplateProcess( HttpServletRequest request, HttpServletResponse response, Template template, TemplateModel data) throws ServletException, IOException { } /** * Returns the {@link freemarker.template.Configuration} object used by this servlet. * Please don't forget that {@link freemarker.template.Configuration} is not thread-safe * when you modify it. */ protected Configuration getConfiguration() { return config; } /** * If the parameter "nocache" was set to true, generate a set of headers * that will advise the HTTP client not to cache the returned page. */ private void setBrowserCachingPolicy(HttpServletResponse res) { if (nocache) { // HTTP/1.1 + IE extensions res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, " + "post-check=0, pre-check=0"); // HTTP/1.0 res.setHeader("Pragma", "no-cache"); // Last resort for those that ignore all of the above res.setHeader("Expires", EXPIRATION_DATE); } } }

The table below shows all metrics for FreemarkerServlet.java.

MetricValueDescription
BLOCKS100.00Number of blocks
BLOCK_COMMENT51.00Number of block comment lines
COMMENTS286.00Comment lines
COMMENT_DENSITY 0.73Comment density
COMPARISONS55.00Number of comparison operators
CYCLOMATIC87.00Cyclomatic complexity
DECL_COMMENTS15.00Comments in declarations
DOC_COMMENT197.00Number of javadoc comment lines
ELOC391.00Effective lines of code
EXEC_COMMENTS29.00Comments in executable code
EXITS86.00Procedure exits
FUNCTIONS20.00Number of function declarations
HALSTEAD_DIFFICULTY71.44Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY85.00Interface complexity
JAVA0001 0.00JAVA0001 Package name does not contain only lower case letters
JAVA0002 1.00JAVA0002 Package name does not begin with a top level domain name or country code
JAVA0003 0.00JAVA0003 Minimize use of on-demand (.*) imports
JAVA0004 0.00JAVA0004 Unnecessary import from java.lang
JAVA0005 1.00JAVA0005 Imports not in specified order
JAVA0006 0.00JAVA0006 Empty finally block
JAVA0007 0.00JAVA0007 Should not declare public field
JAVA0008 0.00JAVA0008 Empty catch block
JAVA0009 0.00JAVA0009 Protected member in final class
JAVA0010 0.00JAVA0010 Non-instantiable class does not contain a non-private static member
JAVA0011 0.00JAVA0011 Abstract class does not contain an abstract method
JAVA0012 0.00JAVA0012 Non-constructor method with same name as declaring class
JAVA0013 0.00JAVA0013 Non-blank final field is not static
JAVA0014 0.00JAVA0014 Class with only static members has non-private constructor
JAVA0015 0.00JAVA0015 Package class contains public nested type
JAVA0016 0.00JAVA0016 Abstract class contains public constructor
JAVA0017 0.00JAVA0017 Class name does not have required form
JAVA0018 0.00JAVA0018 Method name does not have required form
JAVA0019 0.00JAVA0019 Interface name does not have required form
JAVA0020 0.00JAVA0020 Field name does not have required form
JAVA0021 0.00JAVA0021 Interface method name does not have required form
JAVA0022 0.00JAVA0022 Static final field name does not have required form
JAVA0023 0.00JAVA0023 Empty finalize method
JAVA0024 0.00JAVA0024 Empty class
JAVA0025 0.00JAVA0025 Method override is empty
JAVA0026 0.00JAVA0026 Finalize method with parameters
JAVA0029 0.00JAVA0029 Private method not used
JAVA0030 0.00JAVA0030 Private field not used
JAVA0031 0.00JAVA0031 Case statement not properly closed
JAVA0032 0.00JAVA0032 Switch statement missing default
JAVA0033 0.00JAVA0033 default: not last case in switch statement
JAVA0034 4.00JAVA0034 Missing braces in if statement
JAVA0035 0.00JAVA0035 Missing braces in for statement
JAVA0036 0.00JAVA0036 Missing braces in while statement
JAVA0038 0.00JAVA0038 Non-case label in switch statement
JAVA0039 0.00JAVA0039 Break statement with label
JAVA0040 0.00JAVA0040 Switch statement contains N cases (maximum: M)
JAVA0041 0.00JAVA0041 Nested synchronized block
JAVA0042 0.00JAVA0042 Empty synchronized statement
JAVA0043 0.00JAVA0043 Inner class does not use outer class
JAVA0044 0.00JAVA0044 Serializable class with no instance variables
JAVA0045 0.00JAVA0045 Serializable class with only transient fields
JAVA0046 0.00JAVA0046 Name of class not derived from Exception ends with 'Exception'
JAVA0047 0.00JAVA0047 Serializable class derives from invalid base class
JAVA0048 0.00JAVA0048 Name of class derived from Exception does not end with 'Exception'
JAVA0049 0.00JAVA0049 Nested block at depth N (maximum: M)
JAVA0050 0.00JAVA0050 Class derives from java.lang.Error
JAVA0051 0.00JAVA0051 Class derives from java.lang.RuntimeException
JAVA0052 0.00JAVA0052 Class derives from java.lang.Throwable
JAVA0053 0.00JAVA0053 Unused label
JAVA0054 0.00JAVA0054 Inheritance depth N exceeds maximum M
JAVA0055 0.00JAVA0055 Class should be interface
JAVA0056 0.00JAVA0056 Unnecessary abstract modifier for interface or annotation
JAVA0057 0.00JAVA0057 Unnecessary default constructor
JAVA0058 0.00JAVA0058 Constructor calls super()
JAVA0059 0.00JAVA0059 Method override only calls super()
JAVA0061 0.00JAVA0061 Inaccessible member in anonymous class
JAVA0062 0.00JAVA0062 Public class missing public member or protected constructor
JAVA0063 0.00JAVA0063 Identifier name should not contain '$'
JAVA0064 0.00JAVA0064 N variations of identifier name (maximum: M)
JAVA0065 0.00JAVA0065 Unnecessary final modifier for method in final class
JAVA0066 0.00JAVA0066 Unnecessary modifier for interface nested type
JAVA0067 0.00JAVA0067 Array descriptor on identifier name
JAVA0068 0.00JAVA0068 Modifiers not declared in recommended order
JAVA0071 0.00JAVA0071 Strings compared with ==
JAVA0073 0.00JAVA0073 Integer division in floating-point context
JAVA0074 0.00JAVA0074 Use of Object.notify()
JAVA0075 3.00JAVA0075 Method parameter hides field
JAVA0076 2.00JAVA0076 Use of magic number
JAVA0077 0.00JAVA0077 Private field not used in declaring class
JAVA0078 0.00JAVA0078 Floating point values compared with ==
JAVA0079 0.00JAVA0079 Use of instance to reference static member
JAVA0080 0.00JAVA0080 Import declaration not used
JAVA0081 0.00JAVA0081 Boolean literal in comparison
JAVA0082 0.00JAVA0082 Unnecessary widening cast
JAVA0083 0.00JAVA0083 Unnecessary instanceof test
JAVA0084 0.00JAVA0084 Should use compound assignment operator
JAVA0085 0.00JAVA0085 Use of sun.* class
JAVA0087 0.00JAVA0087 Use of Thread.sleep()
JAVA0089 0.00JAVA0089 Use of restricted package
JAVA0092 0.00JAVA0092 Use of restricted type
JAVA0093 0.00JAVA0093 Redundant assignment
JAVA0094 0.00JAVA0094 Field hides a superclass field
JAVA0095 0.00JAVA0095 Uninitialized private field
JAVA0096 0.00JAVA0096 Field in nested class hides outer field
JAVA0098 0.00JAVA0098 Minimize use of implicit field initializers
JAVA0100 0.00JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0101 0.00JAVA0101 Unnecessary modifier for field in interface
JAVA0102 0.00JAVA0102 Last statement in finalize() not super.finalize()
JAVA0103 0.00JAVA0103 Explicit call to finalize()
JAVA0104 0.00JAVA0104 finalize() only calls super.finalize()
JAVA0105 0.00JAVA0105 Duplicate import declaration
JAVA0106 0.00JAVA0106 Unnecessary import from current package
JAVA0108 4.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 0.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0110 4.00JAVA0110 Incorrect javadoc: no @return tag
JAVA0111 0.00JAVA0111 Incorrect javadoc: @return tag for void method
JAVA0112 0.00JAVA0112 Incorrect javadoc: no exception 'exception' in throws
JAVA0113 0.00JAVA0113 Incorrect javadoc: no @author tag
JAVA0114 0.00JAVA0114 Incorrect javadoc: no @version tag
JAVA011510.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 8.00JAVA0116 Missing javadoc: field 'field'
JAVA0117 4.00JAVA0117 Missing javadoc: method 'method'
JAVA0118 0.00JAVA0118 Missing javadoc: type 'type'
JAVA0119 0.00JAVA0119 Control variable changed within body of for loop
JAVA0123 0.00JAVA0123 Use all three components of for loop
JAVA0125 0.00JAVA0125 Continue statement with label
JAVA0126 0.00JAVA0126 Method declares unchecked exception in throws
JAVA0128 0.00JAVA0128 Public constructor in non-public class
JAVA0130 0.00JAVA0130 Non-static method does not use instance fields
JAVA0131 0.00JAVA0131 Compatible method does not override base
JAVA0132 0.00JAVA0132 Method overload with compatible signature
JAVA0133 0.00JAVA0133 Non-synchronized method overrides synchronized method
JAVA0135 0.00JAVA0135 Only one of Object.equals and Object.hashCode defined: missing 'method'
JAVA0136 0.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 1.00JAVA0137 Non-abstract class missing constructor
JAVA0138 0.00JAVA0138 N parameters defined for method (maximum: M)
JAVA0139 0.00JAVA0139 Definition of main other than public static void main(java.lang.String[])
JAVA0141 0.00JAVA0141 Unnecessary modifier for method in interface
JAVA0143 0.00JAVA0143 Synchronized method
JAVA0144 0.00JAVA0144 Line exceeds maximum M characters
JAVA0145 0.00JAVA0145 Tab character used in source file
JAVA0150 3.00JAVA0150 java.lang.Error (or subclass) thrown
JAVA0153 0.00JAVA0153 Inefficient conversion of integer to string
JAVA0159 0.00JAVA0159 Inefficient conversion of string to integer
JAVA016010.00JAVA0160 Method does not throw specified exception
JAVA0161 0.00JAVA0161 Conditional wait() not in loop
JAVA0163 0.00JAVA0163 Empty statement
JAVA0165 0.00JAVA0165 Conflicting return statement in finally block
JAVA0166 2.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 0.00JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0171 0.00JAVA0171 Unused local variable
JAVA017317.00JAVA0173 Unused method parameter
JAVA0174 0.00JAVA0174 Assigned local variable never used
JAVA0175 0.00JAVA0175 Successive assignment to variable
JAVA0176 0.00JAVA0176 Local variable name does not have required form
JAVA0177 1.00JAVA0177 Variable declaration missing initializer
JAVA0179 1.00JAVA0179 Local variable hides visible field
JAVA0233 1.00JAVA0233 Definition of serialVersionUID other than 'private static final long serialVersionUID'
JAVA0234 0.00JAVA0234 Class is Serializable but does not define serialVersionUID
JAVA0235 0.00JAVA0235 Class defines serialVersionUID but does not implement Serializable
JAVA0236 0.00JAVA0236 Attempt to clone an object which does not implement Cloneable
JAVA0237 0.00JAVA0237 Class implements Cloneable but does not have public clone method
JAVA0238 0.00JAVA0238 Clone method does not call super.clone()
JAVA0239 0.00JAVA0239 Class declares 'readObject' or 'writeObject' but does not implement Serializable
JAVA0240 0.00JAVA0240 Serializable class which declares readObject or writeObject but not both
JAVA0241 0.00JAVA0241 'readObject' or 'writeObject' should be declared private in Serializable class
JAVA0242 0.00JAVA0242 Transient field in non-Serializable class
JAVA0243 0.00JAVA0243 'readResolve' or 'writeReplace' should be declared private or protected
JAVA0244 0.00JAVA0244 Field or method name in subclass differs only by case from inherited field or method
JAVA0245 0.00JAVA0245 JUnit TestCase with non-trivial constructor
JAVA0246 0.00JAVA0246 JUnit assertXXX statement missing message parameter
JAVA0247 0.00JAVA0247 JUnit 'setUp()' and 'tearDown()' should call super method
JAVA0248 0.00JAVA0248 JUnit method 'setUp' or 'tearDown' with incorrect signature
JAVA0249 0.00JAVA0249 JUnit TestCase 'suite()' should be declared static
JAVA0250 0.00JAVA0250 JUnit TestCase declares testXXX method with incorrect signature
JAVA0251 0.00JAVA0251 Use '%n' for line breaks in printf/format for platform independence
JAVA0252 0.00JAVA0252 'enum' is a Java 1.5 reserved word
JAVA0253 0.00JAVA0253 Not all enum constants consumed in switch statement
JAVA0254 0.00JAVA0254 Use enhanced for loop construct instead of Iterator
JAVA0255 0.00JAVA0255 Result of method invocation not used
JAVA0256 0.00JAVA0256 Assignment of external collection/array to field
JAVA0257 0.00JAVA0257 Use of 'Constant Interface' anti-pattern
JAVA0258 0.00JAVA0258 Implement Iterable for foreach compatibility
JAVA0259 0.00JAVA0259 Return of collection/array field
JAVA0260 0.00JAVA0260 Use 'enum' instead of Enumerated Type pattern
JAVA0261 0.00JAVA0261 Use specialized Enum collection types
JAVA0262 0.00JAVA0262 Use of char in integer context
JAVA0263 0.00JAVA0263 Long literal ends with 'l' instead of 'L'
JAVA0264 0.00JAVA0264 Integer math in long context - check for overflow
JAVA0265 0.00JAVA0265 Use of Throwable.printStackTrace()
JAVA0266 0.00JAVA0266 Use of System.out
JAVA0267 0.00JAVA0267 Use of System.err
JAVA0269 0.00JAVA0269 Contents of StringBuffer never used
JAVA0270 0.00JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0271 0.00JAVA0271 Minimize use of on-demand (.*) static imports
JAVA0272 0.00JAVA0272 Thread.run() called
JAVA0273 0.00JAVA0273 Non-final derivative of Thread calls start() in constructor
JAVA0274 0.00JAVA0274 Serializable class has a synchronized readObject()
JAVA0275 0.00JAVA0275 Serializable class has a synchronized writeObject() and no other synchronized methods
JAVA0276 0.00JAVA0276 Unnecessary use of String constructor
JAVA0277 0.00JAVA0277 Iterator.next() implementation does not throw NoSuchElementException
JAVA0278 0.00JAVA0278 Unnecessary use of Boolean constructor
JAVA0279 0.00JAVA0279 Serialization method readObject or readObjectNoData calls an overridable method
JAVA0280 0.00JAVA0280 IllegalMonitorStateException caught
JAVA0281 0.00JAVA0281 Iterator.next() not called in loop
JAVA0282 0.00JAVA0282 Call to Iterator.next() in loop which does not test Iterator.hasNext()
JAVA0283 0.00JAVA0283 Control variable not updated in loop body
JAVA0284 0.00JAVA0284 Explicit garbage collection
JAVA0285 0.00JAVA0285 Dereference of potentially null variable
JAVA0286 0.00JAVA0286 Dereference of null variable
JAVA0287 0.00JAVA0287 Unnecessary null check
JAVA0288 0.00JAVA0288 Inconsistent null check
LINES815.00Number of lines in the source file
LINE_COMMENT38.00Number of line comments
LOC477.00Lines of code
LOGICAL_LINES209.00Number of statements
LOOPS 3.00Number of loops
NEST_DEPTH 5.00Maximum nesting depth
OPERANDS975.00Number of operands
OPERATORS1787.00Number of operators
PARAMS31.00Number of formal parameter declarations
PROGRAM_LENGTH2762.00Halstead program length
PROGRAM_VOCAB399.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS54.00Number of return points from functions
SIZE37129.00Size of the file in bytes
UNIQUE_OPERANDS348.00Number of unique operands
UNIQUE_OPERATORS51.00Number of unique operators
WHITESPACE52.00Number of whitespace lines