KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > infoglue > deliver > util > VelocityTemplateProcessor


1 /* ===============================================================================
2  *
3  * Part of the InfoGlue Content Management Platform (www.infoglue.org)
4  *
5  * ===============================================================================
6  *
7  * Copyright (C)
8  *
9  * This program is free software; you can redistribute it and/or modify it under
10  * the terms of the GNU General Public License version 2, as published by the
11  * Free Software Foundation. See the file LICENSE.html for more information.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
19  * Place, Suite 330 / Boston, MA 02111-1307 / USA.
20  *
21  * ===============================================================================
22  */

23
24 package org.infoglue.deliver.util;
25
26 import java.io.File JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.PrintWriter JavaDoc;
29 import java.io.Reader JavaDoc;
30 import java.io.StringReader JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.Map JavaDoc;
33
34 import javax.servlet.RequestDispatcher JavaDoc;
35 import javax.servlet.ServletException JavaDoc;
36
37 import org.apache.log4j.Logger;
38 import org.apache.velocity.VelocityContext;
39 import org.apache.velocity.app.Velocity;
40 import org.infoglue.cms.io.FileHelper;
41 import org.infoglue.cms.util.CmsPropertyHandler;
42 import org.infoglue.deliver.applications.databeans.DeliveryContext;
43 import org.infoglue.deliver.controllers.kernel.impl.simple.TemplateController;
44
45 /**
46  *
47  * @author Mattias Bogeblad
48  */

49
50 public class VelocityTemplateProcessor
51 {
52     private final static Logger logger = Logger.getLogger(VelocityTemplateProcessor.class.getName());
53
54     /**
55      * This method takes arguments and renders a template given as a string to the specified outputstream.
56      * Improve later - cache for example the engine.
57      */

58     
59     public void renderTemplate(Map JavaDoc params, PrintWriter JavaDoc pw, String JavaDoc templateAsString) throws Exception JavaDoc
60     {
61         renderTemplate(params, pw, templateAsString, false);
62     }
63     
64     /**
65      * This method takes arguments and renders a template given as a string to the specified outputstream.
66      * Improve later - cache for example the engine.
67      */

68     
69     public void renderTemplate(Map JavaDoc params, PrintWriter JavaDoc pw, String JavaDoc templateAsString, boolean forceVelocity) throws Exception JavaDoc
70     {
71         try
72         {
73             Timer timer = new Timer();
74             timer.setActive(false);
75             
76             if(templateAsString.indexOf("<%") > -1 || templateAsString.indexOf("http://java.sun.com/products/jsp/dtd/jspcore_1_0.dtd") > -1)
77             {
78                 dispatchJSP(params, pw, templateAsString);
79             }
80             else
81             {
82                 boolean useFreeMarker = false;
83                 String JavaDoc useFreeMarkerString = CmsPropertyHandler.getUseFreeMarker();
84                 if(useFreeMarkerString != null && useFreeMarkerString.equalsIgnoreCase("true"))
85                     useFreeMarker = true;
86                 
87                 if((useFreeMarker || templateAsString.indexOf("<#-- IG:FreeMarker -->") > -1) && !forceVelocity)
88                 {
89                     FreemarkerTemplateProcessor.getProcessor().renderTemplate(params, pw, templateAsString);
90                 }
91                 else
92                 {
93                     Velocity.init();
94             
95                     VelocityContext context = new VelocityContext();
96                     Iterator JavaDoc i = params.keySet().iterator();
97                     while(i.hasNext())
98                     {
99                         String JavaDoc key = (String JavaDoc)i.next();
100                         context.put(key, params.get(key));
101                     }
102                     
103                     Reader JavaDoc reader = new StringReader JavaDoc(templateAsString);
104                     boolean finished = Velocity.evaluate(context, pw, "Generator Error", reader);
105                 }
106             }
107
108             timer.printElapsedTime("End renderTemplate");
109         }
110         catch(Exception JavaDoc e)
111         {
112             logger.warn("templateAsString: \n" + (templateAsString.length() > 500 ? templateAsString.substring(0, 500) + "... (template truncated)." : templateAsString));
113             
114             if(CmsPropertyHandler.getOperatingMode().equalsIgnoreCase("0") && (CmsPropertyHandler.getDisableTemplateDebug() == null || !CmsPropertyHandler.getDisableTemplateDebug().equalsIgnoreCase("true")))
115                 pw.println("Error:" + e.getMessage());
116             else
117             {
118                 logger.warn("Warning:" + e.getMessage(), e);
119                 throw e;
120             }
121         }
122     }
123
124     /**
125      * This methods renders a template which is written in JSP. The string is written to disk and then called.
126      *
127      * @param params
128      * @param pw
129      * @param templateAsString
130      * @throws ServletException
131      * @throws IOException
132      */

133
134     public void dispatchJSP(Map JavaDoc params, PrintWriter JavaDoc pw, String JavaDoc templateAsString) throws ServletException JavaDoc, IOException JavaDoc, Exception JavaDoc
135     {
136         Timer timer = new Timer();
137         timer.setActive(false);
138
139         int hashCode = templateAsString.hashCode();
140
141         String JavaDoc contextRootPath = CmsPropertyHandler.getContextRootPath();
142         String JavaDoc fileName = contextRootPath + "jsp" + File.separator + "Template_" + hashCode + ".jsp";
143         
144         File JavaDoc template = new File JavaDoc(fileName);
145         if(!template.exists())
146             FileHelper.writeToFile(template, templateAsString, false);
147         
148         TemplateController templateController = (TemplateController)params.get("templateLogic");
149         DeliveryContext deliveryContext = templateController.getDeliveryContext();
150         RequestDispatcher JavaDoc dispatch = templateController.getHttpServletRequest().getRequestDispatcher("/jsp/Template_" + hashCode + ".jsp");
151         templateController.getHttpServletRequest().setAttribute("org.infoglue.cms.deliver.templateLogic", templateController);
152         CharResponseWrapper wrapper = new CharResponseWrapper(deliveryContext.getHttpServletResponse());
153         
154         dispatch.include(templateController.getHttpServletRequest(), wrapper);
155
156         String JavaDoc result = wrapper.toString();
157
158         pw.println(result);
159     }
160     
161 }
162
Popular Tags