1 55 56 package org.apache.bsf.engines.jython; 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 75 76 public class JythonEngine extends BSFEngineImpl { 77 PythonInterpreter interp; 78 79 82 public Object call (Object object, String method, Object [] args) 83 throws BSFException { 84 85 PyObject[] pyargs = Py.EmptyObjects; 86 if (args != null) { 87 pyargs = new PyObject[args.length]; 88 for (int i = 0; i < pyargs.length; i++) 89 pyargs[i] = Py.java2py(args[i]); 90 } 91 92 if (object != null) { 93 PyObject o = Py.java2py(object); 94 return unwrap(o.invoke(method, pyargs)); 95 } 96 PyObject m = interp.get(method); 97 if (m == null) 98 m = interp.eval(method); 99 if (m != null) { 100 return unwrap(m.__call__(pyargs)); 101 } 102 return null; 103 } 104 107 public void declareBean (BSFDeclaredBean bean) throws BSFException { 108 interp.set (bean.name, bean.bean); 109 } 110 113 public Object eval (String source, int lineNo, int columnNo, 114 Object script) throws BSFException { 115 try { 116 Object result = interp.eval (script.toString ()); 117 if (result != null && result instanceof PyJavaInstance) 118 result = ((PyJavaInstance)result).__tojava__(Object .class); 119 return result; 120 } catch (PyException e) { 121 e.printStackTrace (); 122 throw new BSFException (BSFException.REASON_EXECUTION_ERROR, 123 "exception from Jython: " + e, e); 124 } 125 } 126 129 public void exec (String source, int lineNo, int columnNo, 130 Object script) throws BSFException { 131 try { 132 interp.exec (script.toString ()); 133 } catch (PyException e) { 134 e.printStackTrace (); 135 throw new BSFException (BSFException.REASON_EXECUTION_ERROR, 136 "exception from Jython: " + e, e); 137 } 138 } 139 142 public void initialize (BSFManager mgr, String lang, 143 Vector declaredBeans) throws BSFException { 144 super.initialize (mgr, lang, declaredBeans); 145 146 interp = new PythonInterpreter (); 148 149 interp.set ("bsf", new BSFFunctions (mgr, this)); 151 152 int size = declaredBeans.size (); 153 for (int i = 0; i < size; i++) { 154 declareBean ((BSFDeclaredBean) declaredBeans.elementAt (i)); 155 } 156 } 157 158 161 public void undeclareBean (BSFDeclaredBean bean) throws BSFException { 162 interp.set (bean.name, null); 163 } 164 public Object unwrap(PyObject result) { 165 if (result != null) { 166 Object ret = result.__tojava__(Object .class); 167 if (ret != Py.NoConversion) 168 return ret; 169 } 170 return result; 171 } 172 } 173 | Popular Tags |