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.IOException;
23 import java.io.PrintStream;
24 import java.io.UncheckedIOException;
25 import java.net.MalformedURLException;
26 import java.net.URL;
27 import java.util.List;
28 import java.util.Map;
29
30 import groovy.lang.Binding;
31 import groovy.lang.GroovyShell;
32 import org.codehaus.groovy.control.CompilerConfiguration;
33 import org.codehaus.groovy.tools.RootLoader;
34
35
36
37
38
39
40 class GroovyScriptInterpreter implements ScriptInterpreter {
41
42 private final RootLoader childFirstLoader =
43 new RootLoader(new URL[] {}, Thread.currentThread().getContextClassLoader());
44
45 @Override
46 public void setClassPath(List<String> classPath) {
47 if (classPath == null || classPath.isEmpty()) {
48 return;
49 }
50
51 classPath.stream().map(this::toUrl).forEach(childFirstLoader::addURL);
52 }
53
54 private URL toUrl(String path) {
55 try {
56 return new File(path).toURI().toURL();
57 } catch (MalformedURLException e) {
58 throw new UncheckedIOException(e);
59 }
60 }
61
62
63
64
65 @Override
66 public Object evaluateScript(String script, Map<String, ?> globalVariables, PrintStream scriptOutput)
67 throws ScriptEvaluationException {
68 PrintStream origOut = System.out;
69 PrintStream origErr = System.err;
70
71 try {
72
73 if (scriptOutput != null) {
74 System.setErr(scriptOutput);
75 System.setOut(scriptOutput);
76 }
77
78 GroovyShell interpreter = new GroovyShell(
79 childFirstLoader,
80 new Binding(globalVariables),
81 new CompilerConfiguration(CompilerConfiguration.DEFAULT));
82
83 return interpreter.evaluate(script);
84 } catch (Throwable e) {
85 throw new ScriptEvaluationException(e);
86 } finally {
87 System.setErr(origErr);
88 System.setOut(origOut);
89 }
90 }
91
92 @Override
93 public void close() throws IOException {
94 childFirstLoader.close();
95 }
96 }