1 package ar.com.jiji.kaya.scripting;
2
3 import groovy.lang.Binding;
4 import groovy.lang.GroovyClassLoader;
5 import groovy.lang.GroovyShell;
6
7 import java.io.InputStream;
8 import java.util.HashMap;
9 import java.util.Map;
10
11 import org.codehaus.groovy.control.CompilationFailedException;
12
13 /**
14 *
15 */
16
17 /**
18 * @author lparra
19 *
20 */
21 public class ScriptingEngine {
22
23 private GroovyClassLoader gcl;
24
25 private Map<String, Class> loaded;
26
27 protected ScriptingEngine() {
28 gcl = new GroovyClassLoader();
29 loaded = new HashMap<String, Class>();
30 }
31
32 private static ScriptingEngine scriptingEngine;
33
34 public synchronized static ScriptingEngine getInstance() {
35 if (scriptingEngine == null)
36 scriptingEngine = new ScriptingEngine();
37 return scriptingEngine;
38 }
39
40 /**
41 * Lee un script y devuelve una instancia de el.
42 *
43 * @param scriptName
44 * El nombre del script en el classpath.
45 * @throws ScriptingException
46 * @return Nunca devuelve null
47 */
48 @SuppressWarnings("unchecked")
49 public Object getScript(String scriptName) throws ScriptingException {
50 try {
51 Class clazz = loaded.get(scriptName);
52 if (clazz == null) {
53 InputStream in = GroovyClassLoader
54 .getSystemResourceAsStream(scriptName);
55 if (in == null)
56 throw new ScriptNotFoundException(scriptName);
57 clazz = gcl.parseClass(in);
58 loaded.put(scriptName, clazz);
59 }
60 return clazz.newInstance();
61 } catch (CompilationFailedException e) {
62 throw new ScriptingException(e);
63 } catch (InstantiationException e) {
64 throw new ScriptingException(e);
65 } catch (IllegalAccessException e) {
66 throw new ScriptingException(e);
67 }
68 }
69
70 /**
71 * Evalua el script.
72 *
73 * @param code
74 * @return
75 */
76 public Object evaluate(String code) {
77 return evaluate(code, null);
78 }
79
80 /**
81 * Evalua el script y le pasa un contexto.
82 *
83 * @param code
84 * @return
85 */
86 public Object evaluate(String code, Map<String, Object> ctx)
87 throws ScriptingException {
88 try {
89
90 Binding binding = new Binding(ctx);
91 GroovyShell gsh = new GroovyShell(binding);
92 return gsh.evaluate(code);
93 } catch (CompilationFailedException e) {
94 throw new ScriptingException(e);
95 }
96 }
97 }