| 1 package org.sapia.soto.state.code; 2 3 import instantj.compile.CompilationFailedException; 4 import instantj.compile.Compiler; 5 import instantj.compile.Source; 6 7 import org.apache.commons.lang.ClassUtils; 8 import org.apache.commons.lang.math.JVMRandom; 9 10 import org.sapia.soto.state.Result; 11 import org.sapia.soto.state.Step; 12 13 import java.io.ByteArrayOutputStream ; 14 import java.io.PrintStream ; 15 16 17 25 public class JavaStep implements Step { 26 static { 27 System.setProperty("instantj.compile.compiler", 28 "instantj.compile.pizza.PizzaSourceCompiler"); 29 } 30 31 private String _name; 32 private Step _inner; 33 34 37 public JavaStep() { 38 } 39 40 public void setName(String name) { 41 _name = name; 42 } 43 44 47 public String getName() { 48 if (_name == null) { 49 return ClassUtils.getShortClassName(getClass()); 50 } 51 52 return _name; 53 } 54 55 public void setText(String src) throws Exception { 56 try { 57 Class clazz = generate(src); 58 _inner = (Step) clazz.newInstance(); 59 } catch (CompilationFailedException e) { 60 ByteArrayOutputStream bos = new ByteArrayOutputStream (); 61 PrintStream ps = new PrintStream (bos); 62 e.printErrors(ps); 63 ps.flush(); 64 ps.close(); 65 throw new CompilationFailedException(bos.toString()); 66 } 67 } 68 69 72 public void execute(Result st) { 73 if (_inner == null) { 74 throw new IllegalStateException ("Source code not defined"); 75 } 76 77 _inner.execute(st); 78 } 79 80 private Class generate(String src) throws Exception { 81 src = "public class Soto_State_Java_" + new JVMRandom().nextLong() + 82 " implements org.sapia.soto.state.Step{" + 83 " public String getName(){ return \"" + getName() + "\"; }" + 84 " public void execute(org.sapia.soto.state.Result result){" + src + 85 " }" + "}"; 86 87 return Compiler.compile(new Source(src), true).getType(); 88 } 89 90 } 100 | Popular Tags |