1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.springframework.extensions.webscripts.processor;
20
21 import groovy.lang.Binding;
22 import groovy.lang.GroovyShell;
23 import groovy.lang.Script;
24
25 import java.io.ByteArrayInputStream;
26 import java.io.InputStream;
27 import java.io.Writer;
28 import java.util.Map;
29
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
32 import org.springframework.extensions.surf.core.scripts.ScriptException;
33 import org.springframework.extensions.webscripts.ScriptContent;
34 import org.springframework.extensions.webscripts.processor.AbstractScriptProcessor;
35
36
37
38
39 public class GroovyScriptProcessor extends AbstractScriptProcessor
40 {
41 private static final Log logger = LogFactory.getLog(GroovyScriptProcessor.class);
42
43
44
45
46 public String getExtension()
47 {
48 return "groovy";
49 }
50
51
52
53
54 public String getName()
55 {
56 return "groovy";
57 }
58
59
60
61
62
63
64
65
66
67 private Object executeGroovyScript(InputStream is, Writer out, Map<String, Object> model)
68 {
69 try
70 {
71 GroovyShell shell = new GroovyShell();
72 Script script = shell.parse(is);
73
74 this.addProcessorModelExtensions(model);
75
76 Binding binding = new Binding(model);
77 for(String name : processorExtensions.keySet())
78 {
79 binding.setProperty(name, processorExtensions.get(name));
80 }
81 binding.setProperty("out", out);
82 script.setBinding(binding);
83
84 return script.run();
85 }
86 catch (Exception exception)
87 {
88 throw new ScriptException("Error executing groovy script", exception);
89 }
90 }
91
92
93
94
95 public Object executeGroovyString(String script, Map<String, Object> model)
96 {
97 return executeGroovyScript(new ByteArrayInputStream(script.getBytes()), null, model);
98 }
99
100
101
102
103
104 public void init()
105 {
106 super.init();
107
108
109 }
110
111
112
113
114 public ScriptContent findScript(String path)
115 {
116 return getScriptLoader().getScript(path);
117 }
118
119
120
121
122 public Object executeScript(String path, Map<String, Object> model)
123 {
124 ScriptContent scriptContent = findScript(path);
125 if (scriptContent == null)
126 {
127 throw new ScriptException("Unable to locate: " + path);
128 }
129
130 return executeScript(scriptContent, model);
131 }
132
133
134
135
136 public Object executeScript(ScriptContent scriptContent, Map<String, Object> model)
137 {
138 return executeGroovyScript(scriptContent.getInputStream(), null, model);
139 }
140
141
142
143
144 public Object unwrapValue(Object value)
145 {
146 return value;
147 }
148
149
150
151
152 public void reset()
153 {
154 init();
155 }
156 }