View Javadoc

1   package br.com.ibnetwork.guara.view.impl.velocity;
2   
3   //AVALON
4   import org.apache.avalon.framework.configuration.Configurable;
5   import org.apache.avalon.framework.configuration.Configuration;
6   import org.apache.avalon.framework.configuration.ConfigurationException;
7   import org.apache.avalon.framework.service.ServiceException;
8   import org.apache.avalon.framework.service.ServiceManager;
9   import org.apache.avalon.framework.service.Serviceable;
10  
11  //VELOCITY
12  import org.apache.velocity.Template;
13  import org.apache.velocity.VelocityContext;
14  import org.apache.velocity.app.VelocityEngine;
15  
16  //GUARA
17  import br.com.ibnetwork.guara.view.Context;
18  import br.com.ibnetwork.guara.view.TemplateEngine;
19  import br.com.ibnetwork.guara.view.TemplateEngineException;
20  import br.com.ibnetwork.guara.view.impl.TemplateEngineSupport;
21  
22  //JDK
23  import java.io.Writer;
24  import java.util.Properties;
25  
26  /***
27   * @author <a href="mailto:leandro@ibnetwork.com.br">Leandro Rodrigo Saad Cruz</a>
28   */
29  public class VelocityTemplateEngine
30      extends TemplateEngineSupport
31  	implements TemplateEngine, Serviceable, Configurable
32  {
33  	private VelocityEngine ve;
34  	
35  	public void service(ServiceManager manager) 
36  		throws ServiceException 
37  	{
38  	    ve = new VelocityEngine();
39  	}
40      
41  	public void configure(Configuration conf) 
42  		throws ConfigurationException
43  	{
44  		super.configure(conf);
45          log.debug("Loading velocity configuration from: "+configurationFile);
46          try
47          {
48  			Properties properties = new Properties();
49  			properties.load(configurationFile.openStream());
50  		    ve.init(properties);
51          }
52          catch (Exception e)
53          {
54              throw new ConfigurationException("Error configuring VelocityTemplateEngine",e);
55          }
56  	}
57  
58      public boolean templateExists(String templateName) 
59      	throws TemplateEngineException
60      {
61          String realName = toFileName(templateName);
62          return ve.templateExists(realName);
63      }
64  
65      public void merge(String templateName, Context context, Writer w)
66      	throws TemplateEngineException
67      {
68          String realName = toFileName(templateName);
69          if(log.isDebugEnabled()) log.debug("rendering [" + realName + "]");		
70  		VelocityContext ctx = switchContext(context);
71      	try
72          {
73      	    Template template = ve.getTemplate(realName,encoding);
74      	    template.merge(ctx, w);
75          }
76          catch (Exception e)
77          {            
78  			throw new TemplateEngineException("Error merging template["+realName+"] ", e);
79          }
80      }
81  
82      private VelocityContext switchContext(Context context)
83      {
84          return new VelocityContext(context.getMap());
85      }
86  }