1 37 package org.webharvest.runtime.scripting; 38 39 import bsh.EvalError; 40 import bsh.Interpreter; 41 import org.webharvest.exception.ScriptException; 42 43 import java.util.Iterator ; 44 import java.util.Map ; 45 46 49 public class ScriptEngine extends Interpreter { 50 51 public static final String CONTEXT_VARIABLE_NAME = "___web_harvest_context___"; 52 53 private Map context; 54 55 59 public ScriptEngine(Map context) { 60 this.getNameSpace().importCommands("org.webharvest.runtime.scripting"); 61 this.context = context; 62 try { 63 this.set(CONTEXT_VARIABLE_NAME, this.context); 64 } catch (EvalError e) { 65 throw new ScriptException("Cannot set Web-Harvest context in scripter: " + e.getMessage(), e); 66 } 67 } 68 69 74 public void setVariable(String name, Object value) { 75 try { 76 super.set(name, value); 77 } catch (EvalError e) { 78 throw new ScriptException("Cannot set variable in scripter: " + e.getMessage(), e); 79 } 80 } 81 82 86 public Object eval(String expression) { 87 if (this.context != null) { 89 Iterator it = this.context.entrySet().iterator(); 90 while (it.hasNext()) { 91 Map.Entry entry = (Map.Entry ) it.next(); 92 String name = (String ) entry.getKey(); 93 setVariable( name, entry.getValue() ); 94 } 95 } 96 97 try { 98 return super.eval(expression); 99 } catch (EvalError e) { 100 throw new ScriptException("Error during script execution: " + e.getMessage(), e); 101 } 102 } 103 104 109 public void setInContext(String name, Object value) { 110 if (this.context != null) { 111 this.context.put(name, value); 112 } 113 } 114 115 } | Popular Tags |