Category: Programming

Bean Shell Compiler

By vijay on October 13, 2005 — 1 min read

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.

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 Duvvuri *
 * @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;
 }
}

 

 More