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 ClassLoader curentClassLoader = Thread.currentThread().getContextClassLoader();
72 try {
73
74 if (scriptOutput != null) {
75 System.setErr(scriptOutput);
76 System.setOut(scriptOutput);
77 }
78
79 GroovyShell interpreter = new GroovyShell(
80 childFirstLoader,
81 new Binding(globalVariables),
82 new CompilerConfiguration(CompilerConfiguration.DEFAULT));
83
84 Thread.currentThread().setContextClassLoader(childFirstLoader);
85 return interpreter.evaluate(script);
86 } catch (Throwable e) {
87 throw new ScriptEvaluationException(e);
88 } finally {
89 Thread.currentThread().setContextClassLoader(curentClassLoader);
90 System.setErr(origErr);
91 System.setOut(origOut);
92 }
93 }
94
95 @Override
96 public void close() throws IOException {
97 childFirstLoader.close();
98 }
99 }