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.util.List;
25 import java.util.Map;
26
27 import bsh.Capabilities;
28 import bsh.EvalError;
29 import bsh.Interpreter;
30 import bsh.TargetError;
31
32
33
34
35
36
37 class BeanShellScriptInterpreter 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 {
51 Interpreter engine = new Interpreter();
52
53 if (scriptOutput != null) {
54 System.setErr(scriptOutput);
55 System.setOut(scriptOutput);
56 engine.setErr(scriptOutput);
57 engine.setOut(scriptOutput);
58 }
59
60 if (!Capabilities.haveAccessibility()) {
61 try {
62 Capabilities.setAccessibility(true);
63 } catch (Exception e) {
64 if (scriptOutput != null) {
65 e.printStackTrace(scriptOutput);
66 }
67 }
68 }
69
70 if (classPath != null && !classPath.isEmpty()) {
71 for (String path : classPath) {
72 try {
73 engine.getClassManager()
74 .addClassPath(new File(path).toURI().toURL());
75 } catch (IOException e) {
76 throw new RuntimeException("bad class path: " + path, e);
77 }
78 }
79 }
80
81 if (globalVariables != null) {
82 for (Map.Entry<String, ?> entry : globalVariables.entrySet()) {
83 try {
84 engine.set(entry.getKey(), entry.getValue());
85 } catch (EvalError e) {
86 throw new RuntimeException(e);
87 }
88 }
89 }
90
91 try {
92 return engine.eval(script);
93 } catch (TargetError e) {
94 throw new ScriptEvaluationException(e.getTarget());
95 } catch (ThreadDeath e) {
96 throw e;
97 } catch (Throwable e) {
98 throw new ScriptEvaluationException(e);
99 }
100 } finally {
101 System.setErr(origErr);
102 System.setOut(origOut);
103 }
104 }
105 }