| 42 | import org.python.core.PyTuple; |
| 43 | |
| 44 | public class JythonUtils { |
| 45 | |
| 46 | private static TupleFactory tupleFactory = TupleFactory.getInstance(); |
| 47 | private static BagFactory bagFactory = DefaultBagFactory.getInstance(); |
| 48 | |
| 49 | @SuppressWarnings("unchecked") |
| 50 | public static Object pythonToPig(PyObject pyObject) throws ExecException { |
| 51 | try { |
| 52 | Object javaObj = null; |
| 53 | // Add code for all supported pig types here |
| 54 | // Tuple, bag, map, int, long, float, double, chararray, bytearray |
| 55 | if (pyObject instanceof PyTuple) { |
| 56 | PyTuple pyTuple = (PyTuple) pyObject; |
| 57 | Object[] tuple = new Object[pyTuple.size()]; |
| 58 | int i = 0; |
| 59 | for (PyObject tupleObject : pyTuple.getArray()) { |
| 60 | tuple[i++] = pythonToPig(tupleObject); |
| 61 | } |
| 62 | javaObj = tupleFactory.newTuple(Arrays.asList(tuple)); |
| 63 | } else if (pyObject instanceof PyList) { |
| 64 | DataBag list = bagFactory.newDefaultBag(); |
| 65 | for (PyObject bagTuple : ((PyList) pyObject).asIterable()) { |
| 66 | // If the item of the array is not a tuple, |
| 67 | // wrap it into tuple before adding to bag |
| 68 | Object pigBagItem = pythonToPig(bagTuple); |
| 69 | Tuple pigBagTuple; |
| 70 | if (!(pigBagItem instanceof Tuple)) { |
| 71 | pigBagTuple = TupleFactory.getInstance().newTuple(1); |
| 72 | pigBagTuple.set(0, pigBagItem); |
| 73 | } else { |
| 74 | pigBagTuple = (Tuple)pigBagItem; |
| 75 | } |
| 76 | list.add(pigBagTuple); |
| 77 | } |
| 78 | javaObj = list; |
| 79 | } else if (pyObject instanceof PyDictionary) { |
| 80 | Map<?, Object> map = Py.tojava(pyObject, Map.class); |
| 81 | Map<Object, Object> newMap = new HashMap<Object, Object>(); |
| 82 | for (Map.Entry<?, Object> entry : map.entrySet()) { |
| 83 | if (entry.getValue() instanceof PyObject) { |
| 84 | newMap.put(entry.getKey(), pythonToPig((PyObject) entry.getValue())); |
| 85 | } else { |
| 86 | // Jython sometimes uses directly the java class: for example for integers |
| 87 | newMap.put(entry.getKey(), entry.getValue()); |
| 88 | } |
| 89 | } |
| 90 | javaObj = newMap; |
| 91 | } else if (pyObject instanceof PyLong) { |
| 92 | javaObj = pyObject.__tojava__(Long.class); |
| 93 | } else if (pyObject instanceof PyBoolean) { |
| 94 | javaObj = pyObject.__tojava__(Boolean.class); |
| 95 | } else if (pyObject instanceof PyInteger) { |
| 96 | javaObj = pyObject.__tojava__(Integer.class); |
| 97 | } else if (pyObject instanceof PyFloat) { |
| 98 | // J(P)ython is loosely typed, supports only float type, |
| 99 | // hence we convert everything to double to save precision |
| 100 | javaObj = pyObject.__tojava__(Double.class); |
| 101 | } else if (pyObject instanceof PyString) { |
nothing calls this directly
no test coverage detected