svn commit: r674222 - in /ofbiz/trunk: applications/content/src/org/ofbiz/content/survey/SurveyWrapper.java framework/base/src/base/org/ofbiz/base/util/template/FreeMarkerWorker.java framework/webapp/src/org/ofbiz/webapp/ftl/FreeMarkerViewHandler.java

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

svn commit: r674222 - in /ofbiz/trunk: applications/content/src/org/ofbiz/content/survey/SurveyWrapper.java framework/base/src/base/org/ofbiz/base/util/template/FreeMarkerWorker.java framework/webapp/src/org/ofbiz/webapp/ftl/FreeMarkerViewHandler.java

adrianc
Author: adrianc
Date: Sat Jul  5 11:43:21 2008
New Revision: 674222

URL: http://svn.apache.org/viewvc?rev=674222&view=rev
Log:
FreeMarkerWorker.java improvements:

1. Better handling of the FreeMarker Configuration instance. Eliminated the need for synchronizing code.
2. OFBiz transforms are now kept in the Configuration object - no need to load them into the rendering context on every run.
3. Some small code cleanups.

FreeMarkerViewHandler.java improvements:

1. Eliminated redundant Configuration object initialization by cloning the Configuration object kept in FreeMarkerWorker.
2. Now supports the "component://" syntax for page attribute.

Modified:
    ofbiz/trunk/applications/content/src/org/ofbiz/content/survey/SurveyWrapper.java
    ofbiz/trunk/framework/base/src/base/org/ofbiz/base/util/template/FreeMarkerWorker.java
    ofbiz/trunk/framework/webapp/src/org/ofbiz/webapp/ftl/FreeMarkerViewHandler.java

Modified: ofbiz/trunk/applications/content/src/org/ofbiz/content/survey/SurveyWrapper.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/content/src/org/ofbiz/content/survey/SurveyWrapper.java?rev=674222&r1=674221&r2=674222&view=diff
==============================================================================
--- ofbiz/trunk/applications/content/src/org/ofbiz/content/survey/SurveyWrapper.java (original)
+++ ofbiz/trunk/applications/content/src/org/ofbiz/content/survey/SurveyWrapper.java Sat Jul  5 11:43:21 2008
@@ -30,7 +30,6 @@
 import java.util.List;
 import java.util.Map;
 
-import javolution.util.FastList;
 import javolution.util.FastMap;
 import javolution.util.FastSet;
 
@@ -44,8 +43,6 @@
 import org.ofbiz.entity.GenericEntityException;
 import org.ofbiz.entity.GenericValue;
 import org.ofbiz.entity.condition.EntityCondition;
-import org.ofbiz.entity.condition.EntityConditionList;
-import org.ofbiz.entity.condition.EntityExpr;
 import org.ofbiz.entity.condition.EntityOperator;
 import org.ofbiz.entity.transaction.TransactionUtil;
 import org.ofbiz.entity.util.EntityFindOptions;
@@ -191,7 +188,6 @@
             templateContext = FastMap.newInstance();
         }
 
-        FreeMarkerWorker.addAllOfbizTransforms(templateContext);
         templateContext.put("partyId", partyId);
         templateContext.put("survey", survey);
         templateContext.put("surveyResults", results);
@@ -218,14 +214,7 @@
     // returns the FTL Template object
     // Note: the template will not be cached
     protected Template getTemplate(URL templateUrl) {
-        Configuration config = null;
-        try {
-            config = FreeMarkerWorker.getDefaultOfbizConfig();
-        } catch (IOException e) {
-            Debug.logError(e, "Error creating default OFBiz FreeMarker Configuration", module);
-        } catch (TemplateException e) {
-            Debug.logError(e, "Error creating default OFBiz FreeMarker Configuration", module);
-        }
+        Configuration config = FreeMarkerWorker.getDefaultOfbizConfig();
 
         Template template = null;
         try {

Modified: ofbiz/trunk/framework/base/src/base/org/ofbiz/base/util/template/FreeMarkerWorker.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/base/src/base/org/ofbiz/base/util/template/FreeMarkerWorker.java?rev=674222&r1=674221&r2=674222&view=diff
==============================================================================
--- ofbiz/trunk/framework/base/src/base/org/ofbiz/base/util/template/FreeMarkerWorker.java (original)
+++ ofbiz/trunk/framework/base/src/base/org/ofbiz/base/util/template/FreeMarkerWorker.java Sat Jul  5 11:43:21 2008
@@ -44,7 +44,6 @@
 
 import org.ofbiz.base.location.FlexibleLocation;
 import org.ofbiz.base.util.Debug;
-import org.ofbiz.base.util.UtilDateTime;
 import org.ofbiz.base.util.UtilGenerics;
 import org.ofbiz.base.util.UtilMisc;
 import org.ofbiz.base.util.UtilProperties;
@@ -60,14 +59,11 @@
 import freemarker.template.SimpleScalar;
 import freemarker.template.Template;
 import freemarker.template.TemplateException;
-import freemarker.template.TemplateHashModel;
 import freemarker.template.TemplateModel;
 import freemarker.template.TemplateModelException;
 //import com.clarkware.profiler.Profiler;
 
-
-/**
- * FreemarkerViewHandler - Freemarker Template Engine Util
+/** FreeMarkerWorker - Freemarker Template Engine Utilities.
  *
  */
 public class FreeMarkerWorker {
@@ -76,15 +72,23 @@
     
     // 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...
     public static UtilCache<String, Template> cachedTemplates = new UtilCache<String, Template>("template.ftl.general", 0, 0, false);
-    private static Configuration defaultOfbizConfig = null;
+    protected static Configuration defaultOfbizConfig = new Configuration();
 
-    // TemplateModel
-    public static Map<String, Object> ftlTransforms = FastMap.newInstance();
-    
     public static final String FRAMEWORK_TRANSFORMS = "frameworkTransforms";
     public static final String APPLICATION_TRANSFORMS = "applicationTransforms";
 
     static {
+        BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
+        defaultOfbizConfig.setObjectWrapper(wrapper);
+        defaultOfbizConfig.setSharedVariable("Static", wrapper.getStaticModels());
+        defaultOfbizConfig.setLocalizedLookup(false);
+        defaultOfbizConfig.setTemplateLoader(new FlexibleTemplateLoader());
+        try {
+            defaultOfbizConfig.setSetting("datetime_format", "yyyy-MM-dd HH:mm:ss.SSS");
+            defaultOfbizConfig.setSetting("number_format", "0.##########");
+        } catch (TemplateException e) {
+            Debug.logError("Unable to set date/time and number formats in FreeMarker: " + e, module);
+        }
         // Load framework transforms first.
         // Transforms properties file set up as key=transform name, property=transform class name
         Properties props = UtilProperties.getProperties(FRAMEWORK_TRANSFORMS);
@@ -97,7 +101,7 @@
         // Load application transforms next.
         props = UtilProperties.getProperties(APPLICATION_TRANSFORMS);
         if (props == null || props.isEmpty()) {
-            Debug.logError("Unable to locate properties file " + APPLICATION_TRANSFORMS, module);
+            Debug.logWarning("Unable to locate properties file " + APPLICATION_TRANSFORMS + ". If you are using only the OFBiz framework, then this warning can be ignored.", module);
         } else {
             loadTransforms(props);
         }
@@ -108,20 +112,16 @@
      */
     protected static void loadTransforms(Properties props) {
         ClassLoader loader = Thread.currentThread().getContextClassLoader();
-        for (Iterator i = props.keySet().iterator(); i.hasNext();) {
+        for (Iterator<Object> i = props.keySet().iterator(); i.hasNext();) {
             String key = (String)i.next();
             String className = props.getProperty(key);
             if (Debug.verboseOn()) {
                 Debug.logVerbose("Adding FTL Transform " + key + " with class " + className, module);
             }
             try {
-                ftlTransforms.put(key, loader.loadClass(className).newInstance());
-            } catch (ClassNotFoundException e) {
-                Debug.logError(e, "Could not pre-initialize dynamically loaded class: " + className + " ", module);
-            } catch (IllegalAccessException e) {
-                Debug.logError(e, "Could not pre-initialize dynamically loaded class: " + className + " ", module);
-            } catch (InstantiationException e) {
-                Debug.logError(e, "Could not pre-initialize dynamically loaded class: " + className + " ", module);
+                defaultOfbizConfig.setSharedVariable(key, loader.loadClass(className).newInstance());
+            } catch (Exception e) {
+                Debug.logError(e, "Could not pre-initialize dynamically loaded class: " + className + ": " + e, module);
             }
         }
     }
@@ -170,7 +170,7 @@
                 template = cachedTemplates.get(templateLocation);
                 if (template == null) {
                     Reader templateReader = new StringReader(templateString);
-                    template = new Template(templateLocation, templateReader, getDefaultOfbizConfig());
+                    template = new Template(templateLocation, templateReader, defaultOfbizConfig);
                     templateReader.close();
                     cachedTemplates.put(templateLocation, template);
                 }
@@ -187,7 +187,6 @@
      * @param outWriter The Writer to render to
      */
     public static void renderTemplate(Template template, Map<String, Object> context, Appendable outWriter) throws TemplateException, IOException {
-        addAllOfbizTransforms(context);
         // make sure there is no "null" string in there as FreeMarker will try to use it
         context.remove("null");
         // Since the template cache keeps a single instance of a Template that is shared among users,
@@ -202,16 +201,6 @@
         env.process();
     }
     
-    public static void addAllOfbizTransforms(Map<String, Object> context) {
-        BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
-        TemplateHashModel staticModels = wrapper.getStaticModels();
-        if (context == null) {
-            context = FastMap.newInstance();
-        }
-        context.put("Static", staticModels);
-        context.putAll(ftlTransforms);
-    }
-
     /**
      * Apply user settings to an Environment instance.
      * @param env An Environment instance
@@ -231,22 +220,7 @@
         env.setTimeZone(timeZone);
     }
 
-    public static Configuration getDefaultOfbizConfig() throws TemplateException, IOException {
-        if (defaultOfbizConfig == null) {
-            synchronized (FreeMarkerWorker.class) {
-                if (defaultOfbizConfig == null) {
-                    Configuration config = new Configuration();            
-                    config.setObjectWrapper(BeansWrapper.getDefaultInstance());
-                    // the next two settings don't do anything - Freemarker will format
-                    // output according to the user's locale
-                    config.setSetting("datetime_format", "yyyy-MM-dd HH:mm:ss.SSS");
-                    config.setSetting("number_format", "0.##########");
-                    config.setLocalizedLookup(false);
-                    config.setTemplateLoader(new FlexibleTemplateLoader());
-                    defaultOfbizConfig = config;
-                }
-            }
-        }
+    public static Configuration getDefaultOfbizConfig() {
         return defaultOfbizConfig;
     }
     
@@ -275,7 +249,7 @@
             int lastSlash = locationFile.lastIndexOf("/");
             String locationDir = locationFile.substring(0, lastSlash);
             String filename = locationFile.substring(lastSlash + 1);
-            if (Debug.verboseOn()) Debug.logVerbose("FreeMarker render: filename=" + filename + ", locationDir=" + locationDir, module);
+            Debug.logVerbose("FreeMarker render: filename=" + filename + ", locationDir=" + locationDir, module);
         }
         
         return templateReader;
@@ -294,7 +268,7 @@
                 if (template == null) {
                     // only make the reader if we need it, and then close it right after!
                     Reader templateReader = makeReader(templateLocation);
-                    template = new Template(templateLocation, templateReader, getDefaultOfbizConfig());
+                    template = new Template(templateLocation, templateReader, defaultOfbizConfig);
                     templateReader.close();
                     cachedTemplates.put(templateLocation, template);
                 }
@@ -505,7 +479,7 @@
                 map.putAll(UtilGenerics.checkMap(o));
                 context.put(key, map);
             } else if (o instanceof List) {
-                List<Object> list = new ArrayList();
+                List<Object> list = new ArrayList<Object>();
                 list.addAll(UtilGenerics.checkList(o));
                 context.put(key, list);
             } else {

Modified: ofbiz/trunk/framework/webapp/src/org/ofbiz/webapp/ftl/FreeMarkerViewHandler.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/framework/webapp/src/org/ofbiz/webapp/ftl/FreeMarkerViewHandler.java?rev=674222&r1=674221&r2=674222&view=diff
==============================================================================
--- ofbiz/trunk/framework/webapp/src/org/ofbiz/webapp/ftl/FreeMarkerViewHandler.java (original)
+++ ofbiz/trunk/framework/webapp/src/org/ofbiz/webapp/ftl/FreeMarkerViewHandler.java Sat Jul  5 11:43:21 2008
@@ -20,7 +20,6 @@
 
 import java.io.File;
 import java.io.IOException;
-import java.util.HashMap;
 import java.util.Map;
 
 import javax.servlet.ServletContext;
@@ -29,6 +28,7 @@
 import javax.servlet.http.HttpSession;
 
 import org.ofbiz.base.util.UtilHttp;
+import org.ofbiz.base.util.collections.MapStack;
 import org.ofbiz.base.util.template.FreeMarkerWorker;
 import org.ofbiz.webapp.view.ViewHandler;
 import org.ofbiz.webapp.view.ViewHandlerException;
@@ -38,42 +38,25 @@
 import freemarker.ext.servlet.HttpRequestHashModel;
 import freemarker.ext.servlet.HttpSessionHashModel;
 import freemarker.template.Configuration;
-import freemarker.template.SimpleHash;
 import freemarker.template.Template;
 import freemarker.template.TemplateException;
-import freemarker.template.WrappingTemplateModel;
 
-
-/**
- * FreemarkerViewHandler - Freemarker Template Engine View Handler
+/** FreemarkerViewHandler - Freemarker Template Engine View Handler.
  */
 public class FreeMarkerViewHandler implements ViewHandler {
     
     public static final String module = FreeMarkerViewHandler.class.getName();
-    
     protected ServletContext servletContext = null;
-    protected Configuration config = null;
-
+    protected Configuration config = (Configuration) FreeMarkerWorker.getDefaultOfbizConfig().clone();
+    
     public void init(ServletContext context) throws ViewHandlerException {
         this.servletContext = context;
-
-        config = new freemarker.template.Configuration();
-        config.setLocalizedLookup(false);
-        
-        //nice thought, but doesn't do auto reloading with this: config.setServletContextForTemplateLoading(context, "/");
+        config.setCacheStorage(new OfbizCacheStorage("unknown"));
         try {
-            config.setDirectoryForTemplateLoading(new File(context.getRealPath("/")));
-        } catch (java.io.IOException e) {
+            config.setDirectoryForTemplateLoading(new File(servletContext.getRealPath("/")));
+        } catch (IOException e) {
             throw new ViewHandlerException("Could not create file for webapp root path", e);
-        }
-        WrappingTemplateModel.setDefaultObjectWrapper(BeansWrapper.getDefaultInstance());
-        try {        
-            config.setObjectWrapper(BeansWrapper.getDefaultInstance());
-            config.setCacheStorage(new OfbizCacheStorage("unknown"));
-            config.setSetting("datetime_format", "yyyy-MM-dd HH:mm:ss.SSS");
-        } catch (TemplateException e) {
-            throw new ViewHandlerException("Freemarker TemplateException", e.getCause());
-        }        
+        }      
     }    
     
     public void render(String name, String page, String info, String contentType, String encoding,
@@ -82,21 +65,18 @@
             throw new ViewHandlerException("Invalid template source");
         
         // make the root context (data model) for freemarker
-        SimpleHash root = new SimpleHash(BeansWrapper.getDefaultInstance());
-        prepOfbizRoot(root, request, response);
+        MapStack<String> context = MapStack.create();
+        prepOfbizRoot(context, request, response);
                       
-        // get the template
-        Template template = null;
-        try {
-            template = config.getTemplate(page, UtilHttp.getLocale(request));
-        } catch (IOException e) {
-            throw new ViewHandlerException("Cannot open template file: " + page, e);
-        }
-        template.setObjectWrapper(BeansWrapper.getDefaultInstance());
-        
         // process the template & flush the output
         try {
-            template.process(root, response.getWriter(), BeansWrapper.getDefaultInstance());
+            if (page.startsWith("component://")) {
+                FreeMarkerWorker.renderTemplateAtLocation(page, context, response.getWriter());
+            } else {
+                // backwards compatibility
+                Template template = config.getTemplate(page);
+                FreeMarkerWorker.renderTemplate(template, context, response.getWriter());
+            }
             response.flushBuffer();
         } catch (TemplateException te) {
             throw new ViewHandlerException("Problems processing Freemarker template", te);
@@ -105,12 +85,6 @@
         }      
     }
     
-    public static void prepOfbizRoot(SimpleHash root, HttpServletRequest request, HttpServletResponse response) {
-        Map rootPrep = new HashMap();
-        prepOfbizRoot(rootPrep, request, response);
-        root.putAll(rootPrep);
-    }
-    
     public static void prepOfbizRoot(Map root, HttpServletRequest request, HttpServletResponse response) {
         ServletContext servletContext = (ServletContext) request.getAttribute("servletContext");
         HttpSession session = request.getSession();
@@ -152,6 +126,5 @@
         TaglibFactory JspTaglibs = new TaglibFactory(servletContext);
         root.put("JspTaglibs", JspTaglibs);
 
-        FreeMarkerWorker.addAllOfbizTransforms(root);
     }
 }