Search in sources :

Example 46 with PyObject

use of org.python.core.PyObject in project oxCore by GluuFederation.

the class PythonService method loadPythonScript.

@SuppressWarnings("unchecked")
private <T> T loadPythonScript(String scriptPythonType, Class<T> scriptJavaType, PyObject[] constructorArgs, PythonInterpreter interpreter) throws PythonException {
    PyObject scriptPythonTypeObject = interpreter.get(scriptPythonType);
    if (scriptPythonTypeObject == null) {
        return null;
    }
    PyObject scriptPythonTypeClass;
    try {
        scriptPythonTypeClass = scriptPythonTypeObject.__call__(constructorArgs);
    } catch (Exception ex) {
        log.error("Failed to initialize python class", ex.getMessage());
        throw new PythonException(String.format("Failed to initialize python class '%s'", scriptPythonType), ex);
    }
    Object scriptJavaClass = scriptPythonTypeClass.__tojava__(scriptJavaType);
    if (!ReflectHelper.assignableFrom(scriptJavaClass.getClass(), scriptJavaType)) {
        return null;
    }
    return (T) scriptJavaClass;
}
Also used : PythonException(org.xdi.exception.PythonException) PyObject(org.python.core.PyObject) PyObject(org.python.core.PyObject) PythonException(org.xdi.exception.PythonException) IOException(java.io.IOException) PyException(org.python.core.PyException)

Example 47 with PyObject

use of org.python.core.PyObject in project yamcs-studio by yamcs.

the class JythonScriptStore method dispose.

@Override
protected void dispose() {
    if (interp != null) {
        PyObject o = interp.getLocals();
        if (o != null && o instanceof PyStringMap) {
            ((PyStringMap) o).clear();
        }
        // o = state.getBuiltins();
        // if (o != null && o instanceof PyStringMap) {
        // ((PyStringMap)o).clear();
        // }
        o = state.getDict();
        if (o != null && o instanceof PyStringMap) {
            ((PyStringMap) o).clear();
        }
        state.close();
        state.cleanup();
        interp.close();
        interp.cleanup();
        interp = null;
        state = null;
    }
    code = null;
    super.dispose();
}
Also used : PyStringMap(org.python.core.PyStringMap) PyObject(org.python.core.PyObject)

Example 48 with PyObject

use of org.python.core.PyObject in project oxCore by GluuFederation.

the class CustomScriptManager method createExternalTypeFromStringWithPythonException.

public BaseExternalType createExternalTypeFromStringWithPythonException(CustomScript customScript, Map<String, SimpleCustomProperty> configurationAttributes) throws PythonException {
    String script = customScript.getScript();
    String scriptName = StringHelper.toLowerCase(customScript.getName()) + ".py";
    if (script == null) {
        return null;
    }
    CustomScriptType customScriptType = customScript.getScriptType();
    BaseExternalType externalType = null;
    InputStream bis = null;
    try {
        bis = new ByteArrayInputStream(script.getBytes("UTF-8"));
        externalType = pythonService.loadPythonScript(bis, scriptName, customScriptType.getPythonClass(), customScriptType.getCustomScriptType(), new PyObject[] { new PyLong(System.currentTimeMillis()) });
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(bis);
    }
    if (externalType == null) {
        return null;
    }
    boolean initialized = false;
    try {
        initialized = externalType.init(configurationAttributes);
    } catch (Exception ex) {
        log.error("Failed to initialize custom script: '{}'", ex, customScript.getName());
    }
    if (initialized) {
        return externalType;
    }
    return null;
}
Also used : PyLong(org.python.core.PyLong) ByteArrayInputStream(java.io.ByteArrayInputStream) CustomScriptType(org.xdi.model.custom.script.CustomScriptType) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) BaseExternalType(org.xdi.model.custom.script.type.BaseExternalType) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PyObject(org.python.core.PyObject) PythonException(org.xdi.exception.PythonException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 49 with PyObject

use of org.python.core.PyObject in project phoebus by ControlSystemStudio.

the class JythonSupport method loadClass.

/**
 * Load a Jython class
 *
 *  @param type Type of the Java object to return
 *  @param class_name Name of the Jython class,
 *                    must be in package (file) using lower case of class name
 *  @param args Arguments to pass to constructor
 *  @return Java object for instance of Jython class
 *  @throws Exception on error
 */
@SuppressWarnings("unchecked")
public <T> T loadClass(final Class<T> type, final String class_name, final String... args) throws Exception {
    // Get package name
    final String pack_name = class_name.toLowerCase();
    logger.log(Level.FINE, "Loading Jython class {0} from {1}", new Object[] { class_name, pack_name });
    try {
        // Import class into Jython
        // Debug: Print the path that's actually used
        // final String statement = "import sys\nprint sys.path\nfrom " + pack_name +  " import " + class_name;
        final String statement = "from " + pack_name + " import " + class_name;
        interpreter.exec(statement);
    } catch (PyException ex) {
        logger.log(Level.WARNING, "Error loading Jython class {0} from {1}", new Object[] { class_name, pack_name });
        logger.log(Level.WARNING, "Jython sys.path:\n * {0}", interpreter.getSystemState().path.stream().collect(Collectors.joining("\n * ")));
        throw new Exception("Error loading Jython class " + class_name + ":" + getExceptionMessage(ex), ex);
    }
    // Create Java reference
    final PyObject py_class = interpreter.get(class_name);
    final PyObject py_object;
    if (args.length <= 0)
        py_object = py_class.__call__();
    else {
        final PyObject[] py_args = new PyObject[args.length];
        for (int i = 0; i < py_args.length; ++i) py_args[i] = new PyString(args[i]);
        py_object = py_class.__call__(py_args);
    }
    final T java_ref = (T) py_object.__tojava__(type);
    return java_ref;
}
Also used : PyString(org.python.core.PyString) PyException(org.python.core.PyException) PyObject(org.python.core.PyObject) PyString(org.python.core.PyString) PyObject(org.python.core.PyObject) PyException(org.python.core.PyException)

Example 50 with PyObject

use of org.python.core.PyObject in project Pydev by fabioz.

the class JythonModules method getPepJythonModule.

/**
 * @param module: The name of the module (i.e.: pycodestyle, autopep8)
 * @return null if it was not able to get the pycodestyle module.
 */
private static PyObject getPepJythonModule(IPythonInterpreter interpreter, String module) {
    synchronized (loadJythonLock) {
        String s = "" + "import sys\n" + "add_to_pythonpath = '%s'\n" + "if add_to_pythonpath not in sys.path:\n" + "    sys.path.append(add_to_pythonpath)\n" + "import " + module + "\n";
        // put the parent dir of pycodestyle.py in the pythonpath.
        File pepModuleLoc = CorePlugin.getPepModuleLocation(module + ".py");
        if (pepModuleLoc == null) {
            return null;
        }
        s = StringUtils.format(s, StringUtils.replaceAllSlashes(pepModuleLoc.getParentFile().getAbsolutePath()));
        interpreter.exec(s);
        return (PyObject) interpreter.get(module);
    }
}
Also used : File(java.io.File) PyObject(org.python.core.PyObject)

Aggregations

PyObject (org.python.core.PyObject)80 PyString (org.python.core.PyString)24 PyList (org.python.core.PyList)16 ArrayList (java.util.ArrayList)15 HashMap (java.util.HashMap)12 PyException (org.python.core.PyException)12 IOException (java.io.IOException)9 Serializable (java.io.Serializable)9 PyInteger (org.python.core.PyInteger)8 Test (org.junit.Test)7 PyStringMap (org.python.core.PyStringMap)7 PythonInterpreter (org.python.util.PythonInterpreter)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 Map (java.util.Map)6 PyDictionary (org.python.core.PyDictionary)6 PyFloat (org.python.core.PyFloat)6 List (java.util.List)5 PyLong (org.python.core.PyLong)5 PyNone (org.python.core.PyNone)5 PyTuple (org.python.core.PyTuple)5