1 46 package groovy.lang; 47 48 import org.codehaus.groovy.ast.expr.ArgumentListExpression; 49 import org.codehaus.groovy.control.CompilationFailedException; 50 import org.codehaus.groovy.runtime.InvokerHelper; 51 52 import java.io.File ; 53 import java.io.IOException ; 54 55 62 public abstract class Script extends GroovyObjectSupport { 63 private Binding binding = new Binding(); 64 65 protected Script() { 66 } 67 68 protected Script(Binding binding) { 69 this.binding = binding; 70 } 71 72 public Binding getBinding() { 73 return binding; 74 } 75 76 public void setBinding(Binding binding) { 77 this.binding = binding; 78 } 79 80 public Object getProperty(String property) { 81 try { 83 return binding.getVariable(property); 84 } catch (MissingPropertyException e) { 85 return super.getProperty(property); 86 } 87 } 88 89 public void setProperty(String property, Object newValue) { 90 binding.setVariable(property, newValue); 92 } 94 95 102 public Object invokeMethod(String name, Object args) { 103 try { 104 return super.invokeMethod(name, args); 105 } 106 catch (MissingMethodException mme) { 109 try { 110 if (name.equals(mme.getMethod())) { 111 Object boundClosure = binding.getVariable(name); 112 if (boundClosure != null && boundClosure instanceof Closure) { 113 return ((Closure) boundClosure).call(args); 114 } else { 115 throw mme; 116 } 117 } else { 118 throw mme; 119 } 120 } catch (MissingPropertyException mpe) { 121 throw mme; 122 } 123 } 124 } 125 126 132 public abstract Object run(); 133 134 136 141 public void println() { 142 Object object; 143 144 try { 145 object = getProperty("out"); 146 } catch (MissingPropertyException e) { 147 System.out.println(); 148 return; 149 } 150 151 InvokerHelper.invokeMethod(object, "println", ArgumentListExpression.EMPTY_ARRAY); 152 } 153 154 159 public void print(Object value) { 160 Object object; 161 162 try { 163 object = getProperty("out"); 164 } catch (MissingPropertyException e) { 165 System.out.print(value); 166 return; 167 } 168 169 InvokerHelper.invokeMethod(object, "print", new Object []{value}); 170 } 171 172 177 public void println(Object value) { 178 Object object; 179 180 try { 181 object = getProperty("out"); 182 } catch (MissingPropertyException e) { 183 System.out.println(value); 184 return; 185 } 186 187 InvokerHelper.invokeMethod(object, "println", new Object []{value}); 188 } 189 190 196 public Object evaluate(String expression) throws CompilationFailedException, IOException { 197 GroovyShell shell = new GroovyShell(binding); 198 return shell.evaluate(expression); 199 } 200 201 207 public Object evaluate(File file) throws CompilationFailedException, IOException { 208 GroovyShell shell = new GroovyShell(binding); 209 return shell.evaluate(file); 210 } 211 212 215 public void run(File file, String [] arguments) throws CompilationFailedException, IOException { 216 GroovyShell shell = new GroovyShell(binding); 217 shell.run(file, arguments); 218 } 219 } 220 | Popular Tags |