1 31 package org.blojsom.plugin.velocity; 32 33 import org.apache.commons.logging.Log; 34 import org.apache.commons.logging.LogFactory; 35 import org.apache.velocity.VelocityContext; 36 import org.apache.velocity.app.VelocityEngine; 37 import org.blojsom.blog.Blog; 38 import org.blojsom.plugin.Plugin; 39 import org.blojsom.plugin.PluginException; 40 import org.blojsom.util.BlojsomConstants; 41 42 import javax.servlet.ServletConfig ; 43 import javax.servlet.ServletContext ; 44 import java.io.StringWriter ; 45 import java.util.Map ; 46 import java.util.Properties ; 47 48 55 public abstract class StandaloneVelocityPlugin implements Plugin { 56 57 protected Log _logger = LogFactory.getLog(StandaloneVelocityPlugin.class); 58 59 protected Properties _velocityProperties; 60 protected ServletConfig _servletConfig; 61 62 70 public void init() throws PluginException { 71 } 72 73 78 public void setVelocityProperties(Properties velocityProperties) { 79 _velocityProperties = velocityProperties; 80 } 81 82 87 public void setServletConfig(ServletConfig servletConfig) { 88 _servletConfig = servletConfig; 89 } 90 91 100 protected String mergeTemplate(String template, Blog blog, Map context) { 101 ServletContext servletContext = _servletConfig.getServletContext(); 102 103 VelocityEngine velocityEngine = new VelocityEngine(); 105 106 try { 107 Properties updatedVelocityProperties = (Properties ) _velocityProperties.clone(); 108 updatedVelocityProperties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, servletContext.getRealPath("/WEB-INF/" 109 + "blogs/" + blog.getBlogId() + "/templates/") + ", " + servletContext.getRealPath("/WEB-INF/templates/")); 110 velocityEngine.init(updatedVelocityProperties); 111 } catch (Exception e) { 112 if (_logger.isErrorEnabled()) { 113 _logger.error(e); 114 } 115 116 return null; 117 } 118 119 StringWriter writer = new StringWriter (); 120 121 VelocityContext velocityContext = new VelocityContext(context); 123 124 if (!velocityEngine.templateExists(template)) { 125 if (_logger.isErrorEnabled()) { 126 _logger.error("Could not find template for user: " + template); 127 } 128 129 return null; 130 } else { 131 try { 132 velocityEngine.mergeTemplate(template, BlojsomConstants.UTF8, velocityContext, writer); 133 } catch (Exception e) { 134 if (_logger.isErrorEnabled()) { 135 _logger.error(e); 136 } 137 138 return null; 139 } 140 } 141 142 if (_logger.isDebugEnabled()) { 143 _logger.debug("Merged template: " + template); 144 } 145 146 return writer.toString(); 147 } 148 } | Popular Tags |