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 bsh.Capabilities;
23 import bsh.EvalError;
24 import bsh.Interpreter;
25 import bsh.TargetError;
26
27 import java.io.File;
28 import java.io.IOException;
29 import java.io.PrintStream;
30 import java.util.List;
31 import java.util.Map;
32
33 import org.codehaus.plexus.component.annotations.Component;
34
35
36
37
38
39
40
41 @Component( role = ScriptInterpreter.class, hint = "bsh" )
42 public class BeanShellScriptInterpreter
43 implements ScriptInterpreter
44 {
45
46
47
48
49 public Object evaluateScript( String script, List<String> classPath, Map<String, ? extends Object> globalVariables,
50 PrintStream scriptOutput )
51 throws ScriptEvaluationException
52 {
53 PrintStream origOut = System.out;
54 PrintStream origErr = System.err;
55
56 try
57 {
58 Interpreter engine = new Interpreter();
59
60 if ( scriptOutput != null )
61 {
62 System.setErr( scriptOutput );
63 System.setOut( scriptOutput );
64 engine.setErr( scriptOutput );
65 engine.setOut( scriptOutput );
66 }
67
68 if ( !Capabilities.haveAccessibility() )
69 {
70 try
71 {
72 Capabilities.setAccessibility( true );
73 }
74 catch ( Exception e )
75 {
76 if ( scriptOutput != null )
77 {
78 e.printStackTrace( scriptOutput );
79 }
80 }
81 }
82
83 if ( classPath != null && !classPath.isEmpty() )
84 {
85 for ( String path : classPath )
86 {
87 try
88 {
89 engine.getClassManager().addClassPath( new File( path ).toURI().toURL() );
90 }
91 catch ( IOException e )
92 {
93 throw new RuntimeException( "bad class path: " + path, e );
94 }
95 }
96 }
97
98 if ( globalVariables != null )
99 {
100 for ( String variable : globalVariables.keySet() )
101 {
102 Object value = globalVariables.get( variable );
103 try
104 {
105 engine.set( variable, value );
106 }
107 catch ( EvalError e )
108 {
109 throw new RuntimeException( e );
110 }
111 }
112 }
113
114 try
115 {
116 return engine.eval( script );
117 }
118 catch ( TargetError e )
119 {
120 throw new ScriptEvaluationException( e.getTarget() );
121 }
122 catch ( ThreadDeath e )
123 {
124 throw e;
125 }
126 catch ( Throwable e )
127 {
128 throw new ScriptEvaluationException( e );
129 }
130 }
131 finally
132 {
133 System.setErr( origErr );
134 System.setOut( origOut );
135 }
136 }
137
138 }