Search in sources :

Example 76 with PyObject

use of org.python.core.PyObject in project Pogamut3 by kefik.

the class PyDictionaryWrapper method getJavaObject.

@Override
public Object getJavaObject(Object pyObject) {
    if (!(pyObject instanceof PyDictionary))
        throw new IllegalArgumentException("pyObject is not instance of PyDictionary");
    final PyDictionary pyDict = (PyDictionary) pyObject;
    Map map = new HashMap();
    PyList keys = pyDict.keys();
    int count = keys.__len__();
    PyObject pyKey, pyValue;
    Object javaKey, javaValue;
    for (int i = 0; i < count; ++i) {
        pyKey = keys.__getitem__(i);
        javaKey = PyObjectWrappersManager.getWrapper(pyKey.getClass()).getJavaObject(pyKey);
        pyValue = pyDict.__getitem__(pyKey);
        javaValue = PyObjectWrappersManager.getWrapper(pyValue.getClass()).getJavaObject(pyValue);
        map.put(javaKey, javaValue);
    }
    return map;
}
Also used : HashMap(java.util.HashMap) PyList(org.python.core.PyList) PyObject(org.python.core.PyObject) PyDictionary(org.python.core.PyDictionary) Map(java.util.Map) HashMap(java.util.HashMap) PyObject(org.python.core.PyObject)

Example 77 with PyObject

use of org.python.core.PyObject in project Pogamut3 by kefik.

the class PyListWrapper method getChildren.

@Override
public ArrayList<PyObjectAdapter> getChildren(Object object) {
    if (!(object instanceof PyList))
        throw new IllegalArgumentException("object is not instance of PyList");
    final PyList pyList = (PyList) object;
    int count = (pyList.__len__());
    ArrayList<PyObjectAdapter> list = new ArrayList<PyObjectAdapter>(count);
    PyObject obj;
    for (int i = 0; i < count; ++i) {
        final int place = i;
        obj = pyList.__finditem__(place);
        list.add(new PyObjectAdapter(String.valueOf(place), new PyObjectPlace() {

            private int myPlace = place;

            @Override
            public void set(PyObject newValue) {
                pyList.__setitem__(myPlace, newValue);
            }

            @Override
            public PyObject get() {
                try {
                    return pyList.__finditem__(myPlace);
                } catch (Exception e) {
                    return null;
                }
            }
        }));
    }
    return list;
}
Also used : PyList(org.python.core.PyList) ArrayList(java.util.ArrayList) PyObject(org.python.core.PyObject)

Example 78 with PyObject

use of org.python.core.PyObject in project Pogamut3 by kefik.

the class PyListWrapper method getJavaObject.

@Override
public Object getJavaObject(Object pyObject) {
    if (!(pyObject instanceof PyList))
        throw new IllegalArgumentException("pyObject is not instance of PyList");
    PyList pyList = (PyList) pyObject;
    int count = (pyList.__len__());
    ArrayList list = new ArrayList(count);
    PyObject obj = null;
    PyObjectWrapper wrapper = null;
    for (int i = 0; i < count; ++i) {
        obj = pyList.__getitem__(i);
        wrapper = PyObjectWrappersManager.getWrapper(obj.getClass());
        list.add(wrapper.getJavaObject(obj));
    }
    return list;
}
Also used : PyList(org.python.core.PyList) ArrayList(java.util.ArrayList) PyObject(org.python.core.PyObject)

Example 79 with PyObject

use of org.python.core.PyObject in project sponge by softelnet.

the class JythonKnowledgeBaseInterpreter method scanToAutoEnable.

@Override
public void scanToAutoEnable() {
    PyScriptEngineScope scope = eval("globals()");
    List<PyType> processorPyTypes = getProcessorClasses().values().stream().map(cls -> (PyType) Py.java2py(cls)).collect(Collectors.toList());
    List<Object> autoEnabled = new ArrayList<>();
    SpongeUtils.stream(((ScopeIterator) scope.__iter__()).iterator()).forEachOrdered(element -> {
        String name = element.toString();
        PyObject pyObject = scope.__finditem__(name);
        // Java-based processor classes (extending PyJavaType) are not auto-enabled.
        if (pyObject != null && pyObject instanceof PyType && !(pyObject instanceof PyJavaType)) {
            PyType pyType = (PyType) pyObject;
            boolean extendsProcessorType = processorPyTypes.stream().filter(processorClass -> !pyType.equals(processorClass) && pyType.isSubType(processorClass)).findFirst().isPresent();
            if (extendsProcessorType && !isProcessorAbstract(name)) {
                autoEnabled.add(name);
                ((JythonKnowledgeBaseEngineOperations) getEngineOperations()).enable(pyType);
            }
        }
    });
    if (logger.isDebugEnabled() && !autoEnabled.isEmpty()) {
        logger.debug("Auto-enabling: {}", autoEnabled);
    }
}
Also used : Arrays(java.util.Arrays) LoggerFactory(org.slf4j.LoggerFactory) KnowledgeBase(org.openksavi.sponge.kb.KnowledgeBase) ActionBuilder(org.openksavi.sponge.action.ActionBuilder) StringUtils(org.apache.commons.lang3.StringUtils) BaseSpongeEngine(org.openksavi.sponge.core.engine.BaseSpongeEngine) SpongeEngine(org.openksavi.sponge.engine.SpongeEngine) ArrayList(java.util.ArrayList) EngineScriptKnowledgeBaseInterpreter(org.openksavi.sponge.core.kb.EngineScriptKnowledgeBaseInterpreter) JythonOutputStreamValue(org.openksavi.sponge.jython.JythonOutputStreamValue) ScopeIterator(org.python.jsr223.PyScriptEngineScope.ScopeIterator) PySystemState(org.python.core.PySystemState) PyScriptEngineScope(org.python.jsr223.PyScriptEngineScope) PythonConstants(org.openksavi.sponge.jython.PythonConstants) OutputStreamValue(org.openksavi.sponge.type.value.OutputStreamValue) Compilable(javax.script.Compilable) PyPredicate(org.openksavi.sponge.jython.util.PyPredicate) Logger(org.slf4j.Logger) JythonActionBuilder(org.openksavi.sponge.jython.JythonActionBuilder) JythonRule(org.openksavi.sponge.jython.JythonRule) Plugin(org.openksavi.sponge.plugin.Plugin) PyBiConsumer(org.openksavi.sponge.jython.util.PyBiConsumer) ScriptEngineManager(javax.script.ScriptEngineManager) PyObject(org.python.core.PyObject) Reader(java.io.Reader) PySupplier(org.openksavi.sponge.jython.util.PySupplier) Collectors(java.util.stream.Collectors) Py(org.python.core.Py) KnowledgeBaseConstants(org.openksavi.sponge.kb.KnowledgeBaseConstants) List(java.util.List) Validate(org.apache.commons.lang3.Validate) Invocable(javax.script.Invocable) JythonUtils(org.openksavi.sponge.jython.util.JythonUtils) BasePlugin(org.openksavi.sponge.core.plugin.BasePlugin) ScriptKnowledgeBaseInterpreter(org.openksavi.sponge.kb.ScriptKnowledgeBaseInterpreter) PyType(org.python.core.PyType) PyConsumer(org.openksavi.sponge.jython.util.PyConsumer) PyJavaType(org.python.core.PyJavaType) SpongeException(org.openksavi.sponge.SpongeException) ScriptEngine(javax.script.ScriptEngine) Rule(org.openksavi.sponge.rule.Rule) SpongeUtils(org.openksavi.sponge.core.util.SpongeUtils) Collections(java.util.Collections) ArrayList(java.util.ArrayList) ScopeIterator(org.python.jsr223.PyScriptEngineScope.ScopeIterator) PyScriptEngineScope(org.python.jsr223.PyScriptEngineScope) PyType(org.python.core.PyType) PyObject(org.python.core.PyObject) PyObject(org.python.core.PyObject) PyJavaType(org.python.core.PyJavaType)

Example 80 with PyObject

use of org.python.core.PyObject in project jans by JanssenProject.

the class CustomScriptManager method createExternalTypeFromStringWithPythonException.

public BaseExternalType createExternalTypeFromStringWithPythonException(CustomScript customScript, Map<String, SimpleCustomProperty> configurationAttributes) throws Exception {
    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(String.format("%s. Script inum: %s", e.getMessage(), customScript.getInum()), e);
    } finally {
        IOUtils.closeQuietly(bis);
    }
    if (externalType == null) {
        return null;
    }
    boolean initialized = false;
    try {
        if (externalType.getApiVersion() > 10) {
            initialized = externalType.init(customScript, configurationAttributes);
        } else {
            initialized = externalType.init(configurationAttributes);
            log.warn(" Update the script's init method to init(self, customScript, configurationAttributes)", customScript.getName());
        }
    } 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(io.jans.model.custom.script.CustomScriptType) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) BaseExternalType(io.jans.model.custom.script.type.BaseExternalType) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PyObject(org.python.core.PyObject) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

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