1 17 package org.oddjob.script; 18 19 import java.util.HashMap ; 20 import java.util.Iterator ; 21 import java.util.Map ; 22 23 import org.apache.bsf.BSFException; 24 import org.apache.bsf.BSFManager; 25 import org.apache.tools.ant.BuildException; 26 27 31 public class ScriptRunner { 32 33 static { 39 BSFManager.registerScriptingEngine( 40 "groovy", 41 "org.codehaus.groovy.bsf.GroovyEngine", 42 new String [] {"groovy", "gy"}); 43 } 44 45 46 private String language; 47 48 49 private String script = ""; 50 51 52 private Map beans = new HashMap (); 53 54 55 61 public void addBeans(Map dictionary) { 62 for (Iterator i = dictionary.keySet().iterator(); i.hasNext();) { 63 String key = (String ) i.next(); 64 try { 65 Object val = dictionary.get(key); 66 addBean(key, val); 67 } catch (BuildException ex) { 68 } 73 } 74 } 75 76 82 public void addBean(String key, Object bean) { 83 boolean isValid = key.length() > 0 84 && Character.isJavaIdentifierStart(key.charAt(0)); 85 86 for (int i = 1; isValid && i < key.length(); i++) { 87 isValid = Character.isJavaIdentifierPart(key.charAt(i)); 88 } 89 90 if (isValid) { 91 beans.put(key, bean); 92 } 93 } 94 95 103 public void executeScript(String execName) throws BuildException { 104 if (language == null) { 105 throw new BuildException("script language must be specified"); 106 } 107 108 try { 109 BSFManager manager = new BSFManager (); 110 111 for (Iterator i = beans.keySet().iterator(); i.hasNext();) { 112 String key = (String ) i.next(); 113 Object value = beans.get(key); 114 if (value != null) { 115 manager.declareBean(key, value, value.getClass()); 116 } else { 117 manager.undeclareBean(key); 122 } 123 } 124 125 manager.exec(language, execName, 0, 0, script); 127 } catch (BSFException be) { 128 Throwable t = be; 129 Throwable te = be.getTargetException(); 130 if (te != null) { 131 if (te instanceof BuildException) { 132 throw (BuildException) te; 133 } else { 134 t = te; 135 } 136 } 137 throw new BuildException(t); 138 } 139 } 140 141 146 public void setLanguage(String language) { 147 this.language = language; 148 } 149 150 155 public String getLanguage() { 156 return language; 157 } 158 159 160 public String getScript() { 161 return script; 162 } 163 164 public void setScript(String script) { 165 this.script = script; 166 } 167 } 168 | Popular Tags |