1 package org.enhydra.shark.scripting; 2 3 import org.enhydra.shark.api.RootException; 4 import org.enhydra.shark.api.SharkTransaction; 5 import org.enhydra.shark.api.internal.scripting.Evaluator; 6 import org.enhydra.shark.api.internal.working.CallbackUtilities; 7 8 import java.util.*; 9 10 import org.mozilla.javascript.*; 11 12 13 17 public class JavaScriptEvaluator implements Evaluator { 18 19 private static final String LOG_CHANNEL="Scripting"; 20 21 private CallbackUtilities cus; 22 public void configure (CallbackUtilities cus) throws RootException { 23 this.cus=cus; 24 } 25 26 27 35 public boolean evaluateCondition (SharkTransaction t,String condition,Map context) throws RootException { 36 if(condition==null || condition.trim().length()==0){ 37 return true; 38 } 39 40 java.lang.Object eval=evaluateExpression(t,condition,context,java.lang.Boolean .class); 41 try { 42 return ((Boolean )eval).booleanValue(); 43 } catch (Exception ex) { 44 cus.error(LOG_CHANNEL,"JavaScriptEvaluator -> The result of condition "+condition+" cannot be converted to boolean"); 45 cus.error("JavaScriptEvaluator -> The result of condition "+condition+" cannot be converted to boolean"); 46 throw new RootException("Result cannot be converted to boolean",ex); 47 } 48 49 } 50 51 60 public java.lang.Object evaluateExpression (SharkTransaction t,String expr,Map context,Class resultClass) throws RootException { 61 org.mozilla.javascript.Context cx=org.mozilla.javascript.Context.enter(); 62 Scriptable scope=cx.initStandardObjects(null); 63 64 java.lang.Object eval; 65 try { 66 prepareContext(scope,context); 67 if (resultClass!=null) { 69 eval = org.mozilla.javascript.Context.toType(cx.evaluateString(scope,expr,"",1,null),resultClass); 70 } else { 71 eval = cx.evaluateString(scope,expr,"",1,null); 72 } 73 cus.debug(LOG_CHANNEL,"JavaScriptEvaluator -> Javascript expression "+expr+" is evaluated to "+eval); 74 return eval; 76 77 } catch (Exception jse) { 78 cus.error(LOG_CHANNEL,"JavaScriptEvaluator -> The result of expression "+expr+" can't be evaluated - error message="+jse.getMessage()); 79 cus.error("JavaScriptEvaluator -> The result of expression "+expr+" can't be evaluated - error message="+jse.getMessage()); 80 throw new RootException("Result cannot be evaluated",jse); 81 } finally { 82 org.mozilla.javascript.Context.exit(); 83 } 84 } 85 86 private void prepareContext (Scriptable scope,Map context) throws Exception { 87 Iterator iter = context.entrySet().iterator(); 88 while(iter.hasNext()){ 89 Map.Entry me=(Map.Entry)iter.next(); 90 String key = me.getKey().toString(); 91 java.lang.Object value = me.getValue(); 92 scope.put(key,scope,value); 94 } 95 } 96 97 } 98 | Popular Tags |