1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.shared.scriptinterpreter;
20
21 import java.io.File;
22 import java.io.PrintStream;
23 import java.net.URL;
24 import java.util.List;
25 import java.util.Map;
26
27 import groovy.lang.Binding;
28 import groovy.lang.GroovyShell;
29 import org.codehaus.groovy.control.CompilerConfiguration;
30 import org.codehaus.groovy.tools.RootLoader;
31
32
33
34
35
36
37 class GroovyScriptInterpreter implements ScriptInterpreter {
38
39
40 @Override
41 public Object evaluateScript(
42 String script,
43 List<String> classPath,
44 Map<String, ? extends Object> globalVariables,
45 PrintStream scriptOutput)
46 throws ScriptEvaluationException {
47 PrintStream origOut = System.out;
48 PrintStream origErr = System.err;
49
50 try (RootLoader childFirstLoader =
51 new RootLoader(new URL[] {}, getClass().getClassLoader())) {
52
53 if (scriptOutput != null) {
54 System.setErr(scriptOutput);
55 System.setOut(scriptOutput);
56 }
57
58 if (classPath != null && !classPath.isEmpty()) {
59 for (String path : classPath) {
60 childFirstLoader.addURL(new File(path).toURI().toURL());
61 }
62 }
63
64 GroovyShell interpreter = new GroovyShell(
65 childFirstLoader,
66 new Binding(globalVariables),
67 new CompilerConfiguration(CompilerConfiguration.DEFAULT));
68
69 return interpreter.evaluate(script);
70 } catch (Throwable e) {
71 throw new ScriptEvaluationException(e);
72 } finally {
73 System.setErr(origErr);
74 System.setOut(origOut);
75 }
76 }
77 }