1
14
15 package com.liferay.portal.scripting.groovy;
16
17 import com.liferay.portal.kernel.cache.SingleVMPoolUtil;
18 import com.liferay.portal.kernel.scripting.ExecutionException;
19 import com.liferay.portal.kernel.scripting.ScriptingException;
20 import com.liferay.portal.kernel.scripting.ScriptingExecutor;
21
22 import groovy.lang.Binding;
23 import groovy.lang.GroovyShell;
24 import groovy.lang.Script;
25
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.Set;
29
30
36 public class GroovyExecutor implements ScriptingExecutor {
37
38 public static final String CACHE_NAME = GroovyExecutor.class.getName();
39
40 public static final String LANGUAGE = "groovy";
41
42 public void clearCache() {
43 SingleVMPoolUtil.clear(CACHE_NAME);
44 }
45
46 public String getLanguage() {
47 return LANGUAGE;
48 }
49
50 public Map<String, Object> eval(
51 Set<String> allowedClasses, Map<String, Object> inputObjects,
52 Set<String> outputNames, String script)
53 throws ScriptingException {
54
55 if (allowedClasses != null) {
56 throw new ExecutionException(
57 "Constrained execution not supported for Groovy");
58 }
59
60 Script compiledScript = getCompiledScript(script);
61
62 Binding binding = new Binding(inputObjects);
63
64 compiledScript.setBinding(binding);
65
66 compiledScript.run();
67
68 if (outputNames == null) {
69 return null;
70 }
71
72 Map<String, Object> outputObjects = new HashMap<String, Object>();
73
74 for (String outputName : outputNames) {
75 outputObjects.put(outputName, binding.getVariable(outputName));
76 }
77
78 return outputObjects;
79 }
80
81 protected Script getCompiledScript(String script) {
82 if (_groovyShell == null) {
83 synchronized (this) {
84 _groovyShell = new GroovyShell();
85 }
86 }
87
88 String key = String.valueOf(script.hashCode());
89
90 Script compiledScript = (Script)SingleVMPoolUtil.get(CACHE_NAME, key);
91
92 if (compiledScript == null) {
93 compiledScript = _groovyShell.parse(script);
94
95 SingleVMPoolUtil.put(CACHE_NAME, key, compiledScript);
96 }
97
98 return compiledScript;
99 }
100
101 private GroovyShell _groovyShell;
102
103 }