Search in sources :

Example 56 with PyObject

use of org.python.core.PyObject in project gda-core by openGDA.

the class ScriptBasedItem method evaluateFunction.

/**
 * The function will be given a single double as argument, and expects a double as return
 *
 * Any exception is rethrown as a WorkflowException
 */
private Object evaluateFunction(String functionName, PyObject function, PyObject argument) throws WorkflowException {
    logger.debug("Evaluating {}({})...", functionName, argument.__str__());
    try {
        Object result = function.__call__(argument).__tojava__(Object.class);
        logger.debug("... evaluation result = {}", result);
        return Objects.requireNonNull(result, "Function returned null!");
    } catch (PyException e) {
        throw new WorkflowException("Error executing function '" + functionName + "'", e);
    }
}
Also used : PyException(org.python.core.PyException) WorkflowException(uk.ac.diamond.daq.beamline.configuration.api.WorkflowException) PyObject(org.python.core.PyObject)

Example 57 with PyObject

use of org.python.core.PyObject in project gda-core by openGDA.

the class HighlightersTest method testDifferentThemesHaveDifferentHighlighters.

@Test
public void testDifferentThemesHaveDifferentHighlighters() throws Exception {
    PyObject h1 = mock(PyObject.class);
    PyObject h2 = mock(PyObject.class);
    when(h1.__call__(new PyUnicode("abcd"))).thenReturn(new PyUnicode("theme1"));
    when(h2.__call__(new PyUnicode("abcd"))).thenReturn(new PyUnicode("theme2"));
    evalResponse = returnsElementsOf(asList(h1, h2));
    Highlighter high1 = Highlighters.getHighlighter("theme_one");
    Highlighter high2 = Highlighters.getHighlighter("theme_two");
    assertThat(high1.highlight(reader, "abcd"), is(AttributedString.fromAnsi("theme1")));
    assertThat(high2.highlight(reader, "abcd"), is(AttributedString.fromAnsi("theme2")));
}
Also used : PyUnicode(org.python.core.PyUnicode) PyObject(org.python.core.PyObject) Highlighter(org.jline.reader.Highlighter) Test(org.junit.Test)

Example 58 with PyObject

use of org.python.core.PyObject in project gda-core by openGDA.

the class JythonServer method getAllFromJythonNamespace.

/**
 * Returns the contents of the top-level namespace.
 * <p>
 * This returns object references so cannot be distributed.
 *
 * @return Map<String, Object> of items in jython namespace
 */
private Map<String, Object> getAllFromJythonNamespace() {
    PyStringMap locals = (PyStringMap) this.interp.getAllFromJythonNamepsace();
    PyList dict = locals.keys();
    dict.sort();
    final Map<String, Object> output = new LinkedHashMap<>();
    for (int i = 0; i < dict.__len__(); i++) {
        PyObject key = dict.__getitem__(i);
        output.put(key.asString(), locals.get(key).__tojava__(Object.class));
    }
    return output;
}
Also used : PyStringMap(org.python.core.PyStringMap) PyList(org.python.core.PyList) PyObject(org.python.core.PyObject) PyObject(org.python.core.PyObject) LinkedHashMap(java.util.LinkedHashMap)

Example 59 with PyObject

use of org.python.core.PyObject in project gda-core by openGDA.

the class ScannableGetPositionWrapper method calStringFormattedValues.

String[] calStringFormattedValues() {
    Object[] elements = getElements();
    String[] stringFormattedValues = new String[elements.length];
    int index = 0;
    for (Object object : elements) {
        String val = "unknown";
        if (object != null) {
            val = object.toString();
            try {
                String format = formats != null ? (formats.length > index ? formats[index] : formats[0]) : null;
                if (format == null) {
                    if (object instanceof PyObject) {
                        val = (String) (((PyObject) object).__str__()).__tojava__(String.class);
                    }
                } else {
                    Object transformedObject = object;
                    if (object instanceof PyFloat) {
                        transformedObject = ((PyFloat) object).__tojava__(Double.class);
                    } else if (object instanceof PyInteger) {
                        transformedObject = ((PyInteger) object).__tojava__(Integer.class);
                    } else if (object instanceof PyObject) {
                        transformedObject = ((PyObject) object).__str__().__tojava__(String.class);
                        try {
                            transformedObject = Double.parseDouble((String) transformedObject);
                        } catch (Exception e) {
                        // ignore as transformedObject will be unchanged
                        }
                    }
                    val = String.format(format, transformedObject);
                }
            } catch (Exception e) {
            // do nothing - the default value is object.toString
            }
        }
        stringFormattedValues[index] = val;
        index++;
    }
    return stringFormattedValues;
}
Also used : PyFloat(org.python.core.PyFloat) PyObject(org.python.core.PyObject) PyString(org.python.core.PyString) PyInteger(org.python.core.PyInteger) PyObject(org.python.core.PyObject)

Example 60 with PyObject

use of org.python.core.PyObject in project gda-core by openGDA.

the class ScannableUtils method convertToJava.

/**
 * Converts a Jython PyObject into its Java equivalent if that is possible. This only works on the sorts of objects
 * dealt with in the Jython environment i.e. Strings, integers, floats (doubles) and arrays of these.
 * <P>
 * If this fails or cannot work for any reason then null is returned.
 *
 * @param object
 * @return Java equivalent object
 */
public static Object convertToJava(PyObject object) {
    Object output = null;
    if (object instanceof PyFloat) {
        output = object.__tojava__(Double.class);
    } else if (object instanceof PyInteger) {
        output = object.__tojava__(Integer.class);
    } else if (object instanceof PyString) {
        output = object.__tojava__(String.class);
    } else if (object instanceof PySequence || object instanceof PyList) {
        // create a Java array of PyObjects
        // ArrayList<PyObject> theList = (ArrayList<PyObject>)
        // object.__tojava__(ArrayList.class);
        // loop through and convert each item into its Java equivilent
        output = new Object[0];
        int length;
        if (object instanceof PySequence) {
            length = ((PySequence) object).__len__();
        } else {
            length = ((PyList) object).__len__();
        }
        for (int i = 0; i < length; i++) {
            PyObject item = null;
            if (object instanceof PySequence) {
                item = ((PySequence) object).__finditem__(i);
            } else {
                item = ((PyList) object).__finditem__(i);
            }
            if (item instanceof PyFloat) {
                Double thisItem = (Double) item.__tojava__(Double.class);
                output = ArrayUtils.add((Object[]) output, thisItem);
            } else if (item instanceof PyInteger) {
                Integer thisItem = (Integer) item.__tojava__(Integer.class);
                output = ArrayUtils.add((Object[]) output, thisItem);
            } else if (item instanceof PyString) {
                String thisItem = (String) item.__tojava__(String.class);
                output = ArrayUtils.add((Object[]) output, thisItem);
            }
        }
    }
    if (output == org.python.core.Py.NoConversion) {
        output = null;
    }
    return output;
}
Also used : PyString(org.python.core.PyString) PyInteger(org.python.core.PyInteger) PyList(org.python.core.PyList) PyFloat(org.python.core.PyFloat) PyObject(org.python.core.PyObject) PyInteger(org.python.core.PyInteger) PyString(org.python.core.PyString) PySequence(org.python.core.PySequence) 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