1 package org.apache.maven.shared.scriptinterpreter;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import groovy.lang.Binding;
23 import groovy.lang.GroovyShell;
24 import org.apache.tools.ant.AntClassLoader;
25 import org.codehaus.groovy.control.CompilerConfiguration;
26 import org.codehaus.plexus.component.annotations.Component;
27
28 import java.io.File;
29 import java.io.PrintStream;
30 import java.io.PrintWriter;
31 import java.util.List;
32 import java.util.Map;
33
34
35
36
37
38
39
40 @Component( role = ScriptInterpreter.class, hint = "groovy" )
41 public class GroovyScriptInterpreter
42 implements ScriptInterpreter
43 {
44
45
46
47
48 public Object evaluateScript( String script, List<String> classPath, Map<String, ? extends Object> globalVariables,
49 PrintStream scriptOutput )
50 throws ScriptEvaluationException
51 {
52 PrintStream origOut = System.out;
53 PrintStream origErr = System.err;
54
55 try
56 {
57 CompilerConfiguration config = new CompilerConfiguration( CompilerConfiguration.DEFAULT );
58
59 if ( scriptOutput != null )
60 {
61 System.setErr( scriptOutput );
62 System.setOut( scriptOutput );
63 config.setOutput( new PrintWriter( scriptOutput ) );
64 }
65
66 ClassLoader loader = null;
67 if ( classPath != null && !classPath.isEmpty() )
68 {
69 AntClassLoader childFirstLoader = new AntClassLoader( getClass().getClassLoader(), false );
70 for ( String path : classPath )
71 {
72 childFirstLoader.addPathComponent( new File( path ) );
73 }
74 loader = childFirstLoader;
75 }
76
77 Binding binding = new Binding( globalVariables );
78
79 GroovyShell interpreter = new GroovyShell( loader, binding, config );
80
81 try
82 {
83 return interpreter.evaluate( script );
84 }
85 catch ( ThreadDeath e )
86 {
87 throw e;
88 }
89 catch ( Throwable e )
90 {
91 throw new ScriptEvaluationException( e );
92 }
93 }
94 finally
95 {
96 System.setErr( origErr );
97 System.setOut( origOut );
98 }
99 }
100
101 }