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 11 import org.python.core.*; 12 import org.python.util.PythonInterpreter; 13 14 15 19 public class PythonEvaluator implements Evaluator { 20 21 private static final String LOG_CHANNEL="Scripting"; 22 23 private CallbackUtilities cus; 24 public void configure (CallbackUtilities cus) throws RootException { 25 this.cus=cus; 26 } 27 28 29 37 public boolean evaluateCondition (SharkTransaction t,String condition,Map context) throws RootException { 38 if(condition==null || condition.trim().length()==0){ 39 return true; 40 } 41 42 java.lang.Object eval=evaluateExpression(t,condition,context,java.lang.Boolean .class); 43 try { 44 return ((Boolean )eval).booleanValue(); 46 } catch (Exception ex) { 47 cus.error(LOG_CHANNEL,"PythonEvaluator -> The result of condition "+condition+" cannot be converted to boolean"); 48 cus.error("PythonEvaluator -> The result of condition "+condition+" cannot be converted to boolean"); 49 throw new RootException("Result cannot be converted to boolean",ex); 50 } 51 52 } 53 54 63 public java.lang.Object evaluateExpression (SharkTransaction t,String expr,Map context,Class resultClass) throws RootException { 64 PythonInterpreter interpreter = new PythonInterpreter(); 65 66 PyObject eval; 67 try { 68 prepareContext(interpreter,context); 69 eval = interpreter.eval(expr); 71 java.lang.Object result=null; 73 if (resultClass!=null) { 74 result=eval.__tojava__(resultClass); 75 } else { 76 result=eval.__tojava__(java.lang.Object .class); 77 } 78 cus.debug(LOG_CHANNEL,"PythonScriptEvaluator -> Python scrip expression "+expr+" is evaluated to "+eval); 81 82 return result; 83 84 } catch (Exception ee) { 85 cus.error(LOG_CHANNEL,"PythonEvaluator -> The result of expression "+expr+" can't be evaluated - error message="+ee.getMessage()); 86 cus.error("PythonEvaluator -> The result of expression "+expr+" can't be evaluated - error message="+ee.getMessage()); 87 throw new RootException("Result cannot be evaluated",ee); 88 } 89 } 90 91 private void prepareContext (PythonInterpreter interpreter,Map context) throws Exception { 92 Iterator iter = context.entrySet().iterator(); 93 while(iter.hasNext()){ 94 Map.Entry me=(Map.Entry)iter.next(); 95 String key = me.getKey().toString(); 96 java.lang.Object value = me.getValue(); 97 interpreter.set(key,value); 99 } 100 } 101 102 } 103 | Popular Tags |