Bean Shell makes your Java programs scriptable. Recently I started working on it. BeanShell provides its own JavaScript-like syntax to access your Java Objects. You can even change the syntax to anything you like using JavaCC. I started playing with it. BeanShell uses a Parser and Abstract Syntax Tree (AST) to tokenize the code. Here’s a small class for compiling the BSH script, before sending it to the interpreter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
import java.io.FileReader; import bsh.ParseException; import bsh.Parser; /** * BshCompiler Class is used to compile the scripts and verify for the syntax * errors, before interpreting. The class constructor takes the Script file * name/path as the argument, and checks for the syntax. Once the process is * complete, use isSuccess to get the result, and also the getResponse * and getErrors to get the respnses. Note that this class is not synchronized, it * has to be handled externally. * * * @author Vijay Kiran * @version 0.1 **/ public class BshCompiler { private StringBuffer response; private StringBuffer errors; private boolean success; private FileReader fileReader = null; private Parser parser; private String script; /** * * scriptFile – path of the scriptFile * * * @param scriptFile */ public BshCompiler(String scriptFile) { this.script = scriptFile; compileScript(); } private boolean compileScript() { response = new StringBuffer(); errors = new StringBuffer(); success = false; try { fileReader = new FileReader(script); parser = new Parser(fileReader); parser.setRetainComments(true); while (!parser.Line()/* eof */) { response.append(parser.popNode() + "n"); } success = true; } catch (Error error) { errors.append(error + "n"); } catch (ParseException parseException) { errors.append("PARSE EXCEPTION: " + parseException.toString() + "n"); errors.append("ERROR MESSAGE: " + parseException.getMessage() + "n"); } catch (Exception e) { System.out.println("Other Exception"); errors.append(e + "n"); } finally { try { if (fileReader != null) { fileReader.close(); } } catch (Exception e) { e.printStackTrace(); } catch (Error error) { } } return success; } public StringBuffer getResponse() { return response; } public StringBuffer getErrors() { return errors; } public boolean isSuccess() { return success; } } |
Posted in:
Programming
Leave a Reply