Save This Page
Home » apache-ofbiz-09.04 » org.ofbiz.base.util.template » [javadoc | source]
    1   /*******************************************************************************
    2    * Licensed to the Apache Software Foundation (ASF) under one
    3    * or more contributor license agreements.  See the NOTICE file
    4    * distributed with this work for additional information
    5    * regarding copyright ownership.  The ASF licenses this file
    6    * to you under the Apache License, Version 2.0 (the
    7    * "License"); you may not use this file except in compliance
    8    * with the License.  You may obtain a copy of the License at
    9    *
   10    * http://www.apache.org/licenses/LICENSE-2.0
   11    *
   12    * Unless required by applicable law or agreed to in writing,
   13    * software distributed under the License is distributed on an
   14    * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   15    * KIND, either express or implied.  See the License for the
   16    * specific language governing permissions and limitations
   17    * under the License.
   18    *******************************************************************************/
   19   package org.ofbiz.base.util.template;
   20   
   21   import java.io.IOException;
   22   import java.io.InputStream;
   23   import java.io.InputStreamReader;
   24   import java.io.PrintWriter;
   25   import java.io.Reader;
   26   import java.io.StringReader;
   27   import java.io.StringWriter;
   28   import java.io.Writer;
   29   import java.net.MalformedURLException;
   30   import java.net.URL;
   31   import java.util.ArrayList;
   32   import java.util.Date;
   33   import java.util.Enumeration;
   34   import java.util.Iterator;
   35   import java.util.List;
   36   import java.util.Locale;
   37   import java.util.Map;
   38   import java.util.Properties;
   39   import java.util.Set;
   40   import java.util.TimeZone;
   41   
   42   import javax.servlet.ServletContext;
   43   import javax.servlet.http.HttpServletRequest;
   44   
   45   import javolution.util.FastList;
   46   import javolution.util.FastMap;
   47   
   48   import org.ofbiz.base.location.FlexibleLocation;
   49   import org.ofbiz.base.util.Debug;
   50   import org.ofbiz.base.util.StringUtil;
   51   import org.ofbiz.base.util.UtilGenerics;
   52   import org.ofbiz.base.util.UtilMisc;
   53   import org.ofbiz.base.util.UtilProperties;
   54   import org.ofbiz.base.util.UtilValidate;
   55   import org.ofbiz.base.util.StringUtil.SimpleEncoder;
   56   import org.ofbiz.base.util.cache.UtilCache;
   57   
   58   import freemarker.cache.TemplateLoader;
   59   import freemarker.core.Environment;
   60   import freemarker.ext.beans.BeanModel;
   61   import freemarker.ext.beans.BeansWrapper;
   62   import freemarker.template.Configuration;
   63   import freemarker.template.SimpleHash;
   64   import freemarker.template.SimpleScalar;
   65   import freemarker.template.Template;
   66   import freemarker.template.TemplateException;
   67   import freemarker.template.TemplateExceptionHandler;
   68   import freemarker.template.TemplateModel;
   69   import freemarker.template.TemplateModelException;
   70   
   71   /** FreeMarkerWorker - Freemarker Template Engine Utilities.
   72    *
   73    */
   74   public class FreeMarkerWorker {
   75   
   76       public static final String module = FreeMarkerWorker.class.getName();
   77   
   78       // use soft references for this so that things from Content records don't kill all of our memory, or maybe not for performance reasons... hmmm, leave to config file...
   79       public static UtilCache<String, Template> cachedTemplates = new UtilCache<String, Template>("template.ftl.general", 0, 0, false);
   80       protected static BeansWrapper defaultOfbizWrapper = BeansWrapper.getDefaultInstance();
   81       protected static Configuration defaultOfbizConfig = makeConfiguration(defaultOfbizWrapper);
   82   
   83       public static Configuration makeConfiguration(BeansWrapper wrapper) {
   84           Configuration newConfig = new Configuration();
   85   
   86           newConfig.setObjectWrapper(wrapper);
   87           newConfig.setSharedVariable("Static", wrapper.getStaticModels());
   88           newConfig.setLocalizedLookup(false);
   89           newConfig.setSharedVariable("StringUtil", new BeanModel(new StringUtil(), wrapper));
   90           newConfig.setTemplateLoader(new FlexibleTemplateLoader());
   91           newConfig.setTemplateExceptionHandler(new FreeMarkerWorker.OFBizTemplateExceptionHandler());
   92           try {
   93               newConfig.setSetting("datetime_format", "yyyy-MM-dd HH:mm:ss.SSS");
   94               newConfig.setSetting("number_format", "0.##########");
   95           } catch (TemplateException e) {
   96               Debug.logError("Unable to set date/time and number formats in FreeMarker: " + e, module);
   97           }
   98           // Transforms properties file set up as key=transform name, property=transform class name
   99           ClassLoader loader = Thread.currentThread().getContextClassLoader();
  100           Enumeration<URL> resources;
  101           try {
  102               resources = loader.getResources("freemarkerTransforms.properties");
  103           } catch (IOException e) {
  104               Debug.logError(e, "Could not load list of freemarkerTransforms.properties", module);
  105               throw (InternalError) new InternalError(e.getMessage()).initCause(e);
  106           }
  107           while (resources.hasMoreElements()) {
  108               URL propertyURL = resources.nextElement();
  109               Debug.logInfo("loading properties: " + propertyURL, module);
  110               Properties props = UtilProperties.getProperties(propertyURL);
  111               if (props == null || props.isEmpty()) {
  112                   Debug.logError("Unable to locate properties file " + propertyURL, module);
  113               } else {
  114                   loadTransforms(loader, props, newConfig);
  115               }
  116           }
  117   
  118           return newConfig;
  119       }
  120   
  121       /**
  122        * Protected helper method.
  123        */
  124       protected static void loadTransforms(ClassLoader loader, Properties props, Configuration config) {
  125           for (Iterator<Object> i = props.keySet().iterator(); i.hasNext();) {
  126               String key = (String) i.next();
  127               String className = props.getProperty(key);
  128               if (Debug.verboseOn()) {
  129                   Debug.logVerbose("Adding FTL Transform " + key + " with class " + className, module);
  130               }
  131               try {
  132                   config.setSharedVariable(key, loader.loadClass(className).newInstance());
  133               } catch (Exception e) {
  134                   Debug.logError(e, "Could not pre-initialize dynamically loaded class: " + className + ": " + e, module);
  135               }
  136           }
  137       }
  138   
  139       /**
  140        * Renders a template at the specified location.
  141        * @param templateLocation Location of the template - file path or URL
  142        * @param context The context Map
  143        * @param outWriter The Writer to render to
  144        */
  145       public static void renderTemplateAtLocation(String templateLocation, Map<String, Object> context, Appendable outWriter) throws MalformedURLException, TemplateException, IOException {
  146           renderTemplate(templateLocation, context, outWriter);
  147       }
  148   
  149       /**
  150        * Renders a template contained in a String.
  151        * @param templateLocation A unique ID for this template - used for caching
  152        * @param templateString The String containing the template
  153        * @param context The context Map
  154        * @param outWriter The Writer to render to
  155        */
  156       public static void renderTemplate(String templateLocation, String templateString, Map<String, Object> context, Appendable outWriter) throws TemplateException, IOException {
  157           if (UtilValidate.isEmpty(templateString)) {
  158               renderTemplate(templateLocation, context, outWriter);
  159           } else {
  160               renderTemplateFromString(templateString, templateLocation, context, outWriter);
  161           }
  162       }
  163   
  164       /**
  165        * Renders a template from a Reader.
  166        * @param templateLocation A unique ID for this template - used for caching
  167        * @param context The context Map
  168        * @param outWriter The Writer to render to
  169        */
  170       public static void renderTemplate(String templateLocation, Map<String, Object> context, Appendable outWriter) throws TemplateException, IOException {
  171           Template template = getTemplate(templateLocation);
  172           renderTemplate(template, context, outWriter);
  173       }
  174   
  175       public static Environment renderTemplateFromString(String templateString, String templateLocation, Map<String, Object> context, Appendable outWriter) throws TemplateException, IOException {
  176           Template template = cachedTemplates.get(templateLocation);
  177           if (template == null) {
  178               synchronized (cachedTemplates) {
  179                   template = cachedTemplates.get(templateLocation);
  180                   if (template == null) {
  181                       Reader templateReader = new StringReader(templateString);
  182                       template = new Template(templateLocation, templateReader, defaultOfbizConfig);
  183                       templateReader.close();
  184                       cachedTemplates.put(templateLocation, template);
  185                   }
  186               }
  187           }
  188   
  189           return renderTemplate(template, context, outWriter);
  190       }
  191   
  192       /**
  193        * Renders a Template instance.
  194        * @param template A Template instance
  195        * @param context The context Map
  196        * @param outWriter The Writer to render to
  197        */
  198       public static Environment renderTemplate(Template template, Map<String, Object> context, Appendable outWriter) throws TemplateException, IOException {
  199           // make sure there is no "null" string in there as FreeMarker will try to use it
  200           context.remove("null");
  201           // Since the template cache keeps a single instance of a Template that is shared among users,
  202           // and since that Template instance is immutable, we need to create an Environment instance and
  203           // use it to process the template with the user's settings.
  204           //
  205           // FIXME: the casting from Appendable to Writer is a temporary fix that could cause a
  206           //        run time error if in the future we will pass a different class to the method
  207           //        (such as a StringBuffer).
  208           Environment env = template.createProcessingEnvironment(context, (Writer) outWriter);
  209           applyUserSettings(env, context);
  210           env.process();
  211           return env;
  212       }
  213   
  214       /**
  215        * Apply user settings to an Environment instance.
  216        * @param env An Environment instance
  217        * @param context The context Map containing the user settings
  218        */
  219       public static void applyUserSettings(Environment env, Map<String, Object> context) throws TemplateException {
  220           Locale locale = (Locale) context.get("locale");
  221           if (locale == null) {
  222               locale = Locale.getDefault();
  223           }
  224           env.setLocale(locale);
  225   
  226           TimeZone timeZone = (TimeZone) context.get("timeZone");
  227           if (timeZone == null) {
  228               timeZone = TimeZone.getDefault();
  229           }
  230           env.setTimeZone(timeZone);
  231       }
  232   
  233       public static Configuration getDefaultOfbizConfig() {
  234           return defaultOfbizConfig;
  235       }
  236   
  237       /** Make sure to close the reader when you're done! That's why this method is private, BTW. */
  238       private static Reader makeReader(String templateLocation) throws IOException {
  239           if (UtilValidate.isEmpty(templateLocation)) {
  240               throw new IllegalArgumentException("FreeMarker template location null or empty");
  241           }
  242   
  243           URL locationUrl = null;
  244           try {
  245               locationUrl = FlexibleLocation.resolveLocation(templateLocation);
  246           } catch (MalformedURLException e) {
  247               throw new IllegalArgumentException(e.getMessage());
  248           }
  249           if (locationUrl == null) {
  250               throw new IllegalArgumentException("FreeMarker file not found at location: " + templateLocation);
  251           }
  252   
  253           InputStream locationIs = locationUrl.openStream();
  254           Reader templateReader = new InputStreamReader(locationIs);
  255   
  256           String locationProtocol = locationUrl.getProtocol();
  257           if ("file".equals(locationProtocol) && Debug.verboseOn()) {
  258               String locationFile = locationUrl.getFile();
  259               int lastSlash = locationFile.lastIndexOf("/");
  260               String locationDir = locationFile.substring(0, lastSlash);
  261               String filename = locationFile.substring(lastSlash + 1);
  262               Debug.logVerbose("FreeMarker render: filename=" + filename + ", locationDir=" + locationDir, module);
  263           }
  264   
  265           return templateReader;
  266       }
  267   
  268       /**
  269        * Gets a Template instance from the template cache. If the Template instance isn't
  270        * found in the cache, then one will be created.
  271        * @param templateLocation Location of the template - file path or URL
  272        */
  273       public static Template getTemplate(String templateLocation) throws TemplateException, IOException {
  274           return getTemplate(templateLocation, cachedTemplates, defaultOfbizConfig);
  275       }
  276   
  277       public static Template getTemplate(String templateLocation, UtilCache<String, Template> cache, Configuration config) throws TemplateException, IOException {
  278           Template template = (Template) cache.get(templateLocation);
  279           if (template == null) {
  280               synchronized (cache) {
  281                   template = (Template) cache.get(templateLocation);
  282                   if (template == null) {
  283                       // only make the reader if we need it, and then close it right after!
  284                       Reader templateReader = makeReader(templateLocation);
  285                       template = new Template(templateLocation, templateReader, config);
  286                       templateReader.close();
  287                       cache.put(templateLocation, template);
  288                   }
  289               }
  290           }
  291           return template;
  292       }
  293   
  294       public static String getArg(Map<String, ? extends Object> args, String key, Environment env) {
  295           Map<String, ? extends Object> templateContext = UtilGenerics.checkMap(FreeMarkerWorker.getWrappedObject("context", env));
  296           return getArg(args, key, templateContext);
  297       }
  298   
  299       public static String getArg(Map<String, ? extends Object> args, String key, Map<String, ? extends Object> templateContext) {
  300           //SimpleScalar s = null;
  301           Object o = null;
  302           String returnVal = null;
  303           o = args.get(key);
  304           returnVal = (String) unwrap(o);
  305           if (returnVal == null) {
  306               try {
  307                   if (templateContext != null) {
  308                       returnVal = (String) templateContext.get(key);
  309                   }
  310               } catch (ClassCastException e2) {
  311                   //return null;
  312               }
  313           }
  314           return returnVal;
  315       }
  316   
  317       public static Object getArgObject(Map<String, ? extends Object> args, String key, Map<String, ? extends Object> templateContext) {
  318           //SimpleScalar s = null;
  319           Object o = null;
  320           Object returnVal = null;
  321           o = args.get(key);
  322           returnVal = unwrap(o);
  323           if (returnVal == null) {
  324               try {
  325                   if (templateContext != null) {
  326                       returnVal = templateContext.get(key);
  327                   }
  328               } catch (ClassCastException e2) {
  329                   //return null;
  330               }
  331           }
  332           return returnVal;
  333       }
  334   
  335   
  336      /**
  337       * Gets BeanModel from FreeMarker context and returns the object that it wraps.
  338       * @param varName the name of the variable in the FreeMarker context.
  339       * @param env the FreeMarker Environment
  340       */
  341       public static Object getWrappedObject(String varName, Environment env) {
  342           Object obj = null;
  343           try {
  344               obj = env.getVariable(varName);
  345               if (obj != null) {
  346                   if (obj == TemplateModel.NOTHING) {
  347                       obj = null;
  348                   } else if (obj instanceof BeanModel) {
  349                       BeanModel bean = (BeanModel) obj;
  350                       obj = bean.getWrappedObject();
  351                   } else if (obj instanceof SimpleScalar) {
  352                       obj = obj.toString();
  353                   }
  354               }
  355           } catch (TemplateModelException e) {
  356               Debug.logInfo(e.getMessage(), module);
  357           }
  358           return obj;
  359       }
  360   
  361      /**
  362       * Gets BeanModel from FreeMarker context and returns the object that it wraps.
  363       * @param varName the name of the variable in the FreeMarker context.
  364       * @param env the FreeMarker Environment
  365       */
  366       public static BeanModel getBeanModel(String varName, Environment env) {
  367           BeanModel bean = null;
  368           try {
  369               bean = (BeanModel) env.getVariable(varName);
  370           } catch (TemplateModelException e) {
  371               Debug.logInfo(e.getMessage(), module);
  372           }
  373           return bean;
  374       }
  375   
  376       public static Object get(SimpleHash args, String key) {
  377           Object returnObj = null;
  378           Object o = null;
  379           try {
  380               o = args.get(key);
  381           } catch (TemplateModelException e) {
  382               Debug.logVerbose(e.getMessage(), module);
  383               return returnObj;
  384           }
  385   
  386           returnObj = unwrap(o);
  387   
  388           if (returnObj == null) {
  389               Object ctxObj = null;
  390               try {
  391                   ctxObj = args.get("context");
  392               } catch (TemplateModelException e) {
  393                   Debug.logInfo(e.getMessage(), module);
  394                   return returnObj;
  395               }
  396               Map ctx = null;
  397               if (ctxObj instanceof BeanModel) {
  398                   ctx = (Map)((BeanModel)ctxObj).getWrappedObject();
  399               returnObj = ctx.get(key);
  400               }
  401               /*
  402               try {
  403                   Map templateContext = (Map)FreeMarkerWorker.getWrappedObject("context", env);
  404                   if (templateContext != null) {
  405                       returnObj = (String)templateContext.get(key);
  406                   }
  407               } catch (ClassCastException e2) {
  408                   //return null;
  409               }
  410               */
  411           }
  412           return returnObj;
  413       }
  414   
  415       public static Object unwrap(Object o) {
  416           Object returnObj = null;
  417   
  418           if (o == TemplateModel.NOTHING) {
  419               returnObj = null;
  420           } else if (o instanceof SimpleScalar) {
  421               returnObj = o.toString();
  422           } else if (o instanceof BeanModel) {
  423               returnObj = ((BeanModel)o).getWrappedObject();
  424           }
  425   
  426           return returnObj;
  427       }
  428   
  429       public static void checkForLoop(String path, Map<String, Object> ctx) throws IOException {
  430           List<String> templateList = UtilGenerics.checkList(ctx.get("templateList"));
  431           if (templateList == null) {
  432               templateList = FastList.newInstance();
  433           } else {
  434               if (templateList.contains(path)) {
  435                   throw new IOException(path + " has already been visited.");
  436               }
  437           }
  438           templateList.add(path);
  439           ctx.put("templateList", templateList);
  440       }
  441   
  442       public static Map<String, Object> createEnvironmentMap(Environment env) {
  443           Map<String, Object> templateRoot = FastMap.newInstance();
  444           Set<String> varNames = null;
  445           try {
  446               varNames = UtilGenerics.checkSet(env.getKnownVariableNames());
  447           } catch (TemplateModelException e1) {
  448               Debug.logError(e1, "Error getting FreeMarker variable names, will not put pass current context on to sub-content", module);
  449           }
  450           if (varNames != null) {
  451               for (String varName: varNames) {
  452                   //freemarker.ext.beans.StringModel varObj = (freemarker.ext.beans.StringModel ) varNameIter.next();
  453                   //Object varObj =  varNameIter.next();
  454                   //String varName = varObj.toString();
  455                   templateRoot.put(varName, FreeMarkerWorker.getWrappedObject(varName, env));
  456               }
  457           }
  458           return templateRoot;
  459       }
  460   
  461       public static void saveContextValues(Map<String, Object> context, String [] saveKeyNames, Map<String, Object> saveMap ) {
  462           //Map saveMap = new HashMap();
  463           for (String key: saveKeyNames) {
  464               Object o = context.get(key);
  465               if (o instanceof Map)
  466                   o = UtilMisc.makeMapWritable(UtilGenerics.checkMap(o));
  467               else if (o instanceof List)
  468                   o = UtilMisc.makeListWritable(UtilGenerics.checkList(o));
  469               saveMap.put(key, o);
  470           }
  471       }
  472   
  473       public static Map<String, Object> saveValues(Map<String, Object> context, String [] saveKeyNames) {
  474           Map<String, Object> saveMap = FastMap.newInstance();
  475           for (String key: saveKeyNames) {
  476               Object o = context.get(key);
  477               if (o instanceof Map)
  478                   o = UtilMisc.makeMapWritable(UtilGenerics.checkMap(o));
  479               else if (o instanceof List)
  480                   o = UtilMisc.makeListWritable(UtilGenerics.checkList(o));
  481               saveMap.put(key, o);
  482           }
  483           return saveMap;
  484       }
  485   
  486   
  487       public static void reloadValues(Map<String, Object> context, Map<String, Object> saveValues, Environment env ) {
  488           for (Map.Entry<String, Object> entry: saveValues.entrySet()) {
  489               String key = entry.getKey();
  490               Object o = entry.getValue();
  491               if (o instanceof Map) {
  492                   Map<Object, Object> map = FastMap.newInstance();
  493                   map.putAll(UtilGenerics.checkMap(o));
  494                   context.put(key, map);
  495               } else if (o instanceof List) {
  496                   List<Object> list = new ArrayList<Object>();
  497                   list.addAll(UtilGenerics.checkList(o));
  498                   context.put(key, list);
  499               } else {
  500                   context.put(key, o);
  501               }
  502               env.setVariable(key, autoWrap(o, env));
  503           }
  504       }
  505   
  506       public static void removeValues(Map<String, ?> context, String... removeKeyNames ) {
  507           for (String key: removeKeyNames) {
  508               context.remove(key);
  509           }
  510       }
  511   
  512       public static void overrideWithArgs(Map<String, Object> ctx, Map<String, Object> args) {
  513           for (Map.Entry<String, Object> entry: args.entrySet()) {
  514               String key = entry.getKey();
  515               Object obj = entry.getValue();
  516               //if (Debug.infoOn()) Debug.logInfo("in overrideWithArgs, key(3):" + key + " obj:" + obj + " class:" + obj.getClass().getName() , module);
  517               if (obj != null) {
  518                   if (obj == TemplateModel.NOTHING) {
  519                       ctx.put(key, null);
  520                   } else {
  521                       Object unwrappedObj = unwrap(obj);
  522                       if (unwrappedObj == null)
  523                           unwrappedObj = obj;
  524                       ctx.put(key, unwrappedObj.toString());
  525                   }
  526               } else {
  527                   ctx.put(key, null);
  528               }
  529           }
  530       }
  531   
  532       public static void convertContext(Map<String, Object> ctx) {
  533           for (Map.Entry<String, Object> entry: ctx.entrySet()) {
  534               Object obj = entry.getValue();
  535               if (obj != null) {
  536                   Object unwrappedObj = unwrap(obj);
  537                   if (unwrappedObj != null) {
  538                       entry.setValue(unwrappedObj);
  539                   }
  540               }
  541           }
  542       }
  543   
  544       public static void getSiteParameters(HttpServletRequest request, Map<String, Object> ctx) {
  545           if (request == null) {
  546               return;
  547           }
  548           if (ctx == null) {
  549               throw new IllegalArgumentException("Error in getSiteParameters, context/ctx cannot be null");
  550           }
  551           ServletContext servletContext = request.getSession().getServletContext();
  552           String rootDir = (String)ctx.get("rootDir");
  553           String webSiteId = (String)ctx.get("webSiteId");
  554           String https = (String)ctx.get("https");
  555           if (UtilValidate.isEmpty(rootDir)) {
  556               rootDir = servletContext.getRealPath("/");
  557               ctx.put("rootDir", rootDir);
  558           }
  559           if (UtilValidate.isEmpty(webSiteId)) {
  560               webSiteId = (String) servletContext.getAttribute("webSiteId");
  561               ctx.put("webSiteId", webSiteId);
  562           }
  563           if (UtilValidate.isEmpty(https)) {
  564               https = (String) servletContext.getAttribute("https");
  565               ctx.put("https", https);
  566           }
  567       }
  568   
  569       public static TemplateModel autoWrap(Object obj, Environment env) {
  570          BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
  571          TemplateModel templateModelObj = null;
  572          try {
  573              templateModelObj = wrapper.wrap(obj);
  574          } catch (TemplateModelException e) {
  575              throw new RuntimeException(e.getMessage());
  576          }
  577          return templateModelObj;
  578       }
  579   
  580       /**
  581        * OFBiz Template Source. This class is used by FlexibleTemplateLoader.
  582        */
  583       static class FlexibleTemplateSource {
  584           protected String templateLocation = null;
  585           protected Date createdDate = new Date();
  586   
  587           protected FlexibleTemplateSource() {}
  588           public FlexibleTemplateSource(String templateLocation) {
  589               this.templateLocation = templateLocation;
  590           }
  591   
  592           public int hashCode() {
  593               return templateLocation.hashCode();
  594           }
  595           public boolean equals(Object obj) {
  596               return obj instanceof FlexibleTemplateSource && obj.hashCode() == this.hashCode();
  597           }
  598           public String getTemplateLocation() {
  599               return templateLocation;
  600           }
  601           public long getLastModified() {
  602               return createdDate.getTime();
  603           }
  604       }
  605   
  606       /**
  607        * OFBiz Template Loader. This template loader uses the FlexibleLocation
  608        * class to locate and load Freemarker templates.
  609        */
  610       static class FlexibleTemplateLoader implements TemplateLoader {
  611           public Object findTemplateSource(String name) throws IOException {
  612               return new FlexibleTemplateSource(name);
  613           }
  614           public long getLastModified(Object templateSource) {
  615               FlexibleTemplateSource fts = (FlexibleTemplateSource) templateSource;
  616               return fts.getLastModified();
  617           }
  618           public Reader getReader(Object templateSource, String encoding) throws IOException {
  619               FlexibleTemplateSource fts = (FlexibleTemplateSource) templateSource;
  620               return makeReader(fts.getTemplateLocation());
  621           }
  622           public void closeTemplateSource(Object templateSource) throws IOException {
  623               // do nothing
  624           }
  625       }
  626   
  627       /**
  628        * OFBiz specific TemplateExceptionHandler.  Sanitizes any error messages present in
  629        * the stack trace prior to printing to the output writer.
  630        *
  631        */
  632       static class OFBizTemplateExceptionHandler implements TemplateExceptionHandler {
  633           public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException {
  634               StringWriter tempWriter = new StringWriter();
  635               PrintWriter pw = new PrintWriter(tempWriter, true);
  636               te.printStackTrace(pw);
  637               String stackTrace = tempWriter.toString();
  638   
  639               StringUtil.SimpleEncoder simpleEncoder = (SimpleEncoder) FreeMarkerWorker.getWrappedObject("simpleEncoder", env);
  640               if (simpleEncoder != null) {
  641                   stackTrace = simpleEncoder.encode(stackTrace);
  642               }
  643               try {
  644                   out.write(stackTrace);
  645               } catch (IOException e) {
  646                   Debug.logError(e, module);
  647               }
  648           }
  649       }
  650   }

Save This Page
Home » apache-ofbiz-09.04 » org.ofbiz.base.util.template » [javadoc | source]