Author: ghuber
Date: Fri Jan 27 17:02:44 2012
New Revision: 1236763

URL: http://svn.apache.org/viewvc?rev=1236763&view=rev
Log:
Theme reloading from WEB-INF/velocity

Modified:
    
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/FeedServlet.java
    
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/RSDServlet.java
    
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogCacheWarmupJob.java
    
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java
    
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/ThemeResourceLoader.java
    
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/VelocityRenderer.java
    
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/WebappResourceLoader.java
    roller/trunk/weblogger-webapp/src/main/webapp/WEB-INF/velocity.properties

Modified: 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/FeedServlet.java
URL: 
http://svn.apache.org/viewvc/roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/FeedServlet.java?rev=1236763&r1=1236762&r2=1236763&view=diff
==============================================================================
--- 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/FeedServlet.java
 (original)
+++ 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/FeedServlet.java
 Fri Jan 27 17:02:44 2012
@@ -219,16 +219,16 @@ public class FeedServlet extends HttpSer
             // determine what template to render with
             boolean siteWide = 
WebloggerRuntimeConfig.isSiteWideWeblog(weblog.getHandle());
            if (siteWide && "entries".equals(feedRequest.getType()) && 
feedRequest.getTerm() != null) {
-                pageId = "templates/feeds/site-search-atom.vm";
+                pageId = "site-search-atom.vm";
 
            } else if ("entries".equals(feedRequest.getType()) && 
feedRequest.getTerm() != null) {
-                pageId = "templates/feeds/weblog-search-atom.vm";
+                pageId = "feeds/weblog-search-atom.vm";
 
             } else if (siteWide) {
-                pageId = 
"templates/feeds/site-"+feedRequest.getType()+"-"+feedRequest.getFormat()+".vm";
+                pageId = 
"site-"+feedRequest.getType()+"-"+feedRequest.getFormat()+".vm";
 
             } else {
-                pageId = 
"templates/feeds/weblog-"+feedRequest.getType()+"-"+feedRequest.getFormat()+".vm";
+                pageId = 
"weblog-"+feedRequest.getType()+"-"+feedRequest.getFormat()+".vm";
             }
 
             // populate the rendering model

Modified: 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/RSDServlet.java
URL: 
http://svn.apache.org/viewvc/roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/RSDServlet.java?rev=1236763&r1=1236762&r2=1236763&view=diff
==============================================================================
--- 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/RSDServlet.java
 (original)
+++ 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/servlets/RSDServlet.java
 Fri Jan 27 17:02:44 2012
@@ -120,7 +120,7 @@ public class RSDServlet extends HttpServ
         Renderer renderer = null;
         try {
             log.debug("Looking up renderer");
-            Template template = new StaticTemplate("templates/weblog/rsd.vm", 
"velocity");
+            Template template = new StaticTemplate("rsd.vm", "velocity");
             renderer = RendererManager.getRenderer(template, 
DeviceType.standard); 
         } catch(Exception e) {
             // nobody wants to render my content :(

Modified: 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogCacheWarmupJob.java
URL: 
http://svn.apache.org/viewvc/roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogCacheWarmupJob.java?rev=1236763&r1=1236762&r2=1236763&view=diff
==============================================================================
--- 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogCacheWarmupJob.java
 (original)
+++ 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogCacheWarmupJob.java
 Fri Jan 27 17:02:44 2012
@@ -135,7 +135,7 @@ public class WeblogCacheWarmupJob implem
                 // lookup Renderer we are going to use
                 Renderer renderer = null;
                 Template template = new StaticTemplate(
-                                       
"templates/feeds/weblog-"+type+"-"+format+".vm", "velocity");
+                                       "weblog-"+type+"-"+format+".vm", 
"velocity");
                 renderer = RendererManager.getRenderer(template, 
DeviceType.standard);
                 
                 

Modified: 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java
URL: 
http://svn.apache.org/viewvc/roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java?rev=1236763&r1=1236762&r2=1236763&view=diff
==============================================================================
--- 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java
 (original)
+++ 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java
 Fri Jan 27 17:02:44 2012
@@ -1,82 +1,74 @@
 /*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-*  contributor license agreements.  The ASF licenses this file to You
-* under the Apache License, Version 2.0 (the "License"); you may not
-* use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.  For additional information regarding
-* copyright in this work, please see the NOTICE file in the top level
-* directory of this distribution.
-*/
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.  For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ */
 package org.apache.roller.weblogger.ui.rendering.velocity;
 
 import java.io.ByteArrayInputStream;
 import java.io.InputStream;
 import java.io.UnsupportedEncodingException;
+
 import org.apache.commons.collections.ExtendedProperties;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
-import org.apache.velocity.exception.ResourceNotFoundException;
-import org.apache.velocity.runtime.resource.Resource;
-import org.apache.velocity.runtime.resource.loader.ResourceLoader;
-import org.apache.roller.weblogger.WebloggerException;
 import org.apache.roller.weblogger.business.WebloggerFactory;
 import org.apache.roller.weblogger.pojos.TemplateCode;
 import org.apache.roller.weblogger.pojos.WeblogTemplate;
-
+import org.apache.velocity.exception.ResourceNotFoundException;
+import org.apache.velocity.runtime.resource.Resource;
+import org.apache.velocity.runtime.resource.loader.ResourceLoader;
 
 /**
- * This is a simple template file loader that loads templates
- * from the Roller instance instead of plain files.
+ * The RollerResourceLoader is a Velocity template loader which loads templates
+ * from custom themes.
  * 
  * RollerResourceLoader makes use of WebloggerFactory.
  * 
  * @author <a href="mailto:[email protected]";>Lance Lavandowska</a>
- * @version $Id: RollerResourceLoader.java,v 1.9 2005/01/15 03:32:49 snoopdave 
Exp $
+ * @version $Id: RollerResourceLoader.java,v 1.9 2005/01/15 03:32:49 snoopdave
+ *          Exp $
  */
 public class RollerResourceLoader extends ResourceLoader {
-    
-    private static Log logger = LogFactory.getLog(RollerResourceLoader.class);
-    
-    
-    public void init(ExtendedProperties configuration) {
-        if (logger.isDebugEnabled()) {
-            logger.debug(configuration);
-        }
-    }
-    
-    public boolean isSourceModified(Resource resource) {
-        return (resource.getLastModified() !=
-                readLastModified(resource, "checking timestamp"));
-    }
-    
-    public long getLastModified(Resource resource) {
-        return readLastModified(resource, "getting timestamp");
-    }
-    
-    /**
-     * Get an InputStream so that the Runtime can build a
-     * template with it.
-     *
-     * @param name name of template
-     * @return InputStream containing template
-     */
-    public InputStream getResourceStream(String name)
-            throws ResourceNotFoundException {
-        
+
+       private static Log logger = 
LogFactory.getLog(RollerResourceLoader.class);
+
+       public void init(ExtendedProperties configuration) {
+               if (logger.isDebugEnabled()) {
+                       logger.debug(configuration);
+               }
+       }
+
+       /**
+        * Get an InputStream so that the Runtime can build a template with it.
+        * 
+        * @param name
+        *            name of template
+        * @return InputStream containing template
+        */
+       public InputStream getResourceStream(String name)
+                       throws ResourceNotFoundException {
+
                logger.debug("Looking for: " + name);
 
-        if (name == null || name.length() == 0) {
-            throw new ResourceNotFoundException("Need to specify a template 
name!");
-        }
+               if (name == null || name.length() == 0) {
+                       throw new ResourceNotFoundException(
+                                       "Need to specify a template name!");
+               }
 
+               // theme templates name are <template>|<deviceType>
                String deviceType = "standard";
                if (name.contains("|")) {
                        String[] pair = name.split("\\|");
@@ -86,70 +78,56 @@ public class RollerResourceLoader extend
 
                logger.debug("   Actually, it's " + name);
 
-        try {
-            WeblogTemplate page = WebloggerFactory
-                               
.getWeblogger().getWeblogManager().getPage(name);
-            
-            if (page == null) {
-                throw new ResourceNotFoundException(
-                        "RollerResourceLoader: page \"" +
-                        name + "\" not found");
-            }
+               try {
+                       WeblogTemplate page = WebloggerFactory.getWeblogger()
+                                       .getWeblogManager().getPage(name);
+
+                       if (page == null) {
+                               throw new ResourceNotFoundException(
+                                               "RollerResourceLoader: page \"" 
+ name + "\" not found");
+                       }
                        String contents;
                        TemplateCode templateCode = 
page.getTemplateCode(deviceType);
                        if (templateCode != null) {
-                               contents = templateCode.getTemplate(); 
+                               contents = templateCode.getTemplate();
                        } else {
                                contents = page.getContents();
                        }
-            return new ByteArrayInputStream(contents.getBytes("UTF-8") );
+                       return new 
ByteArrayInputStream(contents.getBytes("UTF-8"));
 
-        } catch (UnsupportedEncodingException uex) {
-            // This should never actually happen.  We expect UTF-8 in all JRE 
installation.
-            // This rethrows as a Runtime exception after logging.
-            logger.error(uex);
-            throw new RuntimeException(uex);
-
-        } catch (Exception re) {
-            String msg = "RollerResourceLoader Error: " +
-                    "database problem trying to load resource " + name;
-            logger.error( msg, re );
-            throw new ResourceNotFoundException(msg);
-        }
-    }
-    
-    
-    /**
-     * Fetches the last modification time of the resource
-     *
-     * @param resource Resource object we are finding timestamp of
-     * @param i_operation string for logging, indicating caller's intention
-     *
-     * @return timestamp as long
-     */
-    private long readLastModified(Resource resource, String i_operation) {
-        
-        // get the template name from the resource
-        String name = resource.getName();
-
-               if (name.contains("|")) {
-                       String[] pair = name.split("\\|");
-                       name = pair[0];
+               } catch (UnsupportedEncodingException uex) {
+                       // This should never actually happen. We expect UTF-8 
in all JRE
+                       // installation.
+                       // This rethrows as a Runtime exception after logging.
+                       logger.error(uex);
+                       throw new RuntimeException(uex);
+
+               } catch (Exception re) {
+                       String msg = "RollerResourceLoader Error: "
+                                       + "database problem trying to load 
resource " + name;
+                       logger.error(msg, re);
+                       throw new ResourceNotFoundException(msg);
                }
+       }
+
+       /**
+        * Files loaded by this resource loader are not reloadable here, as 
they are
+        * stored in custom themes and there is no way velocity can trigger a
+        * reload.
+        * 
+        * @see 
org.apache.velocity.runtime.resource.loader.ResourceLoader#isSourceModified(org.apache.velocity.runtime.resource.Resource)
+        */
+       public boolean isSourceModified(Resource resource) {
+               return false;
+       }
+
+       /**
+        * Defaults to return 0.
+        * 
+        * @see 
org.apache.velocity.runtime.resource.loader.ResourceLoader#getLastModified(org.apache.velocity.runtime.resource.Resource)
+        */
+       public long getLastModified(Resource resource) {
+               return 0;
+       }
 
-        try {
-            WeblogTemplate page = 
-                    
WebloggerFactory.getWeblogger().getWeblogManager().getPage(name);
-            
-            if (logger.isDebugEnabled()) {
-                logger.debug(name + ": resource=" + resource.getLastModified() 
+
-                        " vs. page=" + page.getLastModified().getTime());
-            }
-            return page.getLastModified().getTime();
-        } catch (WebloggerException re) {
-            logger.error( "Error " + i_operation, re );
-        }
-        return 0;
-    }
-    
 }

Modified: 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/ThemeResourceLoader.java
URL: 
http://svn.apache.org/viewvc/roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/ThemeResourceLoader.java?rev=1236763&r1=1236762&r2=1236763&view=diff
==============================================================================
--- 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/ThemeResourceLoader.java
 (original)
+++ 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/ThemeResourceLoader.java
 Fri Jan 27 17:02:44 2012
@@ -1,20 +1,20 @@
 /*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-*  contributor license agreements.  The ASF licenses this file to You
-* under the Apache License, Version 2.0 (the "License"); you may not
-* use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.  For additional information regarding
-* copyright in this work, please see the NOTICE file in the top level
-* directory of this distribution.
-*/
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.  For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ */
 /*
  * ThemeResourceLoader.java
  *
@@ -39,33 +39,31 @@ import org.apache.roller.weblogger.busin
 import org.apache.roller.weblogger.pojos.Theme;
 import org.apache.roller.weblogger.pojos.ThemeTemplate;
 
-
 /**
- * The ThemeResourceLoader is a Velocity template loader which loads
- * templates from shared themes.
- *
+ * The ThemeResourceLoader is a Velocity template loader which loads templates
+ * from shared themes.
+ * 
  * @author Allen Gilliland
  */
 public class ThemeResourceLoader extends ResourceLoader {
-    
-    private static Log logger = 
-        LogFactory.getFactory().getInstance(ThemeResourceLoader.class);
-        
-    
-    public void init(ExtendedProperties configuration) {
-        logger.debug(configuration);
-    }
-    
-    
-    public InputStream getResourceStream( String name )
-        throws ResourceNotFoundException {
-        
+
+       private static Log logger = LogFactory.getFactory().getInstance(
+                       ThemeResourceLoader.class);
+
+       public void init(ExtendedProperties configuration) {
+               logger.debug(configuration);
+       }
+
+       public InputStream getResourceStream(String name)
+                       throws ResourceNotFoundException {
+
                logger.debug("Looking for: " + name);
-       
-        if (name == null || name.length() < 1) {
-            throw new ResourceNotFoundException("Need to specify a template 
name!");
-        }
-       
+
+               if (name == null || name.length() < 1) {
+                       throw new ResourceNotFoundException(
+                                       "Need to specify a template name!");
+               }
+
                String deviceType = "standard";
                if (name.contains("|")) {
                        String[] pair = name.split("\\|");
@@ -73,88 +71,70 @@ public class ThemeResourceLoader extends
                        deviceType = pair[1];
                }
 
-        try {
-            // parse the name ... theme templates name are <theme>:<template>
-            String[] split = name.split(":", 2);
-            if(split.length < 2)
-                throw new ResourceNotFoundException("Invalid ThemeRL key 
"+name);
-            
-            // lookup the template from the proper theme
-            ThemeManager themeMgr = 
WebloggerFactory.getWeblogger().getThemeManager();
-            Theme theme = themeMgr.getTheme(split[0]);
-            ThemeTemplate template = theme.getTemplateByName(split[1]);
-           
-            if (template == null)
-                throw new ResourceNotFoundException("Template ["+split[1]+
-                        "] doesn't seem to be part of theme ["+split[0]+"]");
-          
+               try {
+                       // parse the name ... theme templates name are
+                       // <theme>:<template>|<deviceType>
+                       String[] split = name.split(":", 2);
+                       if (split.length < 2)
+                               throw new ResourceNotFoundException("Invalid 
ThemeRL key "
+                                               + name);
+
+                       // lookup the template from the proper theme
+                       ThemeManager themeMgr = WebloggerFactory.getWeblogger()
+                                       .getThemeManager();
+                       Theme theme = themeMgr.getTheme(split[0]);
+                       ThemeTemplate template = 
theme.getTemplateByName(split[1]);
+
+                       if (template == null)
+                               throw new ResourceNotFoundException("Template 
[" + split[1]
+                                               + "] doesn't seem to be part of 
theme [" + split[0]
+                                               + "]");
+
                        final String contents;
                        if (template.getTemplateCode(deviceType) != null) {
-                               contents = 
template.getTemplateCode(deviceType).getTemplate();  
+                               contents = 
template.getTemplateCode(deviceType).getTemplate();
                        } else {
-                               contents = template.getContents(); 
+                               contents = template.getContents();
                        }
-            logger.debug("Resource found!");
-           
-            // return the input stream
-            return new ByteArrayInputStream(contents.getBytes("UTF-8"));
-            
-        } catch (UnsupportedEncodingException uex) {
-            // We expect UTF-8 in all JRE installation.
-            // This rethrows as a Runtime exception after logging.
-            logger.error(uex);
-            throw new RuntimeException(uex);
-           
-        } catch (ThemeNotFoundException tnfe) {
-            String msg = "ThemeResourceLoader Error: " + tnfe.getMessage();
-            logger.error(msg, tnfe);
-            throw new ResourceNotFoundException(msg);
-            
-        } catch (WebloggerException re) {
-            String msg = "RollerResourceLoader Error: " + re.getMessage();
-            logger.error( msg, re );
-            throw new ResourceNotFoundException(msg);
-        }
-    }
-    
-    
-    public boolean isSourceModified(Resource resource) {
-        return (resource.getLastModified() != this.getLastModified(resource));
-    }
-    
-    
-    public long getLastModified(Resource resource) {
-        long last_mod = 0;
-        String name = resource.getName();
-        
-        logger.debug("Checking last modified time for resource named ... 
"+name);
-        
-        if (name == null || name.length() < 1)
-            return last_mod;
-        
-        try {
-            // parse the name ... theme templates name are <theme>:<template>
-            String[] split = name.split(":", 2);
-            if(split.length < 2)
-                return last_mod;
-            
-            // lookup the template from the proper theme
-            ThemeManager themeMgr = 
WebloggerFactory.getWeblogger().getThemeManager();
-            Theme theme = themeMgr.getTheme(split[0]);
-            ThemeTemplate template = theme.getTemplateByName(split[1]);
-            
-            if(template == null)
-                return last_mod;
-            
-            last_mod = template.getLastModified().getTime();
-            
-        } catch (ThemeNotFoundException tnfe) {
-            // ignore
-        } catch (WebloggerException re) {
-            // we don't like to see this happen, but oh well
-        }
-        
-        return last_mod;
-    }
-    
+                       logger.debug("Resource found!");
+
+                       // return the input stream
+                       return new 
ByteArrayInputStream(contents.getBytes("UTF-8"));
+
+               } catch (UnsupportedEncodingException uex) {
+                       // We expect UTF-8 in all JRE installation.
+                       // This rethrows as a Runtime exception after logging.
+                       logger.error(uex);
+                       throw new RuntimeException(uex);
+
+               } catch (ThemeNotFoundException tnfe) {
+                       String msg = "ThemeResourceLoader Error: " + 
tnfe.getMessage();
+                       logger.error(msg, tnfe);
+                       throw new ResourceNotFoundException(msg);
+
+               } catch (WebloggerException re) {
+                       String msg = "RollerResourceLoader Error: " + 
re.getMessage();
+                       logger.error(msg, re);
+                       throw new ResourceNotFoundException(msg);
+               }
+       }
+
+       /**
+        * Files loaded by this resource loader are not reloadable here, as 
they are
+        * stored in shared themes and there is no way velocity can trigger a
+        * reload.
+        * 
+        * @see 
org.apache.velocity.runtime.resource.loader.ResourceLoader#isSourceModified(org.apache.velocity.runtime.resource.Resource)
+        */
+       public boolean isSourceModified(Resource resource) {
+               return false;
+       }
+
+       /**
+        * @see 
org.apache.velocity.runtime.resource.loader.ResourceLoader#getLastModified(org.apache.velocity.runtime.resource.Resource)
+        */
+       public long getLastModified(Resource resource) {
+               return 0;
+       }
+
 }

Modified: 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/VelocityRenderer.java
URL: 
http://svn.apache.org/viewvc/roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/VelocityRenderer.java?rev=1236763&r1=1236762&r2=1236763&view=diff
==============================================================================
--- 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/VelocityRenderer.java
 (original)
+++ 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/VelocityRenderer.java
 Fri Jan 27 17:02:44 2012
@@ -90,7 +90,7 @@ public class VelocityRenderer implements
             parseException = ex;
             
             // need to lookup error page template
-            velocityTemplate = 
RollerVelocity.getTemplate("templates/error-page.vm", deviceType);
+            velocityTemplate = RollerVelocity.getTemplate("error-page.vm", 
deviceType);
             
         } catch(Exception ex) {
             // some kind of generic/unknown exception, dump it to the logs

Modified: 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/WebappResourceLoader.java
URL: 
http://svn.apache.org/viewvc/roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/WebappResourceLoader.java?rev=1236763&r1=1236762&r2=1236763&view=diff
==============================================================================
--- 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/WebappResourceLoader.java
 (original)
+++ 
roller/trunk/weblogger-web/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/WebappResourceLoader.java
 Fri Jan 27 17:02:44 2012
@@ -18,8 +18,12 @@
 
 package org.apache.roller.weblogger.ui.rendering.velocity;
 
+import java.io.File;
 import java.io.InputStream;
+import java.util.HashMap;
+
 import javax.servlet.ServletContext;
+
 import org.apache.commons.collections.ExtendedProperties;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
@@ -28,94 +32,273 @@ import org.apache.velocity.exception.Res
 import org.apache.velocity.runtime.resource.Resource;
 import org.apache.velocity.runtime.resource.loader.ResourceLoader;
 
-
 /**
  * Loads Velocity resources from the webapp.
- *
- * All resource urls begin from the root of the webapp.  If a resource path
- * is relative (does not begin with a /) then it is prefixed with the path
+ * 
+ * All resource urls begin from the root of the webapp. If a resource path is
+ * relative (does not begin with a /) then it is prefixed with the path
  * /WEB-INF/velocity/, which is where Roller keeps its velocity files.
+ * 
+ * Resource loader that uses the ServletContext of a webapp to load Velocity
+ * templates. (it's much easier to use with servlets than the standard
+ * FileResourceLoader, in particular the use of war files is transparent).
+ * 
+ * The default search path is '/' (relative to the webapp root), but you can
+ * change this behaviour by specifying one or more paths by mean of as many
+ * webapp.resource.loader.path properties as needed in the velocity.properties
+ * file.
+ * 
+ * All paths must be relative to the root of the webapp.
+ * 
+ * To enable caching and cache refreshing the webapp.resource.loader.cache and
+ * webapp.resource.loader.modificationCheckInterval properties need to be set 
in
+ * the velocity.properties file ... auto-reloading of global macros requires 
the
+ * webapp.resource.loader.cache property to be set to 'false'.
+ * 
  */
 public class WebappResourceLoader extends ResourceLoader {
-    
-    private static Log logger = LogFactory.getLog(WebappResourceLoader.class);
-    
-    private ServletContext mContext = null;
-    
-    
-    /**
-     * @see 
org.apache.velocity.runtime.resource.loader.ResourceLoader#init(org.apache.commons.collections.ExtendedProperties)
-     */
-    public void init(ExtendedProperties config) {
-        
-        logger.debug("WebappResourceLoader : initialization starting.");
-        
-        if (mContext == null) {
-            mContext = RollerContext.getServletContext();
-            logger.debug("Servlet Context = 
"+mContext.getRealPath("/WEB-INF/velocity/"));
-        }
-        
-        logger.debug(config);
-        
-        logger.debug("WebappResourceLoader : initialization complete.");
-    }
-    
-    
-    /**
-     * @see 
org.apache.velocity.runtime.resource.loader.ResourceLoader#getResourceStream(java.lang.String)
-     */
-    public InputStream getResourceStream(String name) 
-            throws ResourceNotFoundException {
-        
-               logger.debug("Looking for resource: " + name);
-        
-        if (name == null || name.length() == 0) {
-            throw new ResourceNotFoundException("No template name provided");
-        }
-        
-               if (name.contains("|")) {
-                       String[] pair = name.split("\\|");
-                       name = pair[0];
+
+       private static Log log = LogFactory.getLog(WebappResourceLoader.class);
+
+       // The root paths for templates (relative to webapp's root).
+       protected String[] paths = null;
+       protected HashMap<String, String> templatePaths = null;
+       protected ServletContext servletContext = null;
+
+       /**
+        * This is abstract in the base class, so we need it. <br>
+        * NOTE: this expects that the ServletContext has already been placed 
in the
+        * runtime's application attributes under its full class name (i.e.
+        * "javax.servlet.ServletContext").
+        * 
+        * @param configuration
+        *            the {@link ExtendedProperties} associated with this 
resource
+        *            loader.
+        */
+       public void init(ExtendedProperties configuration) {
+
+               if (log.isDebugEnabled())
+                       log.debug("WebappResourceLoader: initialization 
starting.");
+
+               // get configured paths
+               paths = configuration.getStringArray("path");
+               if (paths == null || paths.length == 0) {
+                       paths = new String[1];
+                       paths[0] = "/";
+               } else {
+                       // make sure the paths end with a '/'
+                       for (int i = 0; i < paths.length; i++) {
+                               if (!paths[i].endsWith("/")) {
+                                       paths[i] += '/';
+                               }
+                               if (log.isDebugEnabled())
+                                       log.debug("WebappResourceLoader: added 
template path - '"
+                                                       + paths[i] + "'");
+                       }
                }
-                               
+
+               // get the ServletContext
+               servletContext = RollerContext.getServletContext();
+
+               if (log.isDebugEnabled())
+                       log.debug("Servlet Context = "
+                                       + 
servletContext.getRealPath("/WEB-INF/velocity/"));
+
+               // init the template paths map
+               templatePaths = new HashMap<String, String>();
+
+               if (log.isDebugEnabled())
+                       log.debug("WebappResourceLoader: initialization 
complete.");
+       }
+
+       /**
+        * Get an InputStream so that the Runtime can build a template with it.
+        * 
+        * @param name
+        *            name of template to get
+        * @return InputStream containing the template
+        * @throws ResourceNotFoundException
+        *             if template not found in classpath.
+        */
+       public InputStream getResourceStream(String name)
+                       throws ResourceNotFoundException {
+
                InputStream result = null;
-        
-        try {
-            if(!name.startsWith("/")) {
-                name = "/WEB-INF/velocity/" + name;
+               Exception exception = null;
+
+               if (name == null || name.length() == 0) {
+                       throw new ResourceNotFoundException(
+                                       "WebappResourceLoader: No template name 
provided");
+               }
+
+               // names are <template>|<deviceType>
+               // loading weblog.vm etc will not have the type so only check 
for
+               // one.
+               String[] split = name.split("\\|", 2);
+               if (split.length < 1) {
+                       throw new ResourceNotFoundException("Invalid ThemeRL 
key " + name);
+               }
+
+               String savedPath = (String) templatePaths.get(name);
+               if (savedPath != null) {
+                       result = servletContext.getResourceAsStream(savedPath + 
split[0]);
+               }
+
+               if (result == null) {
+
+                       for (int i = 0; i < paths.length; i++) {
+
+                               String path = paths[i] + split[0];
+
+                               try {
+
+                                       result = 
servletContext.getResourceAsStream(path);
+
+                                       // save the path and exit the loop if 
we found the template
+                                       if (result != null) {
+                                               templatePaths.put(name, 
paths[i]);
+                                               break;
+                                       }
+
+                               } catch (NullPointerException npe) {
+                                       // no servletContext was set, whine 
about it!
+                                       throw npe;
+                               } catch (Exception e) {
+                                       // only save the first one for later 
throwing
+                                       if (exception == null) {
+                                               if (log.isDebugEnabled()) {
+                                                       
log.debug("WebappResourceLoader: Could not load "
+                                                                       + path, 
e);
+                                               }
+                                               exception = e;
+                                       }
+                               }
                        }
-            result = this.mContext.getResourceAsStream(name);
-            
-        } catch(Exception e) {
-            throw new ResourceNotFoundException(e.getMessage());
-        }
-        
-        if (result == null) {
-            throw new ResourceNotFoundException("Couldn't find "+name);
-        }
-        
-        return result;
-    }
-    
-    
-    /**
-     * Files loaded by this resource loader are considered static, so they are
-     * never reloaded by velocity.
-     *
-     * @see 
org.apache.velocity.runtime.resource.loader.ResourceLoader#isSourceModified(org.apache.velocity.runtime.resource.Resource)
-     */
-    public boolean isSourceModified(Resource arg0) {
-        return false;
-    }
-    
-    
-    /**
-     * Defaults to return 0.
-     *
-     * @see 
org.apache.velocity.runtime.resource.loader.ResourceLoader#getLastModified(org.apache.velocity.runtime.resource.Resource)
-     */
-    public long getLastModified(Resource arg0) {
-        return 0;
-    }
-    
-}
+               }
+
+               // If we never found the template
+               if (result == null) {
+                       String msg = "WebappResourceLoader: Resource '" + name
+                                       + "' not found.";
+
+                       // convert to a general Velocity 
ResourceNotFoundException
+                       if (exception == null) {
+                               throw new ResourceNotFoundException(msg);
+                       } else {
+                               msg += "  Due to: " + exception;
+                               throw new ResourceNotFoundException(msg, 
exception);
+                       }
+               }
+
+               return result;
+       }
+
+       /**
+        * Gets the cached file.
+        * 
+        * @param rootPath
+        *            the root path
+        * @param fileName
+        *            the file name
+        * 
+        * @return the cached file
+        */
+       private File getCachedFile(String rootPath, String fileName) {
+
+               // We do this when we cache a resource, so do it again to 
ensure a match
+               while (fileName.startsWith("/")) {
+                       fileName = fileName.substring(1);
+               }
+
+               String savedPath = (String) templatePaths.get(fileName);
+
+               // names are <template>|<deviceType>
+               // loading weblog.vm etc will not have the type so only check 
for
+               // one.
+               String[] split = fileName.split("\\|", 2);
+               return new File(rootPath + savedPath, split[0]);
+
+       }
+
+       /**
+        * Checks to see if a resource has been deleted, moved or modified. When
+        * using the resource.loader.cache=true option
+        * 
+        * @param resource
+        *            Resource The resource to check for modification
+        * 
+        * @return boolean True if the resource has been modified
+        */
+       public boolean isSourceModified(Resource resource) {
+
+               String rootPath = servletContext.getRealPath("/");
+               if (rootPath == null) {
+                       // RootPath is null if the servlet container cannot 
translate the
+                       // virtual path to a real path for any reason (such as 
when the
+                       // content is being made available from a .war archive)
+                       return false;
+               }
+
+               // first, try getting the previously found file
+               String fileName = resource.getName();
+               File cachedFile = getCachedFile(rootPath, fileName);
+               if (!cachedFile.exists()) {
+                       // then the source has been moved and/or deleted
+                       return true;
+               }
+
+               /*
+                * Check to see if the file can now be found elsewhere before 
it is
+                * found in the previously saved path
+                */
+               File currentFile = null;
+               for (int i = 0; i < paths.length; i++) {
+                       currentFile = new File(rootPath + paths[i], fileName);
+                       if (currentFile.canRead()) {
+                               /*
+                                * stop at the first resource found (just like 
in
+                                * getResourceStream())
+                                */
+                               break;
+                       }
+               }
+
+               // If the current is the cached and it is readable
+               if (cachedFile.equals(currentFile) && cachedFile.canRead()) {
+                       // then (and only then) do we compare the last modified 
values
+                       return (cachedFile.lastModified() != 
resource.getLastModified());
+               } else {
+                       // We found a new file for the resource or the resource 
is no longer
+                       // readable.
+                       return true;
+               }
+       }
+
+       /**
+        * Checks to see when a resource was last modified
+        * 
+        * @param resource
+        *            Resource the resource to check
+        * 
+        * @return long The time when the resource was last modified or 0 if the
+        *         file can't be read
+        */
+       public long getLastModified(Resource resource) {
+
+               String rootPath = servletContext.getRealPath("/");
+               if (rootPath == null) {
+                       // RootPath is null if the servlet container cannot 
translate the
+                       // virtual path to a real path for any reason (such as 
when the
+                       // content is being made available from a .war archive)
+                       return 0;
+               }
+
+               File cachedFile = getCachedFile(rootPath, resource.getName());
+               if (cachedFile.canRead()) {
+                       return cachedFile.lastModified();
+               } else {
+                       return 0;
+               }
+
+       }
+}
\ No newline at end of file

Modified: 
roller/trunk/weblogger-webapp/src/main/webapp/WEB-INF/velocity.properties
URL: 
http://svn.apache.org/viewvc/roller/trunk/weblogger-webapp/src/main/webapp/WEB-INF/velocity.properties?rev=1236763&r1=1236762&r2=1236763&view=diff
==============================================================================
--- roller/trunk/weblogger-webapp/src/main/webapp/WEB-INF/velocity.properties 
(original)
+++ roller/trunk/weblogger-webapp/src/main/webapp/WEB-INF/velocity.properties 
Fri Jan 27 17:02:44 2012
@@ -38,10 +38,13 @@ class.resource.loader.cache=true
 class.resource.loader.modificationCheckInterval=60
 
 # for the loader we call 'webapp', use the WebappResourceLoader
-webapp.resource.loader.description = Roller Webapp Resource Loader
-webapp.resource.loader.class = 
org.apache.roller.weblogger.ui.rendering.velocity.WebappResourceLoader
+webapp.resource.loader.description=Webapp Resource Loader
+webapp.resource.loader.class=org.apache.roller.weblogger.ui.rendering.velocity.WebappResourceLoader
 webapp.resource.loader.cache=true
+#webapp.resource.loader.cache=false
+webapp.resource.loader.path=/WEB-INF/velocity,/WEB-INF/velocity/templates,/WEB-INF/velocity/templates/feeds,templates/weblog,templates/planet
 webapp.resource.loader.modificationCheckInterval=60
+#webapp.resource.loader.modificationCheckInterval=2
 
 # log invalid template references?
 # set this to false to have a quieter velocity.log
@@ -54,9 +57,14 @@ runtime.log.logsystem.log4j.category=org
 # Override the default global library, set to blank to load no default
 velocimacro.library = weblog.vm,feeds.vm,roller-custom.vm
 
+# To reload via WebappResourceLoader change above: cache=false and 
modificationCheckInterval=2
+# and then below autoreload=true.  The trigger is via the theme reloading 
property themes.reload.mode=true
+# ie change required file (under path /WEB-INF/velocity), then a template on 
the theme currently working on 
+# and refresh.
 # Change to false for deployment environments.
 # Caching for the 'class' & 'webapp' ResourceLoaders must be false for this to 
work
-velocimacro.library.autoreload=true
+velocimacro.library.autoreload=false
+#velocimacro.library.autoreload=true
 
 # Allow Velocimacros to be defined in regular templates
 velocimacro.permissions.allow.inline=true


Reply via email to