| 1 package org.sapia.soto.state.code; 2 3 import groovy.lang.GroovyClassLoader; 4 5 import org.apache.commons.lang.ClassUtils; 6 import org.apache.commons.lang.math.JVMRandom; 7 8 import org.sapia.soto.state.Result; 9 import org.sapia.soto.state.Step; 10 11 import org.sapia.util.xml.confix.ConfigurationException; 12 import org.sapia.util.xml.confix.ObjectCreationCallback; 13 14 import java.io.ByteArrayInputStream ; 15 16 17 25 public class GroovyStep implements Step, ObjectCreationCallback { 26 private String _name; 27 private String _src; 28 private Step _inner; 29 private StringBuffer _imports = new StringBuffer (); 30 31 public GroovyStep() { 32 } 33 34 public void setName(String name) { 35 _name = name; 36 } 37 38 public void addImport(String imp) { 39 _imports.append("import ").append(imp).append(';'); 40 } 41 42 public void setImport(String imp) { 43 addImport(imp); 44 } 45 46 49 public String getName() { 50 if (_name == null) { 51 return ClassUtils.getShortClassName(getClass()); 52 } 53 54 return _name; 55 } 56 57 60 public Object onCreate() throws ConfigurationException { 61 try { 62 Class clazz = generate(); 63 _inner = (Step) clazz.newInstance(); 64 65 return this; 66 } catch (RuntimeException e) { 67 throw e; 68 } catch (Exception e) { 69 throw new ConfigurationException("Could not generate Groovy code for: " + 70 _src, e); 71 } 72 } 73 74 public void setText(String src) throws Exception { 75 _src = src; 76 77 } 87 88 91 public void execute(Result st) { 92 if (_inner == null) { 93 throw new IllegalStateException ("Source code not defined"); 94 } 95 96 _inner.execute(st); 97 } 98 99 private Class generate() throws Exception { 100 if (_src == null) { 101 throw new IllegalStateException ("Groovy source not specified"); 102 } 103 104 String src = _src; 105 106 src = _imports.toString() + "class Soto_State_Java_" + getName() + "_" + 107 new JVMRandom().nextLong() + " implements org.sapia.soto.state.Step{" + 108 " public String getName(){ return \"" + getName() + "\" }" + 109 " public void execute(" + Result.class.getName() + " result){" + src + 110 " }" + "}"; 111 112 ByteArrayInputStream bis = new ByteArrayInputStream (src.getBytes()); 114 GroovyClassLoader loader = new GroovyClassLoader(Thread.currentThread() 115 .getContextClassLoader()); 116 117 return loader.parseClass(bis, getName()); 118 } 119 } 120 | Popular Tags |