View Javadoc
1   package com.atlassian.refapp.auth.internal;
2   
3   
4   import org.apache.velocity.Template;
5   import org.apache.velocity.VelocityContext;
6   import org.apache.velocity.app.Velocity;
7   import org.apache.velocity.app.VelocityEngine;
8   import org.apache.velocity.runtime.log.JdkLogChute;
9   import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
10  import org.apache.velocity.tools.generic.EscapeTool;
11  
12  import javax.servlet.ServletConfig;
13  import javax.servlet.ServletException;
14  import javax.servlet.http.HttpServlet;
15  
16  abstract class BaseVelocityServlet extends HttpServlet {
17      // JavaDocs say this is threadsafe & stateless, so might as well share an instance
18      // http://velocity.apache.org/tools/releases/1.3/javadoc/org/apache/velocity/tools/generic/EscapeTool.html
19      private static final EscapeTool ESCAPE_TOOL = new EscapeTool();
20  
21      private final VelocityEngine velocity;
22  
23      public BaseVelocityServlet() {
24          velocity = new VelocityEngine();
25          velocity.addProperty(Velocity.RUNTIME_LOG_LOGSYSTEM_CLASS, JdkLogChute.class.getName());
26          velocity.addProperty(Velocity.RESOURCE_LOADER, "classpath");
27          velocity.addProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
28      }
29  
30  
31      @Override
32      public void init(ServletConfig config) throws ServletException {
33          try {
34              velocity.init();
35          } catch (Exception e) {
36              throw new ServletException(e);
37          }
38      }
39  
40      VelocityContext createDefaultVelocityContext() {
41          final VelocityContext context = new VelocityContext();
42          context.put("esc", ESCAPE_TOOL);
43          return context;
44      }
45  
46      Template getTemplate(final String templateName) throws ServletException {
47          try {
48              return velocity.getTemplate(templateName);
49          } catch (Exception e) {
50              throw new ServletException(e);
51          }
52      }
53  }