1 package br.com.ibnetwork.guara.view.impl; 2 3 import java.io.Writer; 4 5 import org.apache.avalon.framework.configuration.Configurable; 6 import org.apache.avalon.framework.configuration.Configuration; 7 import org.apache.avalon.framework.configuration.ConfigurationException; 8 import org.apache.avalon.framework.service.ServiceException; 9 import org.apache.avalon.framework.service.ServiceManager; 10 import org.apache.avalon.framework.service.Serviceable; 11 import org.apache.commons.logging.Log; 12 import org.apache.commons.logging.LogFactory; 13 14 import br.com.ibnetwork.guara.view.Context; 15 import br.com.ibnetwork.guara.view.TemplateEngine; 16 import br.com.ibnetwork.guara.view.TemplateEngineException; 17 18 public class TemplateEngineImpl 19 extends TemplateEngineSupport 20 implements TemplateEngine, Configurable, Serviceable 21 { 22 private Log log = LogFactory.getLog(TemplateEngineImpl.class); 23 24 private TemplateEngine[] engines; 25 26 private ServiceManager manager; 27 28 public void service(ServiceManager manager) 29 throws ServiceException 30 { 31 this.manager = manager; 32 } 33 34 public void configure(Configuration conf) 35 throws ConfigurationException 36 { 37 super.configure(conf); 38 Configuration[] delegates = conf.getChild("delegates").getChildren("delegate"); 39 engines = new TemplateEngine[delegates.length]; 40 for (int i = 0; i < delegates.length; i++) 41 { 42 Configuration configuration = delegates[i]; 43 String role = configuration.getAttribute("role", TemplateEngine.class.getName()); 44 String key = configuration.getAttribute("key"); 45 try 46 { 47 TemplateEngine engine = (TemplateEngine) manager.lookup(role+":"+key); 48 engines[i] = engine; 49 } 50 catch (Throwable t) 51 { 52 log.error("Can't find template engine with role: "+role,t); 53 engines[i] = NullTemplateEngine.instance(); 54 } 55 } 56 } 57 58 private TemplateEngine getEngineForTemplate(String templateName) 59 throws TemplateEngineException 60 { 61 TemplateEngine result = null; 62 for (int i = 0; i < engines.length; i++) 63 { 64 TemplateEngine engine = engines[i]; 65 if(engine.templateExists(templateName)) 66 { 67 result = engine; 68 break; 69 } 70 } 71 if(result == null) 72 { 73 throw new TemplateEngineException("TemplateEngine not found for template ["+templateName+"]"); 74 } 75 return result; 76 77 } 78 79 public void merge(String templateName, Context context, Writer writer) 80 throws TemplateEngineException 81 { 82 TemplateEngine engine = getEngineForTemplate(templateName); 83 engine.merge(templateName, context, writer); 84 } 85 86 public boolean templateExists(String templateName) 87 throws TemplateEngineException 88 { 89 for (int i = 0; i < engines.length; i++) 90 { 91 TemplateEngine engine = engines[i]; 92 if(engine.templateExists(templateName)) { 93 return true; 94 } 95 } 96 return false; 97 } 98 }