public boolean before(Authentication authentication, MethodInvocation mi, PreInvocationAttribute preAttr) { PythonInterpreterPreInvocationAttribute pythonAttr = (PythonInterpreterPreInvocationAttribute) preAttr; String script = pythonAttr.getScript(); PythonInterpreter python = new PythonInterpreter(); python.set("authentication", authentication); python.set("args", createArgumentMap(mi)); python.set("method", mi.getMethod().getName()); Resource scriptResource = new PathMatchingResourcePatternResolver() .getResource(script); try { python.execfile(scriptResource.getInputStream()); } catch (IOException e) { throw new IllegalArgumentException("Couldn't run python script, " + script, e); } PyObject allowed = python.get("allow"); if (allowed == null) { throw new IllegalStateException("Python script did not set the permit flag"); } return (Boolean) Py.tojava(allowed, Boolean.class); }
public String toString() { PyType self_type=getType(); PyObject impl=self_type.lookup("__repr__"); if (impl!=null) { PyObject res=impl.__get__(this,self_type).__call__(); if (!(res instanceof PyString)) throw Py.TypeError("__repr__ returned non-string (type "+res.getType().fastGetName()+")"); return((PyString)res).toString(); } return super.toString(); }
static PyObject loadFromLoader(PyObject importer, String name) { PyUnicode.checkEncoding(name); PyObject load_module = importer.__getattr__("load_module"); ReentrantLock importLock = Py.getSystemState().getImportLock(); importLock.lock(); try { return load_module.__call__(new PyObject[]{new PyString(name)}); } finally { importLock.unlock(); } }
public ImmutableMap<String, Function> call() throws Exception { // This creates a dependency between function and the client. // However, we need to know the load paths before we can do anything, so this is necessary. PythonUtils.initializePython(); Py.getSystemState().path.append(new PyString(file.getParentFile().getCanonicalPath())); PythonInterpreter interpreter = new PythonInterpreter(); try { interpreter.execfile(file.getCanonicalPath()); } catch (IOException e) { throw new LoadException(file, e); } catch (PyException e) { throw new LoadException(file, e); } PyStringMap map = (PyStringMap) interpreter.getLocals(); ImmutableMap.Builder<String, Function> builder = ImmutableMap.builder(); for (Object key : map.keys()) { Object o = map.get(Py.java2py(key)); if (o instanceof PyFunction) { String name = (String) key; Function f = new PythonFunction(name, (PyFunction) o); builder.put(name, f); } } return builder.build(); } });
@Override public PyObject __call__(PyObject name) { try { return objectGetattribute.__call__(self, name); } catch (PyException pye) { if (!pye.match(Py.AttributeError)) { throw pye; } } CustomizableMapHolder inst = Py.tojava(self, CustomizableMapHolder.class); return Py.java2py(inst.held.get(Py.tojava(name, String.class))); } };
public Object invoke(Object... args) throws Exception { PyObject[] pyArgs = new PyObject[args.length]; for (int i = 0; i < args.length; i++) pyArgs[i] = Py.java2py(args[i]); PyObject pyResult = fn.__call__(pyArgs); if (pyResult == null) return null; // todo: number conversions should be handled higher up in the code, and not at the Jython level. if (pyResult instanceof PyLong || pyResult instanceof PyInteger) return pyResult.__tojava__(Long.class); Object result = pyResult.__tojava__(Object.class); if (result == Py.NoConversion) throw new RuntimeException("Cannot convert Python object " + pyResult + " to java."); return result; }
/** * Convert java object to its corresponding PyObject representation. * * @param o Java object * @return PyObject */ public static PyObject adapt(Object o) { if (o instanceof PyObject) { return (PyObject) o; } return Py.java2py(o); }
private void module___init__(PyObject name, PyObject doc) { ensureDict(); __dict__.__setitem__("__name__", name); __dict__.__setitem__("__doc__", doc); if (name.equals(new PyString("__main__"))) { __dict__.__setitem__("__builtins__", Py.getSystemState().modules.__finditem__("__builtin__")); __dict__.__setitem__("__package__", Py.None); } }
public void setDict(PyObject newDict) { if (newDict instanceof PyStringMap||newDict instanceof PyDictionary) { dict=newDict; if (dict.__finditem__(PyString.fromInterned("__del__"))!=null&&!JyAttribute.hasAttr(this,JyAttribute.FINALIZE_TRIGGER_ATTR)) { FinalizeTrigger.ensureFinalizer(this); } } else { throw Py.TypeError("__dict__ must be set to a Dictionary "+newDict.getClass().getName()); } }
public synchronized static void initializePython() { if (isInitialized.get()) return; // Set the Jython package cache directory. Properties jythonProperties = new Properties(); String jythonCacheDir = Platform.getUserDataDirectory() + Platform.SEP + "_jythoncache"; jythonProperties.put("python.cachedir", jythonCacheDir); // Initialize Python. PySystemState.initialize(System.getProperties(), jythonProperties, new String[]{""}); // Add the built-in Python libraries. File nodeBoxLibraries = new File(libDir, "nodeboxlibs.zip"); Py.getSystemState().path.add(new PyString(nodeBoxLibraries.getAbsolutePath())); // This folder contains unarchived NodeBox libraries. // Only used in development. File developmentLibraries = new File("src/main/python"); Py.getSystemState().path.add(new PyString(developmentLibraries.getAbsolutePath())); // Add the user's Python directory. Py.getSystemState().path.add(new PyString(Platform.getUserPythonDirectory().getAbsolutePath())); isInitialized.set(true); }
static void raise_errmsg(String msg, PyObject s, PyObject pos, PyObject end) { /* Use the Python function json.decoder.errmsg to raise a nice looking ValueError exception */ final PyObject errmsg_fn = get_errmsg_fn(); if (errmsg_fn != null) { throw Py.ValueError(errmsg_fn.__call__(Py.newString(msg), s, pos, end).asString()); } else { throw Py.ValueError(msg); } }
@Override public PyObject __call__(PyObject memo) { Object obj = self.getJavaProxy(); try { Object copy = cloneX(obj); return Py.java2py(copy); } catch (Exception ex) { throw Py.TypeError("Could not copy Java object"); } } });
/** * Returns the banner to print before the first interaction: "Jython <version> on <platform>". * * @return the banner. */ public static String getDefaultBanner() { return String .format("Jython %s on %s", PySystemState.version, Py.getSystemState().platform); }