1 package org.sapia.validator.rules.groovy; 2 3 import groovy.lang.GroovyClassLoader; 4 5 import java.io.ByteArrayInputStream ; 6 import java.util.Random ; 7 8 import org.sapia.util.xml.confix.ConfigurationException; 9 import org.sapia.validator.Rule; 10 import org.sapia.validator.ValidationContext; 11 12 24 public class GroovyRule extends Rule{ 25 26 private static final Random RAND = new Random (); 27 28 private String _name; 29 private String _src; 30 private Rule _inner; 31 private StringBuffer _imports = new StringBuffer (); 32 33 public void addImport(String imp) { 34 _imports.append("import ").append(imp).append(';'); 35 } 36 37 public void setImport(String imp) { 38 addImport(imp); 39 } 40 41 44 public Object onCreate() throws ConfigurationException { 45 super.onCreate(); 46 try { 47 Class clazz = generate(); 48 _inner = (Rule) clazz.newInstance(); 49 _inner.setId(getId()); 50 _inner.setErrorMessages(getErrorMessages()); 51 return this; 52 } catch (RuntimeException e) { 53 throw e; 54 } catch (Exception e) { 55 throw new ConfigurationException("Could not generate Groovy code for: " + 56 _src, e); 57 } 58 } 59 60 public void setText(String src) throws Exception { 61 _src = src; 62 } 63 64 65 68 public void validate(ValidationContext context) { 69 if (_inner == null) { 70 throw new IllegalStateException ("Source code not defined"); 71 } 72 73 _inner.validate(context); 74 } 75 76 private synchronized Class generate() throws Exception { 77 if (_src == null) { 78 throw new IllegalStateException ("Groovy source not specified"); 79 } 80 81 String src = _src; 82 83 long id = RAND.nextLong(); 84 if(id < 0) id = -id; 85 src = _imports.toString() + " class Vlad_Groovy_Rule_Java_" + 86 id + " extends " + Rule.class.getName() + " {" + 87 " public void validate(" + ValidationContext.class.getName() + " context){" + _src + " }" + 88 89 "}"; 90 91 ByteArrayInputStream bis = new ByteArrayInputStream (src.getBytes()); 92 GroovyClassLoader loader = new GroovyClassLoader(Thread.currentThread() 93 .getContextClassLoader()); 94 95 return loader.parseClass(bis, getClass().getName()); 96 } 97 98 99 } 100 101 102 | Popular Tags |