1 5 package xdoclet.modules.apache.bsf; 6 7 import java.io.ByteArrayOutputStream ; 8 import java.io.PrintStream ; 9 10 import java.util.Properties ; 11 import org.apache.bsf.BSFEngine; 12 import org.apache.bsf.BSFException; 13 import org.apache.bsf.BSFManager; 14 import org.apache.bsf.util.ObjectRegistry; 15 import org.apache.commons.logging.Log; 16 import xdoclet.XDocletException; 17 18 import xdoclet.modules.apache.SubTemplateEngine; 19 import xdoclet.util.LogUtil; 20 21 27 public class BsfSubTemplateEngine implements SubTemplateEngine 28 { 29 47 private BSFManager bsfManager; 48 49 50 public BsfSubTemplateEngine() 51 { 52 Log log = LogUtil.getLog(BsfEngineTagHandler.class, "ctor"); 53 54 try { 55 log.debug("Creating BSFManager()"); 56 bsfManager = new BSFManager(); 57 } 58 catch (Exception ex) { 59 log.error("Exception when creating BSFManager", ex); 60 } 61 } 62 63 67 public Object getVariable(String name) 68 { 69 ObjectRegistry objreg = bsfManager.getObjectRegistry(); 70 71 return objreg.lookup(name); 72 } 73 74 78 public void setVariable(String name, Object value) 79 { 80 if (value != null) { 82 ObjectRegistry objreg = bsfManager.getObjectRegistry(); 83 84 objreg.register(name, value); 85 } 86 } 87 88 92 public void clearVariables() 93 { 94 bsfManager.setObjectRegistry(new ObjectRegistry()); 95 } 96 97 101 public String generate(String template, Properties attributes) throws XDocletException 102 { 103 Log log = LogUtil.getLog(BsfEngineTagHandler.class, "generate"); 104 105 log.debug("generate() called with attributes:" + attributes); 106 107 String scriptingEngine = attributes.getProperty("scriptengine"); 108 109 if (scriptingEngine == null) { 110 throw new XDocletException("Missing attribute 'scriptengine' specifying BSF script language"); 111 } 112 113 ByteArrayOutputStream bbuf = new ByteArrayOutputStream (); 115 PrintStream out = new PrintStream (bbuf); 116 117 try { 118 BSFEngine bsfEngine = bsfManager.loadScriptingEngine(scriptingEngine); 119 120 bsfManager.getObjectRegistry().register("out", out); 121 bsfEngine.exec("", 0, 0, template); 122 123 } 124 catch (BSFException e) { 125 throw new XDocletException(e, "Exception when running scriptengine='" + scriptingEngine + "'"); 126 } 127 out.flush(); 128 return bbuf.toString(); 129 } 130 131 } 132 | Popular Tags |