1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.giraph.jython;
19
20 import org.apache.giraph.graph.Language;
21 import org.apache.giraph.jython.factories.JythonComputationFactory;
22 import org.apache.hadoop.conf.Configuration;
23 import org.python.core.Py;
24 import org.python.core.PyObject;
25 import org.python.util.PythonInterpreter;
26
27 import static org.apache.giraph.conf.GiraphConstants.COMPUTATION_FACTORY_CLASS;
28 import static org.apache.giraph.conf.GiraphConstants.COMPUTATION_LANGUAGE;
29
30
31
32
33 public class JythonUtils {
34
35
36
37
38
39 private static final PythonInterpreter INTERPRETER =
40 new PythonInterpreter();
41
42
43 private JythonUtils() { }
44
45
46
47
48
49
50 public static PythonInterpreter getInterpreter() {
51 return INTERPRETER;
52 }
53
54
55
56
57
58
59
60 public static void init(Configuration conf, String klassName) {
61 COMPUTATION_LANGUAGE.set(conf, Language.JYTHON);
62 COMPUTATION_FACTORY_CLASS.set(conf, JythonComputationFactory.class);
63 JythonOptions.JYTHON_COMPUTATION_CLASS_NAME.set(conf, klassName);
64 }
65
66
67
68
69
70
71
72 public static PyObject newInstance(String className) {
73 PyObject pyClass = JythonUtils.getInterpreter().get(className);
74 PyObject pyObject = pyClass.__call__();
75 return pyObject;
76 }
77
78
79
80
81
82
83
84
85
86 public static <T> T newInstance(String className, Class<? extends T> klass) {
87 PyObject pyObject = newInstance(className);
88 Object object = pyObject.__tojava__(klass);
89 if (Py.NoConversion.equals(object)) {
90 throw new IllegalArgumentException("Cannot coerce Jython class " +
91 className + " to Java type " + klass.getSimpleName());
92 } else {
93 return (T) object;
94 }
95 }
96 }