1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package ch.elca.el4j.services.debug;
18
19 import java.io.ByteArrayOutputStream;
20 import java.io.PrintStream;
21 import java.io.StringReader;
22
23 import org.springframework.context.ApplicationContext;
24
25 import bsh.EvalError;
26 import bsh.Interpreter;
27 import bsh.InterpreterError;
28 import bsh.NameSpace;
29 import bsh.Primitive;
30 import bsh.TargetError;
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50 public class ShellExecutorImpl implements ShellExecutor {
51
52 private ByteArrayOutputStream out;
53
54 private ByteArrayOutputStream err;
55
56 private PrintStream m_outPStream;
57
58 private PrintStream m_errPStream;
59
60 private Interpreter interpreter;
61
62 protected ApplicationContext m_ac;
63
64 public ShellExecutorImpl() {
65 startup();
66 }
67
68 public ShellExecutorImpl(ApplicationContext ac) {
69 this();
70 m_ac = ac;
71 }
72
73
74
75 protected synchronized void startup () {
76
77 out = new ByteArrayOutputStream();
78 err = new ByteArrayOutputStream();
79
80 interpreter = new Interpreter
81 (new StringReader (""),
82 m_outPStream = new PrintStream (out),
83 m_errPStream = new PrintStream (err),
84 false);
85 }
86
87
88
89 public synchronized ResultHolder eval (String stmt) {
90 Object retVal = null;
91
92 try {
93 retVal = interpreter.eval (stmt);
94 if (retVal != Primitive.VOID) {
95 interpreter.set ("$_", retVal);
96 }
97 if (m_ac != null){
98 interpreter.set ("ac", m_ac);
99 }
100
101 Object show = interpreter.get ("bsh.show");
102 if ( (retVal != null) && show instanceof Boolean &&
103 ((Boolean) show).booleanValue() == true){
104 m_outPStream.println ("<"+retVal+">");
105 }
106 } catch (InterpreterError e) {
107 m_errPStream.println ("Internal Error: " + e.getMessage());
108 e.printStackTrace (m_errPStream);
109 } catch (TargetError te) {
110 m_errPStream.println ("// Uncaught Exception: " + te);
111 if (te.inNativeCode()){
112 te.printStackTrace (m_errPStream);
113 }
114 } catch (EvalError ee) {
115 m_errPStream.println (ee.toString());
116 } catch (Exception e) {
117 m_errPStream.println ("Unknown error: " + e);
118 e.printStackTrace (m_errPStream);
119 }
120
121 String outStr = out.toString();
122 out.reset();
123
124 String errStr = err.toString();
125 err.reset();
126
127 return new ResultHolder (retVal,outStr,errStr);
128 }
129
130
131 public synchronized NameSpace getNameSpace () {
132 return interpreter.getNameSpace();
133 }
134
135
136 public synchronized void setNameSpace (NameSpace ns){
137 interpreter.setNameSpace (ns);
138 }
139
140
141 public synchronized Interpreter getInterpreter() {
142 return interpreter;
143 }
144
145
146 public synchronized void setInterpreter(Interpreter interpreter) {
147 this.interpreter = interpreter;
148 }
149
150 }
151