1 55 56 package org.apache.bsf.engines.jpython; 57 58 import java.util.Vector ; 59 60 import org.python.util.*; 61 import org.python.core.*; 62 63 import org.apache.bsf.*; 64 import org.apache.bsf.util.BSFEngineImpl; 65 import org.apache.bsf.util.BSFFunctions; 66 67 73 74 public class JPythonEngine extends BSFEngineImpl { 75 PythonInterpreter interp; 76 77 80 public Object call (Object object, String method, Object [] args) 81 throws BSFException { 82 83 PyObject[] pyargs = Py.EmptyObjects; 84 if (args != null) { 85 pyargs = new PyObject[args.length]; 86 for (int i = 0; i < pyargs.length; i++) 87 pyargs[i] = Py.java2py(args[i]); 88 } 89 90 if (object != null) { 91 PyObject o = Py.java2py(object); 92 return unwrap(o.invoke(method, pyargs)); 93 } 94 PyObject m = interp.get(method); 95 if (m == null) 96 m = interp.eval(method); 97 if (m != null) { 98 return unwrap(m.__call__(pyargs)); 99 } 100 return null; 101 } 102 105 public void declareBean (BSFDeclaredBean bean) throws BSFException { 106 interp.set (bean.name, bean.bean); 107 } 108 111 public Object eval (String source, int lineNo, int columnNo, 112 Object script) throws BSFException { 113 try { 114 Object result = interp.eval (script.toString ()); 115 if (result != null && result instanceof PyJavaInstance) 116 result = ((PyJavaInstance)result).__tojava__(Object .class); 117 return result; 118 } catch (PyException e) { 119 e.printStackTrace (); 120 throw new BSFException (BSFException.REASON_EXECUTION_ERROR, 121 "exception from JPython: " + e, e); 122 } 123 } 124 127 public void exec (String source, int lineNo, int columnNo, 128 Object script) throws BSFException { 129 try { 130 interp.exec (script.toString ()); 131 } catch (PyException e) { 132 e.printStackTrace (); 133 throw new BSFException (BSFException.REASON_EXECUTION_ERROR, 134 "exception from JPython: " + e, e); 135 } 136 } 137 140 public void initialize (BSFManager mgr, String lang, 141 Vector declaredBeans) throws BSFException { 142 super.initialize (mgr, lang, declaredBeans); 143 144 interp = new PythonInterpreter (); 146 147 interp.set ("bsf", new BSFFunctions (mgr, this)); 149 150 int size = declaredBeans.size (); 151 for (int i = 0; i < size; i++) { 152 declareBean ((BSFDeclaredBean) declaredBeans.elementAt (i)); 153 } 154 } 155 156 159 public void undeclareBean (BSFDeclaredBean bean) throws BSFException { 160 interp.set (bean.name, null); 161 } 162 public Object unwrap(PyObject result) { 163 if (result != null) { 164 Object ret = result.__tojava__(Object .class); 165 if (ret != Py.NoConversion) 166 return ret; 167 } 168 return result; 169 } 170 } 171 | Popular Tags |