Java Examples for org.python.core.PyObject
The following java examples will help you to understand the usage of org.python.core.PyObject. These source code samples are taken from different open source projects.
Example 1
| Project: HBuilder-opensource-master File: binascii.java View source code |
/**
* Convert binhex4 formatted ASCII data to binary, without doing
* RLE-decompression. The string should contain a complete number of
* binary bytes, or (in case of the last portion of the binhex4 data)
* have the remaining bits zero.
*/
public static PyTuple a2b_hqx(String ascii_data) {
int leftbits = 0;
char this_ch;
int leftchar = 0;
boolean done = false;
int len = ascii_data.length();
StringBuffer bin_data = new StringBuffer();
for (int i = 0; len > 0; len--, i++) {
// Get the byte and look it up
this_ch = (char) table_a2b_hqx[ascii_data.charAt(i)];
if (this_ch == SKIP)
continue;
if (this_ch == FAIL) {
throw new PyException(Error, "Illegal char");
}
if (this_ch == DONE) {
// The terminating colon
done = true;
break;
}
// Shift it into the buffer and see if any bytes are ready
leftchar = (leftchar << 6) | (this_ch);
leftbits += 6;
if (leftbits >= 8) {
leftbits -= 8;
bin_data.append((char) ((leftchar >> leftbits) & 0xff));
leftchar &= ((1 << leftbits) - 1);
}
}
if (leftbits != 0 && !done) {
throw new PyException(Incomplete, "String has incomplete number of bytes");
}
return new PyTuple(new PyObject[] { Py.java2py(bin_data.toString()), Py.newInteger(done ? 1 : 0) });
}Example 2
| Project: jythonroid-master File: binascii.java View source code |
/**
* Convert binhex4 formatted ASCII data to binary, without doing
* RLE-decompression. The string should contain a complete number of
* binary bytes, or (in case of the last portion of the binhex4 data)
* have the remaining bits zero.
*/
public static PyTuple a2b_hqx(String ascii_data) {
int leftbits = 0;
char this_ch;
int leftchar = 0;
boolean done = false;
int len = ascii_data.length();
StringBuffer bin_data = new StringBuffer();
for (int i = 0; len > 0; len--, i++) {
// Get the byte and look it up
this_ch = (char) table_a2b_hqx[ascii_data.charAt(i)];
if (this_ch == SKIP)
continue;
if (this_ch == FAIL) {
throw new PyException(Error, "Illegal char");
}
if (this_ch == DONE) {
// The terminating colon
done = true;
break;
}
// Shift it into the buffer and see if any bytes are ready
leftchar = (leftchar << 6) | (this_ch);
leftbits += 6;
if (leftbits >= 8) {
leftbits -= 8;
bin_data.append((char) ((leftchar >> leftbits) & 0xff));
leftchar &= ((1 << leftbits) - 1);
}
}
if (leftbits != 0 && !done) {
throw new PyException(Incomplete, "String has incomplete number of bytes");
}
return new PyTuple(new PyObject[] { Py.java2py(bin_data.toString()), Py.newInteger(done ? 1 : 0) });
}Example 3
| Project: jiac-examples-master File: SimpleEmbedded.java View source code |
public static void main(String[] args) throws PyException {
PythonInterpreter interp = new PythonInterpreter();
System.out.println("Hello, brave new world");
interp.exec("import sys");
interp.exec("print sys");
interp.set("a", new PyInteger(42));
interp.exec("print a");
interp.exec("x = 2+2");
PyObject x = interp.get("x");
System.out.println("x: " + x);
System.out.println("Goodbye, cruel world");
}Example 4
| Project: ringmud-master File: Compiler.java View source code |
private void convertPython() {
try {
PythonInterpreter interp = Interpreter.INSTANCE.getInterpreter();
//Provide the DocumentInfo class to all python-defined data.
InputStream documentInfoStream = Interpreter.INSTANCE.getInternalScript("compiler.py");
interp.execfile(documentInfoStream);
List<FileEntry> entriesToRemove = new ArrayList<FileEntry>();
List<FileEntry> entriesToAdd = new ArrayList<FileEntry>();
for (FileEntry entry : mudFile.getEntries("data")) {
if (entry.getEntryName().endsWith(".py")) {
//Add document info object to the interpreter.
interp.exec("__document__ = DocumentInfo()");
//Execute script
interp.execfile(new FileInputStream(entry.getFile()));
//Then convert to XML
List<Persistable> persistables = XMLConverter.getPersistables();
//More efficient to have one string, rather than create it
//in each iteration below. This will be the file name of the python file,
//minus the .py extension.
String fileRoot = entry.getEntryName();
fileRoot = fileRoot.substring(fileRoot.lastIndexOf("/"), fileRoot.length());
File tmp = File.createTempFile(fileRoot, ".xml");
FileOutputStream fileOut = new FileOutputStream(tmp);
BufferedOutputStream buffer = new BufferedOutputStream(fileOut);
PrintStream out = new PrintStream(buffer);
//Retrieve codebehind attribute from document info, if it is present.
PyObject documentInfo = interp.get("__document__");
String codebehind = (String) documentInfo.__findattr__("codebehind").__tojava__(String.class);
//Write beginning of XML document.
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
if (codebehind != null) {
out.print("<ring codebehind=\"" + codebehind + "\">");
} else {
out.println("<ring>");
}
//Write out each persistable to the XML document.
for (Persistable persistable : persistables) {
String xml = persistable.toXML();
out.println(xml);
}
//Write end of XML document.
out.println("</ring>");
XMLConverter.clear();
out.close();
buffer.close();
fileOut.close();
FileEntry fe = new FileEntry();
fe.setFile(tmp);
//Prefix should start with a /
fe.setEntryName("data" + fileRoot + ".xml");
entriesToAdd.add(fe);
entriesToRemove.add(entry);
//Cleanup!
interp.cleanup();
}
}
//Modify the mudfile to remove the python data files and replace them with the
//generated xml files.
mudFile.getEntries().removeAll(entriesToRemove);
mudFile.getEntries().addAll(entriesToAdd);
} catch (IOException e) {
e.printStackTrace();
}
}Example 5
| Project: twist-master File: SimpleTestExternalVariableGet.java View source code |
public void testSimpleTestExternalVariableGet() {
ExternalVariableFactory externalVariableFactory = new ExternalVariableFactory();
ExternalVariableType externalVariable = externalVariableFactory.create();
PyObject testVarInteger = externalVariable.getVariable("testVarInteger");
testVarInteger = (PyObject) testVarInteger.__tojava__(PyObject.class);
System.out.println("external variable testVarInteger get response: " + testVarInteger);
PyObject testVarList = externalVariable.getVariable("testVarList");
testVarList = (PyObject) testVarList.__tojava__(PyObject.class);
System.out.println("external variable testVarList get response: " + testVarList);
PyObject testVarHashMap = externalVariable.getVariable("testVarHashMap");
testVarHashMap = (PyObject) testVarHashMap.__tojava__(PyObject.class);
System.out.println("external variable testVarList get response: " + testVarHashMap);
}Example 6
| Project: twister.github.io-master File: SimpleTestExternalVariableGet.java View source code |
public void testSimpleTestExternalVariableGet() {
ExternalVariableFactory externalVariableFactory = new ExternalVariableFactory();
ExternalVariableType externalVariable = externalVariableFactory.create();
PyObject testVarInteger = externalVariable.getVariable("testVarInteger");
testVarInteger = (PyObject) testVarInteger.__tojava__(PyObject.class);
System.out.println("external variable testVarInteger get response: " + testVarInteger);
PyObject testVarList = externalVariable.getVariable("testVarList");
testVarList = (PyObject) testVarList.__tojava__(PyObject.class);
System.out.println("external variable testVarList get response: " + testVarList);
PyObject testVarHashMap = externalVariable.getVariable("testVarHashMap");
testVarHashMap = (PyObject) testVarHashMap.__tojava__(PyObject.class);
System.out.println("external variable testVarList get response: " + testVarHashMap);
}Example 7
| Project: FreeVoteBot-master File: ScriptModuleLoader.java View source code |
/**
* Loads a module from a Python file that contains a class with the <b>SAME</b> name as the file.
* The class must extend {@link ExternalModule}.
*
* @param f the file to load the {@link org.freecode.irc.votebot.api.ExternalModule} from
* @return the {@link ExternalModule} loaded, or <tt>null</tt>
* @throws IOException if the file was not found
* @throws ScriptException if the script failed to load
*/
public ExternalModule loadFromFile(final File f) throws IOException, ScriptException {
if (f == null || !f.exists()) {
throw new IOException("Invalid file");
}
if (f.getName().endsWith(".py")) {
PythonInterpreter interpreter = new PythonInterpreter();
String clzName = f.getName().replace(".py", "");
interpreter.exec(String.format("from %s import %s", clzName, clzName));
PyObject pyClass = interpreter.get(clzName);
PyObject buildObject = pyClass.__call__();
ExternalModule ext = (ExternalModule) buildObject.__tojava__(ExternalModule.class);
ext.setFvb(fvb);
ext.setExtName(clzName);
interpreter.cleanup();
return ext;
}
return null;
}Example 8
| Project: gutenberg-master File: PygmentsTest.java View source code |
@Test
public void raw_usecase() {
PythonInterpreter interpreter = new PyGateway().getInterpreter();
// Set a variable with the content you want to work with
interpreter.set("code", "" + "(defn year-end-evaluation\n" + " []\n" + " (if (> (rand) 0.5)\n" + " \"You get a raise!\"\n" + " \"Better luck next year!\"))");
// Simple use Pygments as you would in Python
interpreter.exec("from pygments import highlight\n" + "from pygments.lexers.jvm import ClojureLexer\n" + "from pygments.formatters import RawTokenFormatter\n" + "\n" + "result = highlight(code, ClojureLexer(), RawTokenFormatter())");
// Get the result that has been set in a variable
PyObject result = interpreter.get("result");
PyString string = (PyString) result;
assertThat(string.getString()).isEqualTo("" + "Token.Punctuation\tu'('\n" + "Token.Keyword.Declaration\tu'defn '\n" + "Token.Name.Variable\tu'year-end-evaluation'\n" + "Token.Text\tu'\\n '\n" + "Token.Punctuation\tu'['\n" + "Token.Punctuation\tu']'\n" + "Token.Text\tu'\\n '\n" + "Token.Punctuation\tu'('\n" + "Token.Keyword\tu'if '\n" + "Token.Punctuation\tu'('\n" + "Token.Name.Builtin\tu'> '\n" + "Token.Punctuation\tu'('\n" + "Token.Name.Function\tu'rand'\n" + "Token.Punctuation\tu')'\n" + "Token.Text\tu' '\n" + "Token.Literal.Number.Float\tu'0.5'\n" + "Token.Punctuation\tu')'\n" + "Token.Text\tu'\\n '\n" + "Token.Literal.String\tu'\"You get a raise!\"'\n" + "Token.Text\tu'\\n '\n" + "Token.Literal.String\tu'\"Better luck next year!\"'\n" + "Token.Punctuation\tu')'\n" + "Token.Punctuation\tu')'\n" + "Token.Text\tu'\\n'\n");
}Example 9
| Project: jython-on-android-master File: cPickle.java View source code |
/**
* Initialization when module is imported.
*/
public static void classDictInit(PyObject dict) {
cPickle.dict = dict;
// XXX: Hack for JPython 1.0.1. By default __builtin__ is not in
// sys.modules.
imp.importName("__builtin__", true);
PyModule copyreg = (PyModule) importModule("copy_reg");
dispatch_table = (PyDictionary) copyreg.__getattr__("dispatch_table");
extension_registry = (PyDictionary) copyreg.__getattr__("_extension_registry");
inverted_registry = (PyDictionary) copyreg.__getattr__("_inverted_registry");
PickleError = Py.makeClass("PickleError", Py.Exception, _PickleError());
PicklingError = Py.makeClass("PicklingError", PickleError, exceptionNamespace());
UnpickleableError = Py.makeClass("UnpickleableError", PicklingError, _UnpickleableError());
UnpicklingError = Py.makeClass("UnpicklingError", PickleError, exceptionNamespace());
BadPickleGet = Py.makeClass("BadPickleGet", UnpicklingError, exceptionNamespace());
}Example 10
| Project: freemarker-old-master File: JythonWrapper.java View source code |
/**
* Coerces a template model into a {@link PyObject}.
* @param model the model to coerce
* @return the coerced model.
* <ul>
* <li>
* <li>{@link AdapterTemplateModel}s (i.e. {@link freemarker.ext.beans.BeanModel}) are marshalled
* using the standard Python marshaller {@link Py#java2py(Object)} on
* the result of <code>getWrappedObject(PyObject.class)</code>s. The
* native JythonModel instances will just return the underlying PyObject.
* <li>All other models that are {@link TemplateScalarModel scalars} are
* marshalled as {@link PyString}.
* <li>All other models that are {@link TemplateNumberModel numbers} are
* marshalled using the standard Python marshaller
* {@link Py#java2py(Object)} on their underlying <code>Number</code></li>
* <li>All other models are marshalled to a generic internal
* <code>PyObject</code> subclass that'll correctly pass
* <code>__finditem__</code>, <code>__len__</code>,
* <code>__nonzero__</code>, and <code>__call__</code> invocations to
* appropriate hash, sequence, and method models.</li>
* </ul>
*/
public PyObject unwrap(TemplateModel model) throws TemplateModelException {
if (model instanceof AdapterTemplateModel) {
return Py.java2py(((AdapterTemplateModel) model).getAdaptedObject(PYOBJECT_CLASS));
}
if (model instanceof WrapperTemplateModel) {
return Py.java2py(((WrapperTemplateModel) model).getWrappedObject());
}
// Scalars are marshalled to PyString.
if (model instanceof TemplateScalarModel) {
return new PyString(((TemplateScalarModel) model).getAsString());
}
// Numbers are wrapped to Python built-in numeric types.
if (model instanceof TemplateNumberModel) {
Number number = ((TemplateNumberModel) model).getAsNumber();
if (number instanceof BigDecimal) {
number = OptimizerUtil.optimizeNumberRepresentation(number);
}
if (number instanceof BigInteger) {
// release.
return new PyLong((BigInteger) number);
} else {
return Py.java2py(number);
}
}
// Return generic TemplateModel-to-Python adapter
return new TemplateModelToJythonAdapter(model);
}Example 11
| Project: geoserver-old-master File: PythonAppResource.java View source code |
/**
* Creates the environment object.
* <pre>
* REQUEST_METHOD
* The HTTP request method, such as "GET" or "POST". This cannot ever be
* an empty string, and so is always required.
* SCRIPT_NAME
* The initial portion of the request URL's "path" that corresponds to the
* application object, so that the application knows its virtual "location"
* . This may be an empty string, if the application corresponds to the
* "root" of the server.
* PATH_INFO
* The remainder of the request URL's "path", designating the virtual
* "location" of the request's target within the application. This may be
* an empty string, if the request URL targets the application root and
* does not have a trailing slash.
* QUERY_STRING
* The portion of the request URL that follows the "?", if any. May be
* empty or absent.
* CONTENT_TYPE
* The contents of any Content-Type fields in the HTTP request. May be
* empty or absent.
* CONTENT_LENGTH
* The contents of any Content-Length fields in the HTTP request. May be
* empty or absent.
* SERVER_NAME, SERVER_PORT
* When combined with SCRIPT_NAME and PATH_INFO, these variables can be
* used to complete the URL. Note, however, that HTTP_HOST, if present,
* should be used in preference to SERVER_NAME for reconstructing the
* request URL. See the URL Reconstruction section below for more detail.
* SERVER_NAME and SERVER_PORT can never be empty strings, and so are
* always required.
* SERVER_PROTOCOL
* The version of the protocol the client used to send the request.
* Typically this will be something like "HTTP/1.0" or "HTTP/1.1" and may
* be used by the application to determine how to treat any HTTP request
* headers. (This variable should probably be called REQUEST_PROTOCOL,
* since it denotes the protocol used in the request, and is not
* necessarily the protocol that will be used in the server's response.
* However, for compatibility with CGI we have to keep the existing name.)
* HTTP_ Variables
* Variables corresponding to the client-supplied HTTP request headers
* (i.e., variables whose names begin with "HTTP_"). The presence or
* absence of these variables should correspond with the presence or
* absence of the appropriate HTTP header in the request.
*
* </pre>
* @param request
* @return
*/
PyObject createEnviron(Request request) {
PyDictionary environ = new PyDictionary();
environ.put("REQUEST_METHOD", request.getMethod().toString());
Reference ref = request.getResourceRef();
environ.put("SCRIPT_NAME", ref.getLastSegment());
Reference pref = ref.getParentRef();
environ.put("PATH_INFO", pref.toString().substring(request.getRootRef().toString().length(), pref.toString().length() - 1));
environ.put("QUERY_STRING", request.getResourceRef().getQuery());
//TODO: fill in rest of parameters
return environ;
}Example 12
| Project: geoserver_trunk-master File: PythonAppResource.java View source code |
/**
* Creates the environment object.
* <pre>
* REQUEST_METHOD
* The HTTP request method, such as "GET" or "POST". This cannot ever be
* an empty string, and so is always required.
* SCRIPT_NAME
* The initial portion of the request URL's "path" that corresponds to the
* application object, so that the application knows its virtual "location"
* . This may be an empty string, if the application corresponds to the
* "root" of the server.
* PATH_INFO
* The remainder of the request URL's "path", designating the virtual
* "location" of the request's target within the application. This may be
* an empty string, if the request URL targets the application root and
* does not have a trailing slash.
* QUERY_STRING
* The portion of the request URL that follows the "?", if any. May be
* empty or absent.
* CONTENT_TYPE
* The contents of any Content-Type fields in the HTTP request. May be
* empty or absent.
* CONTENT_LENGTH
* The contents of any Content-Length fields in the HTTP request. May be
* empty or absent.
* SERVER_NAME, SERVER_PORT
* When combined with SCRIPT_NAME and PATH_INFO, these variables can be
* used to complete the URL. Note, however, that HTTP_HOST, if present,
* should be used in preference to SERVER_NAME for reconstructing the
* request URL. See the URL Reconstruction section below for more detail.
* SERVER_NAME and SERVER_PORT can never be empty strings, and so are
* always required.
* SERVER_PROTOCOL
* The version of the protocol the client used to send the request.
* Typically this will be something like "HTTP/1.0" or "HTTP/1.1" and may
* be used by the application to determine how to treat any HTTP request
* headers. (This variable should probably be called REQUEST_PROTOCOL,
* since it denotes the protocol used in the request, and is not
* necessarily the protocol that will be used in the server's response.
* However, for compatibility with CGI we have to keep the existing name.)
* HTTP_ Variables
* Variables corresponding to the client-supplied HTTP request headers
* (i.e., variables whose names begin with "HTTP_"). The presence or
* absence of these variables should correspond with the presence or
* absence of the appropriate HTTP header in the request.
*
* </pre>
* @param request
* @return
*/
PyObject createEnviron(Request request) {
PyDictionary environ = new PyDictionary();
environ.put("REQUEST_METHOD", request.getMethod().toString());
Reference ref = request.getResourceRef();
environ.put("SCRIPT_NAME", ref.getLastSegment());
Reference pref = ref.getParentRef();
environ.put("PATH_INFO", pref.toString().substring(request.getRootRef().toString().length(), pref.toString().length() - 1));
environ.put("QUERY_STRING", request.getResourceRef().getQuery());
//TODO: fill in rest of parameters
return environ;
}Example 13
| Project: incubator-freemarker-master File: JythonWrapper.java View source code |
/**
* Coerces a template model into a {@link PyObject}.
* @param model the model to coerce
* @return the coerced model.
* <ul>
* <li>
* <li>{@link AdapterTemplateModel}s (i.e. {@link freemarker.ext.beans.BeanModel}) are marshalled
* using the standard Python marshaller {@link Py#java2py(Object)} on
* the result of <code>getWrappedObject(PyObject.class)</code>s. The
* native JythonModel instances will just return the underlying PyObject.
* <li>All other models that are {@link TemplateScalarModel scalars} are
* marshalled as {@link PyString}.
* <li>All other models that are {@link TemplateNumberModel numbers} are
* marshalled using the standard Python marshaller
* {@link Py#java2py(Object)} on their underlying <code>Number</code></li>
* <li>All other models are marshalled to a generic internal
* <code>PyObject</code> subclass that'll correctly pass
* <code>__finditem__</code>, <code>__len__</code>,
* <code>__nonzero__</code>, and <code>__call__</code> invocations to
* appropriate hash, sequence, and method models.</li>
* </ul>
*/
public PyObject unwrap(TemplateModel model) throws TemplateModelException {
if (model instanceof AdapterTemplateModel) {
return Py.java2py(((AdapterTemplateModel) model).getAdaptedObject(PYOBJECT_CLASS));
}
if (model instanceof WrapperTemplateModel) {
return Py.java2py(((WrapperTemplateModel) model).getWrappedObject());
}
// Scalars are marshalled to PyString.
if (model instanceof TemplateScalarModel) {
return new PyString(((TemplateScalarModel) model).getAsString());
}
// Numbers are wrapped to Python built-in numeric types.
if (model instanceof TemplateNumberModel) {
Number number = ((TemplateNumberModel) model).getAsNumber();
if (number instanceof BigDecimal) {
number = OptimizerUtil.optimizeNumberRepresentation(number);
}
if (number instanceof BigInteger) {
// release.
return new PyLong((BigInteger) number);
} else {
return Py.java2py(number);
}
}
// Return generic TemplateModel-to-Python adapter
return new TemplateModelToJythonAdapter(model);
}Example 14
| Project: scriptographer-master File: JythonScope.java View source code |
public Object get(String name) {
try {
PyObject obj = scope.__getitem__(Py.java2py(name));
if (obj == null)
return null;
if (obj.isCallable())
return new JythonCallable(obj);
return obj.__tojava__(Object.class);
} catch (PyException e) {
return null;
}
}Example 15
| Project: cloud-slang-master File: ScriptExecutorTest.java View source code |
@Test
public void testExecuteScript() throws Exception {
reset(execInterpreter);
final String script = "pass";
Map<String, Value> scriptInputValues = new HashMap<>();
Value value1 = ValueFactory.create("value1");
Value value2 = ValueFactory.create("value2");
scriptInputValues.put("input1", value1);
scriptInputValues.put("input2", value2);
Map<Object, PyObject> scriptOutputValues = new HashMap<>();
PyObject pyObjectValue1 = (PyObject) ValueFactory.createPyObjectValue("value1", false);
PyObject pyObjectValue2 = (PyObject) ValueFactory.createPyObjectValue("value2", false);
scriptOutputValues.put("output1", pyObjectValue1);
scriptOutputValues.put("output2", pyObjectValue2);
when(execInterpreter.getLocals()).thenReturn(new PyStringMap(scriptOutputValues));
when(execInterpreter.get(eq("output1"))).thenReturn(pyObjectValue1);
when(execInterpreter.get(eq("output2"))).thenReturn(pyObjectValue2);
Map<String, Serializable> expectedScriptOutputs = new HashMap<>();
expectedScriptOutputs.put("output1", value1);
expectedScriptOutputs.put("output2", value2);
final Map<String, Value> outputs = scriptExecutor.executeScript(script, scriptInputValues);
verify(execInterpreter).set(eq("input1"), eq((Value) pyObjectValue1));
verify(execInterpreter).set(eq("input2"), eq((Value) pyObjectValue2));
verify(execInterpreter).exec(script);
Assert.assertEquals(expectedScriptOutputs, outputs);
}Example 16
| Project: DrupalLoadTest-master File: AbstractJythonInstrumenterTestCase.java View source code |
protected final Class<?> getClassForInstance(PyInstance target) throws IllegalArgumentException, IllegalAccessException {
Field f;
try {
// Jython 2.1
f = PyObject.class.getField("__class__");
} catch (NoSuchFieldException e) {
try {
f = PyInstance.class.getField("instclass");
} catch (NoSuchFieldException e2) {
throw new AssertionError("Incompatible Jython release in classpath");
}
}
final PyClass pyClass = (PyClass) f.get(target);
return (Class<?>) pyClass.__tojava__(Class.class);
}Example 17
| Project: giraph-gora-master File: HiveJythonUtils.java View source code |
/**
* Initialize a graph type (IVEMM)
*
* @param conf Configuration
* @param graphType GraphType
* @param jythonOrJavaClass jython or java class given by user
* @param jythonFactory Jactory for making Jython types
* @param interpreter PythonInterpreter
* @return Class for Configuration
*/
private static Class initValueType(Configuration conf, GraphType graphType, Object jythonOrJavaClass, JythonFactoryBase jythonFactory, PythonInterpreter interpreter) {
Class<? extends Writable> writableClass = graphType.interfaceClass();
LanguageAndType langType = processUserType(jythonOrJavaClass, interpreter);
switch(langType.getLanguage()) {
case JAVA:
GRAPH_TYPE_LANGUAGES.set(conf, graphType, Language.JAVA);
checkImplements(langType, writableClass, interpreter);
return langType.getJavaClass();
case JYTHON:
GRAPH_TYPE_LANGUAGES.set(conf, graphType, Language.JYTHON);
String jythonClassName = langType.getJythonClassName();
PyObject jythonClass = interpreter.get(jythonClassName);
if (jythonClass == null) {
throw new IllegalArgumentException("Could not find Jython class " + jythonClassName + " for parameter " + graphType);
}
PyObject valuePyObj = jythonClass.__call__();
// Check if the Jython type implements Writable. If so, just use it
// directly. Otherwise, wrap it in a class that does using pickle.
Object pyWritable = valuePyObj.__tojava__(writableClass);
if (pyWritable.equals(Py.NoConversion)) {
GiraphConstants.GRAPH_TYPES_NEEDS_WRAPPERS.set(conf, graphType, true);
jythonFactory.useThisFactory(conf, jythonClassName);
return JythonWritableWrapper.class;
} else {
GiraphConstants.GRAPH_TYPES_NEEDS_WRAPPERS.set(conf, graphType, false);
jythonFactory.useThisFactory(conf, jythonClassName);
return writableClass;
}
default:
throw new IllegalArgumentException("Don't know how to handle " + LanguageAndType.class.getSimpleName() + " with language " + langType.getLanguage());
}
}Example 18
| Project: OpenRefine-master File: JythonHasFieldsWrapper.java View source code |
@Override public PyObject __finditem__(PyObject key) { String k = (String) key.__tojava__(String.class); Object v = _obj.getField(k, _bindings); if (v != null) { if (v instanceof PyObject) { return (PyObject) v; } else if (v instanceof HasFields) { return new JythonHasFieldsWrapper((HasFields) v, _bindings); } else if (Py.getAdapter().canAdapt(v)) { return Py.java2py(v); } else { return new JythonObjectWrapper(v); } } else { return null; } }
Example 19
| Project: Pydev-master File: JythonPlugin.java View source code |
/**
* @param pythonpathFolders folders that should be in the pythonpath when executing the script
* @see JythonPlugin#exec(HashMap, String, PythonInterpreter)
* Same as before but the file to execute is passed as a parameter
*/
public static Throwable exec(HashMap<String, Object> locals, IPythonInterpreter interpreter, File fileToExec, File[] pythonpathFolders, String... argv) {
if (locals == null) {
locals = new HashMap<String, Object>();
}
if (interpreter == null) {
//already disposed
return null;
}
locals.put("__file__", fileToExec.toString());
try {
String codeObjName;
synchronized (codeCache) {
//hold on there... one at a time... please?
String fileName = fileToExec.getName();
if (!fileName.endsWith(".py")) {
throw new RuntimeException("The script to be executed must be a python file. Name:" + fileName);
}
codeObjName = "code" + fileName.substring(0, fileName.indexOf('.'));
final String codeObjTimestampName = codeObjName + "Timestamp";
for (Map.Entry<String, Object> entry : locals.entrySet()) {
interpreter.set(entry.getKey(), entry.getValue());
}
boolean regenerate = false;
if (interpreter instanceof PythonInterpreterWrapperNotShared) {
//Always regenerate if the state is not shared! (otherwise the pythonpath might be wrong as the sys is not the same)
regenerate = true;
}
Tuple<Long, Object> timestamp = codeCache.get(fileToExec);
final long lastModified = FileUtils.lastModified(fileToExec);
if (timestamp == null || timestamp.o1 != lastModified) {
//the file timestamp changed, so, we have to regenerate it
regenerate = true;
}
if (!regenerate) {
//if the 'code' object does not exist or if it's timestamp is outdated, we have to re-set it.
PyObject obj = interpreter.get(codeObjName);
PyObject pyTime = interpreter.get(codeObjTimestampName);
if (obj == null || pyTime == null || !pyTime.__tojava__(Long.class).equals(timestamp.o1)) {
if (DEBUG) {
System.out.println("Resetting object: " + codeObjName);
}
interpreter.set(codeObjName, timestamp.o2);
interpreter.set(codeObjTimestampName, timestamp.o1);
}
}
if (regenerate) {
if (DEBUG) {
System.out.println("Regenerating: " + codeObjName);
}
String path = FileUtils.getFileAbsolutePath(fileToExec);
StringBuffer strPythonPathFolders = new StringBuffer();
strPythonPathFolders.append("[");
for (File file : pythonpathFolders) {
if (file != null) {
strPythonPathFolders.append("r'");
strPythonPathFolders.append(FileUtils.getFileAbsolutePath(file));
strPythonPathFolders.append("',");
}
}
strPythonPathFolders.append("]");
StringBuffer addToSysPath = new StringBuffer();
//we will only add the paths to the pythonpath if it was still not set or if it changed (but it will never remove the ones added before).
//we have to put that in sys because it is the same across different interpreters
addToSysPath.append("if not hasattr(sys, 'PYDEV_PYTHONPATH_SET') or sys.PYDEV_PYTHONPATH_SET != ");
addToSysPath.append(strPythonPathFolders);
addToSysPath.append(":\n");
addToSysPath.append(" sys.PYDEV_PYTHONPATH_SET = ");
addToSysPath.append(strPythonPathFolders);
addToSysPath.append("\n");
addToSysPath.append(" sys.path += ");
addToSysPath.append(strPythonPathFolders);
addToSysPath.append("\n");
if (argv.length > 0) {
addToSysPath.append("sys.argv = [");
for (String s : argv) {
addToSysPath.append(s);
addToSysPath.append(",");
}
addToSysPath.append("];");
addToSysPath.append("\n");
}
String toExec = StringUtils.format(LOAD_FILE_SCRIPT, path, path, addToSysPath.toString());
interpreter.exec(toExec);
String exec = StringUtils.format("%s = compile(toExec, r'%s', 'exec')", codeObjName, path);
interpreter.exec(exec);
//set its timestamp
interpreter.set(codeObjTimestampName, lastModified);
Object codeObj = interpreter.get(codeObjName);
codeCache.put(fileToExec, new Tuple<Long, Object>(lastModified, codeObj));
}
}
interpreter.exec(StringUtils.format("exec(%s)", codeObjName));
} catch (Throwable e) {
if (!IN_TESTS && JythonPlugin.getDefault() == null) {
return null;
}
if (e instanceof ExitScriptException) {
return null;
}
if (e instanceof PyException) {
PyException pE = (PyException) e;
if (pE.type instanceof PyJavaType) {
PyJavaType t = (PyJavaType) pE.type;
if (t.getName() != null && t.getName().indexOf("ExitScriptException") != -1) {
return null;
}
} else if (pE.type instanceof PyClass) {
PyClass t = (PyClass) pE.type;
if (t.__name__ != null && t.__name__.equals("SystemExit")) {
return null;
}
}
}
if (JyScriptingPreferencesPage.getShowScriptingOutput()) {
Log.log(IStatus.ERROR, "Error while executing:" + fileToExec, e);
}
return e;
}
return null;
}Example 20
| Project: qafe-platform-master File: PythonScriptEngine.java View source code |
private synchronized PyObject exec(Script script) {
interp.set("result", null);
try {
for (Iterator iter = script.getParameters().keySet().iterator(); iter.hasNext(); ) {
String key = (String) iter.next();
Object value = script.getParameters().get(key);
interp.set(key, value);
}
interp.exec("result=" + SCRIPT_PREFIX + script.getValue() + SCRIPT_POSTFIX);
} catch (Exception e) {
throw new ScriptProcessingFailedException(script.toString(), e);
}
return interp.get("result");
}Example 21
| Project: spring-security-master File: PythonInterpreterPreInvocationAdvice.java View source code |
public boolean before(Authentication authentication, MethodInvocation mi, PreInvocationAttribute preAttr) {
PythonInterpreterPreInvocationAttribute pythonAttr = (PythonInterpreterPreInvocationAttribute) preAttr;
String script = pythonAttr.getScript();
PythonInterpreter python = new PythonInterpreter();
python.set("authentication", authentication);
python.set("args", createArgumentMap(mi));
python.set("method", mi.getMethod().getName());
Resource scriptResource = new PathMatchingResourcePatternResolver().getResource(script);
try {
python.execfile(scriptResource.getInputStream());
} catch (IOException e) {
throw new IllegalArgumentException("Couldn't run python script, " + script, e);
}
PyObject allowed = python.get("allow");
if (allowed == null) {
throw new IllegalStateException("Python script did not set the permit flag");
}
return (Boolean) Py.tojava(allowed, Boolean.class);
}Example 22
| Project: szeke-master File: SubmitPythonTransformationCommand.java View source code |
@Override
public UpdateContainer doIt(VWorkspace vWorkspace) throws CommandException {
Worksheet worksheet = vWorkspace.getViewFactory().getVWorksheet(vWorksheetId).getWorksheet();
RepFactory f = vWorkspace.getRepFactory();
HNode hNode = f.getHNode(hNodeId);
ExecutionController ctrl = WorkspaceRegistry.getInstance().getExecutionController(vWorkspace.getWorkspace().getId());
List<HNode> accessibleHNodes = f.getHNode(hNodeId).getHNodesAccessibleList(f);
List<HNode> nodesWithNestedTable = new ArrayList<HNode>();
Map<String, String> hNodeIdtoColumnNameMap = new HashMap<String, String>();
for (HNode accessibleHNode : accessibleHNodes) {
if (accessibleHNode.hasNestedTable()) {
nodesWithNestedTable.add(accessibleHNode);
} else {
hNodeIdtoColumnNameMap.put(accessibleHNode.getId(), accessibleHNode.getColumnName());
}
}
accessibleHNodes.removeAll(nodesWithNestedTable);
PythonTransformationHelper pyHelper = new PythonTransformationHelper();
Map<String, String> normalizedColumnNameMap = new HashMap<String, String>();
String clsStmt = pyHelper.getPythonClassCreationStatement(worksheet, normalizedColumnNameMap, accessibleHNodes);
String transformMethodStmt = pyHelper.getPythonTransformMethodDefinitionState(worksheet, transformationCode);
String columnNameDictStmt = pyHelper.getColumnNameDictionaryStatement(normalizedColumnNameMap);
String defGetValueStmt = pyHelper.getGetValueDefStatement(normalizedColumnNameMap);
// Create a map from hNodeId to normalized column name
Map<String, String> hNodeIdToNormalizedColumnName = new HashMap<String, String>();
for (HNode accHNode : accessibleHNodes) {
hNodeIdToNormalizedColumnName.put(accHNode.getId(), normalizedColumnNameMap.get(accHNode.getColumnName()));
}
try {
// Prepare the Python interpreter
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec(pyHelper.getImportStatements());
interpreter.exec(clsStmt);
interpreter.exec(columnNameDictStmt);
interpreter.exec(defGetValueStmt);
interpreter.exec(transformMethodStmt);
Collection<Node> nodes = new ArrayList<Node>();
worksheet.getDataTable().collectNodes(hNode.getHNodePath(f), nodes);
Map<String, String> rowToValueMap = new HashMap<String, String>();
// Go through all nodes collected for the column with given hNodeId
for (Node node : nodes) {
Row row = node.getBelongsToRow();
Map<String, String> values = node.getColumnValues();
StringBuilder objectCreationStmt = new StringBuilder();
objectCreationStmt.append("r = " + pyHelper.normalizeString(worksheet.getTitle()) + "(");
int keyCounter = 0;
for (String valHNodeId : values.keySet()) {
String nodeId = values.get(valHNodeId);
String nodeVal = f.getNode(nodeId).getValue().asString();
if (keyCounter++ != 0)
objectCreationStmt.append(",");
if (nodeVal == null || nodeVal.isEmpty()) {
objectCreationStmt.append(hNodeIdToNormalizedColumnName.get(valHNodeId) + "=\"\"");
} else {
nodeVal = nodeVal.replaceAll("\"", "\\\\\"");
nodeVal = nodeVal.replaceAll("\n", " ");
objectCreationStmt.append(hNodeIdToNormalizedColumnName.get(valHNodeId) + "=\"" + nodeVal + "\"");
}
}
objectCreationStmt.append(")");
interpreter.exec(objectCreationStmt.toString());
try {
PyObject output = interpreter.eval("transform(r)");
// Execution ran successfully, put the value returned in the HashMap
rowToValueMap.put(row.getId(), pyHelper.getPyObjectValueAsString(output));
} catch (PyException p) {
p.printStackTrace();
rowToValueMap.put(row.getId(), errorDefaultValue);
} catch (Exception t) {
t.printStackTrace();
logger.debug("Error occured while transforming.", t);
rowToValueMap.put(row.getId(), errorDefaultValue);
}
}
// Invoke the add column command
JSONArray addColumnInput = getAddColumnCommandInputJSON();
AddColumnCommandFactory addColumnFac = (AddColumnCommandFactory) ctrl.getCommandFactoryMap().get(AddColumnCommand.class.getSimpleName());
addColCmd = (AddColumnCommand) addColumnFac.createCommand(addColumnInput, vWorkspace);
addColCmd.saveInHistory(false);
addColCmd.doIt(vWorkspace);
// Invoke the MultipleValueEditColumnCommand
JSONArray multiCellEditInput = getMultiCellValueEditInputJSON(rowToValueMap, addColCmd.getNewHNodeId());
MultipleValueEditColumnCommandFactory mfc = (MultipleValueEditColumnCommandFactory) ctrl.getCommandFactoryMap().get(MultipleValueEditColumnCommand.class.getSimpleName());
MultipleValueEditColumnCommand mvecc = (MultipleValueEditColumnCommand) mfc.createCommand(multiCellEditInput, vWorkspace);
mvecc.doIt(vWorkspace);
} catch (Exception e) {
e.printStackTrace();
logger.error("Error occured during python transformation.", e);
return new UpdateContainer(new ErrorUpdate("Error occured while applying Python transformation to the column."));
}
// Prepare the output container
UpdateContainer c = new UpdateContainer();
vWorkspace.getViewFactory().updateWorksheet(vWorksheetId, worksheet, worksheet.getHeaders().getAllPaths(), vWorkspace);
vWorkspace.getViewFactory().getVWorksheet(this.vWorksheetId).update(c);
/** Add the alignment update **/
addAlignmentUpdate(c, vWorkspace, worksheet);
c.add(new InfoUpdate("Transformation complete"));
return c;
}Example 23
| Project: Centuries-of-Rage-master File: ScriptModule.java View source code |
public void run() {
while (true) {
// warten, wenn keine events anstehen:
if (events.isEmpty()) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(ScriptModule.class.getName()).log(Level.SEVERE, null, ex);
}
} else // verarbeiten, wenn events anstehen:
{
// event auslösen und dann von der liste entfernen:
for (PyObject script : scripts) {
events.get(0).trigger(script);
}
events.remove(0);
}
}
}Example 24
| Project: darks-orm-master File: PythonParser.java View source code |
/**
* Parse python script data
*
* @param aspectData Aspect data
* @param simpleWrapper {@linkplain darks.orm.core.data.xml.SimpleAspectWrapper SimpleAspectWrapper}
* @param queryEnumType {@linkplain darks.orm.app.QueryEnumType QueryEnumType}
* @param methodType ½âÎö·½·¨ÀàÐÍ JY_ASPECT_BEFORE or JY_ASPECT_AFTER
* @return ÊÇ·ñ¼ÌÐøÖ´ÐÐ
*/
public boolean parse(AspectData aspectData, SimpleAspectWrapper simpleWrapper, QueryEnumType queryEnumType, String methodType) throws JythonAspectException {
if (aspectData == null)
return true;
PythonInterpreter pyInter = initPythonInterpreter(simpleWrapper);
if (aspectData.getAspectType() == AspectType.JYTHON) {
String content = PythonBuilder.buildJython(aspectData, aspectData.getClassName(), aspectData.getContent());
try {
pyInter.exec(content);
} catch (Exception e) {
e.printStackTrace();
throw new JythonAspectException(e);
}
} else if (aspectData.getAspectType() == AspectType.PYFILE) {
pyInter.exec(PythonBuilder.getPythonHeader().toString());
pyInter.execfile(getFileInputStream(aspectData.getContent()));
pyInter.exec(PythonBuilder.buildJythonTail(aspectData.getClassName()));
} else {
return true;
}
PyObject aspectObj = pyInter.get(PythonBuilder.JY_ASPECT_CLASS);
PyObject retObj = aspectObj.invoke(methodType);
if (retObj == null || retObj instanceof PyNone) {
return false;
} else {
Integer ret = (Integer) JythonFactory.getInstance().pyObjectToObject(retObj, Integer.class);
if (ret == 0)
return false;
else
return true;
}
}Example 25
| Project: geoserver-master File: PyAppHook.java View source code |
@Override
public void run(Request request, Response response, ScriptEngine engine) throws ScriptException, IOException {
Object obj = engine.get("app");
if (obj == null) {
throw new RuntimeException("No 'app' function defined");
}
if (!(obj instanceof PyObject)) {
throw new RuntimeException("'app not callable, found a " + obj.toString());
}
PyObject app = (PyObject) obj;
WSGIResponse wr = new WSGIResponse();
RESPONSE.set(wr);
try {
Object ret = app.__call__(new PyObject[] { createEnviron(request), createStartResponse() });
if (ret != null) {
String contentType = wr.headers.get("content-type");
if (contentType == null) {
contentType = "text/plain";
}
MediaType mediaType = new MediaType(contentType);
if (ret instanceof PyString) {
response.setEntity(ret.toString(), mediaType);
} else if (ret instanceof PyList) {
final PyList list = (PyList) ret;
response.setEntity(new OutputRepresentation(mediaType) {
@Override
public void write(OutputStream outputStream) throws IOException {
for (Iterator i = list.iterator(); i.hasNext(); ) {
outputStream.write(i.next().toString().getBytes());
if (i.hasNext()) {
outputStream.write('\n');
}
}
}
});
} else if (ret instanceof PyIterator) {
final PyIterator iter = (PyIterator) ret;
response.setEntity(new OutputRepresentation(mediaType) {
@Override
public void write(OutputStream outputStream) throws IOException {
for (Iterator i = iter.iterator(); i.hasNext(); ) {
outputStream.write(i.next().toString().getBytes());
outputStream.write('\n');
}
}
});
} else if (ret instanceof PyObjectDerived) {
final PyObjectDerived iter = (PyObjectDerived) ret;
response.setEntity(new OutputRepresentation(mediaType) {
@Override
public void write(OutputStream outputStream) throws IOException {
PyObject next = null;
while ((next = iter.__iternext__()) != null) {
outputStream.write(next.toString().getBytes());
outputStream.write('\n');
}
}
});
} else {
LOGGER.warning("Unsure how to handle " + ret + ". Resorting to outputing string " + "representation.");
response.setEntity(ret.toString(), mediaType);
}
}
} finally {
RESPONSE.remove();
}
}Example 26
| Project: giraph-master File: TestJythonWritableWrapper.java View source code |
@Test
public void testWrap() throws IOException {
String jython = "class Foo:\n" + " def __init__(self):\n" + " self.val = 17\n" + "\n" + " def do_add(self, x):\n" + " self.val += x\n" + "\n" + " def do_add_squared(self, x):\n" + " self.do_add(x * x)\n" + "\n" + " def new_other(self):\n" + " self.other_val = 3\n" + "\n" + "def outside_add_squared(foo, x):\n" + " foo.do_add_squared(x)\n" + "\n";
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec(jython);
PyObject fooClass = interpreter.get("Foo");
assertTrue(fooClass instanceof PyClass);
PyObject foo = fooClass.__call__();
PyObject fooVal = foo.__getattr__("val");
assertTrue(fooVal instanceof PyInteger);
PyInteger val = (PyInteger) fooVal;
assertEquals(17, val.getValue());
PyObject function = interpreter.get("outside_add_squared");
assertTrue("method class: " + function.getClass(), function instanceof PyFunction);
function.__call__(foo, new PyInteger(3));
fooVal = foo.__getattr__("val");
assertTrue(fooVal instanceof PyInteger);
val = (PyInteger) fooVal;
assertEquals(26, val.getValue());
JythonWritableWrapper wrappedFoo = new JythonWritableWrapper(foo);
PyObject newOtherMethod = wrappedFoo.__getattr__("new_other");
assertTrue(newOtherMethod instanceof PyMethod);
newOtherMethod.__call__();
function.__call__(wrappedFoo, new PyInteger(2));
fooVal = foo.__getattr__("val");
assertTrue(fooVal instanceof PyInteger);
val = (PyInteger) fooVal;
assertEquals(30, val.getValue());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
wrappedFoo.write(dos);
byte[] data = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(data);
DataInputStream dis = new DataInputStream(bais);
PyObject foo2 = fooClass.__call__();
PyObject foo2Val = foo2.__getattr__("val");
assertTrue(foo2Val instanceof PyInteger);
PyInteger val2 = (PyInteger) foo2Val;
assertEquals(17, val2.getValue());
JythonWritableWrapper wrappedFoo2 = new JythonWritableWrapper(foo2);
foo2Val = wrappedFoo2.getPyObject().__getattr__("val");
assertTrue(foo2Val instanceof PyInteger);
val2 = (PyInteger) foo2Val;
assertEquals(17, val2.getValue());
wrappedFoo2.readFields(dis);
foo2Val = wrappedFoo2.getPyObject().__getattr__("val");
assertTrue(foo2Val instanceof PyInteger);
val2 = (PyInteger) foo2Val;
assertEquals(30, val2.getValue());
}Example 27
| Project: interactivespaces-master File: PythonActivityScriptWrapper.java View source code |
@Override
public Activity newInstance() {
try {
PythonInterpreter interp = PythonInterpreter.threadLocalStateInterpreter(null);
// If script dir in the activity install, include at beginning of
// path.
File scriptDir = new File(activityFilesystem.getInstallDirectory(), "lib/python");
if (scriptDir.exists()) {
if (scriptDir.canRead()) {
PySystemState systemState = interp.getSystemState();
systemState.path.add(0, Py.newString(scriptDir.getAbsolutePath()));
}
}
String script = scriptSource.getScriptContents();
interp.exec(script);
PyObject cls = interp.get(objectName);
if (cls == null)
throw new InteractiveSpacesException(String.format("No callable class named %s in %s", objectName, script));
PyObject processingUnit = cls.__call__();
Object o = processingUnit.__tojava__(Activity.class);
if (o == Py.NoConversion)
throw new InteractiveSpacesException(String.format("The value with name %s must implement %s", objectName, Activity.class.getName()));
return (Activity) o;
} catch (PyException e) {
e.printStackTrace();
throw new InteractiveSpacesException("Could not create Jython Interactive Spaces activity ", e);
}
}Example 28
| Project: liferay-portal-master File: PythonExecutor.java View source code |
@Override
public Map<String, Object> eval(Set<String> allowedClasses, Map<String, Object> inputObjects, Set<String> outputNames, String script) throws ScriptingException {
if (allowedClasses != null) {
throw new ExecutionException("Constrained execution not supported for Python");
}
try {
PyCode compiledScript = getCompiledScript(script);
InteractiveInterpreter interactiveInterpreter = new InteractiveInterpreter();
for (Map.Entry<String, Object> entry : inputObjects.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
interactiveInterpreter.set(key, value);
}
interactiveInterpreter.exec(compiledScript);
if (outputNames == null) {
return null;
}
Map<String, Object> outputObjects = new HashMap<>();
for (String outputName : outputNames) {
PyObject pyObject = interactiveInterpreter.get(outputName);
outputObjects.put(outputName, pyObject.__tojava__(Object.class));
}
return outputObjects;
} catch (PySyntaxError pySyntaxError) {
UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();
Py.displayException(pySyntaxError.type, pySyntaxError.value, pySyntaxError.traceback, new PyFile(unsyncByteArrayOutputStream));
String message = unsyncByteArrayOutputStream.toString();
throw new ScriptingException(message, pySyntaxError);
}
}Example 29
| Project: Parallel-Machine-Simulator-master File: Assignment.java View source code |
private PyObject getValue() throws SyntaxException {
try {
if (assignment.length() > 1) {
String infix = assignment.substring(0, assignment.length() - 1);
return pythonInterpreter.eval(var + infix + value);
} else {
return pythonInterpreter.eval(value);
}
} catch (Exception e) {
throw SyntaxException.invalidExpression(value);
}
}Example 30
| Project: squale-master File: FormulaInterpreter.java View source code |
/**
* @param pFormula la formule
* @param pMeasures mesures
* @return le résulat en phyton une fois la formule appliquée
* @throws FormulaException si erreur
*/
private PyObject calculate(AbstractFormulaBO pFormula, MeasureBO[] pMeasures) throws FormulaException {
// Obtention d'un interprète Python
PythonInterpreter inter = getInterpreter();
PyObject result = null;
try {
// Compilation de la formule correspondate
compileFormula(pFormula);
// Optimisation du traitement des chaînes
StringBuffer function = new StringBuffer();
function.append(FormulaConverter.FUNCTION_PREFIX);
long formulaId = pFormula.getId();
if (formulaId < 0) {
formulaId = 0;
}
function.append(formulaId);
function.append('(');
// Traitement de chacun des paramètres
for (int i = 0; i < pMeasures.length; i++) {
// Chaque paramètre suit une règle de nommage
String param = "measure" + i;
inter.set(param, pMeasures[i]);
// Cas de plusieurs paramètres
if (i > 0) {
function.append(',');
}
function.append(param);
}
function.append(')');
// Appel de la fonction
result = inter.eval(function.toString());
} catch (Throwable t) {
throw new FormulaException(t);
}
return result;
}Example 31
| Project: atlas-lb-master File: JysonCodec.java View source code |
/** * Decode the given JSON string, and return the corresponding Jython object (hierarchy) * * The behaviour of the decoder in relation to the incoming JSON expression is controlled by * several JysonCodec options. These options are exposed as public boolean attributes, which can be set * individually to <b>true</b> or <b>false</b>, or can be controlled as a group by the use of the * <b>strict_mode()</b> and <b>permissive_mode()</b> methods. * * @param json_text A java.lang.String containing the JSON text to be decoded * @return The Jython object (hierarchy) corresponding to the JSON text * @throws JSONDecodeError If an error occurred while decoding the JSON text * */ public static PyObject loads(PyObject[] args, String[] keywords) throws JSONDecodeError { String json_text = ((PyString) args[0]).toString(); JysonDecoder decoder = new JysonDecoder(json_text); boolean strict_mode_arg; for (int kix = 0; kix < keywords.length; kix++) { String keyword = keywords[kix]; PyObject value = args[args.length - keywords.length + kix]; if ("strict_mode".compareTo(keyword) == 0) { strict_mode_arg = value.__nonzero__(); if (strict_mode_arg) decoder.strict_mode(); else decoder.permissive_mode(); } if ("accept_any_primary_datum".compareTo(keyword) == 0) decoder.accept_any_primary_datum = value.__nonzero__(); if ("accept_dangling_commas".compareTo(keyword) == 0) decoder.accept_dangling_commas = value.__nonzero__(); if ("accept_shell_style_comments".compareTo(keyword) == 0) decoder.accept_shell_style_comments = value.__nonzero__(); if ("accept_single_quoted_strings".compareTo(keyword) == 0) decoder.accept_single_quoted_strings = value.__nonzero__(); if ("accept_hex_char_escapes".compareTo(keyword) == 0) decoder.accept_hex_char_escapes = value.__nonzero__(); if ("accept_hexadecimal_integers".compareTo(keyword) == 0) decoder.accept_hexadecimal_integers = value.__nonzero__(); if ("accept_octal_integers".compareTo(keyword) == 0) decoder.accept_octal_integers = value.__nonzero__(); if ("accept_junk_after_data".compareTo(keyword) == 0) decoder.accept_junk_after_data = value.__nonzero__(); } return decoder.get_top_level_object(); }
Example 32
| Project: cucumber-jvm-master File: JythonBackend.java View source code |
public void execute(PyInstance stepdef, Object[] args) throws Throwable {
PyObject[] pyArgs = new PyObject[args.length + 1];
pyArgs[0] = pyWorld;
for (int i = 0; i < args.length; i++) {
pyArgs[i + 1] = argToPyObject(args[i]);
}
try {
stepdef.invoke("execute", pyArgs);
} catch (PyException t) {
Object unwrapped = t.value.__tojava__(Object.class);
if (unwrapped instanceof Throwable) {
throw (Throwable) unwrapped;
} else {
throw t.getCause() == null ? t : t.getCause();
}
}
}Example 33
| Project: django-servlet-master File: DjangoServlet.java View source code |
public void init() throws ServletException {
// find the servlet root path
String rootpath = this.getServletContext().getRealPath("/");
if (!rootpath.endsWith(File.separator)) {
rootpath += File.separator;
}
// properties to pass to PySystemState.initialize
Properties props = new Properties();
Properties baseProps = PySystemState.getBaseProperties();
// adding all the element from the servlet context
// to the properties list
ServletContext context = this.getServletContext();
Enumeration e = context.getInitParameterNames();
while (e.hasMoreElements()) {
String n = (String) e.nextElement();
props.put(n, context.getInitParameter(n));
}
// also add any initialisation parameters to the
// properties list
e = this.getInitParameterNames();
while (e.hasMoreElements()) {
String n = (String) e.nextElement();
props.put(n, this.getInitParameter(n));
}
// servlet root path
if (props.getProperty("python.home") == null && baseProps.getProperty("python.home") == null) {
props.put("python.home", rootpath + "WEB-INF" + File.separator + "lib");
}
// make sure the django.handler property is set
if (props.getProperty("django.handler") == null) {
throw new ServletException("property 'django.handler' needs to be set");
}
String djangoAppHome = props.getProperty("django.app.home");
if (djangoAppHome == null) {
throw new ServletException("property 'django.app.home' needs to be set");
}
// get the django app name from the django.app.home variable
String djangoAppName = djangoAppHome.substring(djangoAppHome.lastIndexOf(File.separator) + 1);
PySystemState.initialize(baseProps, props, new String[0]);
this.sys = new PySystemState();
if (sys == null) {
throw new ServletException("unable to initialise jython");
}
this.sys.path.append(new PyString(djangoAppHome));
try {
// set the system state
Py.setSystemState(this.sys);
// load site packages
imp.load("site");
// load django app settings module
PyObject settings = imp.load("settings");
// get the setup_environ function from the django management module
PyObject setup_environ = imp.importName("django.core.management", false, null, new PyTuple(new PyString("setup_environ"))).__findattr__("setup_environ");
// call setup_environ
setup_environ.__call__(settings);
// load django servlet handler
this.handler = imp.importName(props.getProperty("django.handler"), false, null, new PyTuple(new PyString("handler"))).__findattr__("handler");
} catch (PyException pye) {
log.error(pye.getMessage(), pye);
if (!Py.matchException(pye, Py.ImportError)) {
log.error("error importing site");
}
}
}Example 34
| Project: flare-spork-master File: JythonScriptEngine.java View source code |
/**
* does not call script.close()
* @param script
* @param path
* @param pigContext
* @throws ExecException
*/
static void execfile(InputStream script, String path, PigContext pigContext) throws ExecException {
try {
if (pigContext != null) {
String[] argv;
try {
argv = (String[]) ObjectSerializer.deserialize(pigContext.getProperties().getProperty(PigContext.PIG_CMD_ARGS_REMAINDERS));
} catch (IOException e) {
throw new ExecException("Cannot deserialize command line arguments", e);
}
PySystemState state = Py.getSystemState();
state.argv.clear();
if (argv != null) {
for (String str : argv) {
state.argv.append(new PyString(str));
}
} else {
LOG.warn(PigContext.PIG_CMD_ARGS_REMAINDERS + " is empty. This is not expected unless on testing.");
}
}
// determine the current module state
Map<String, String> before = pigContext != null ? getModuleState() : null;
if (before != null) {
// os.py, stax.py and posixpath.py are part of the initial state
// if Lib directory is present and without including os.py, modules
// which import os fail
Set<String> includePyModules = new HashSet<String>();
for (String key : before.keySet()) {
// $py.class is created if Lib folder is writable
if (key.endsWith(".py") || key.endsWith("$py.class")) {
includePyModules.add(key);
}
}
before.keySet().removeAll(includePyModules);
}
// exec the code, arbitrary imports are processed
interpreter.execfile(script, path);
// determine the 'post import' module state
Map<String, String> after = pigContext != null ? getModuleState() : null;
// add the module files to the context
if (after != null && pigContext != null) {
after.keySet().removeAll(before.keySet());
for (Map.Entry<String, String> entry : after.entrySet()) {
String modulename = entry.getKey();
String modulepath = entry.getValue();
if (modulepath.equals(JVM_JAR)) {
continue;
} else if (modulepath.endsWith(".jar") || modulepath.endsWith(".zip")) {
pigContext.scriptJars.add(modulepath);
} else {
pigContext.addScriptFile(modulename, modulepath);
}
}
}
} catch (PyException e) {
if (e.match(Py.SystemExit)) {
PyObject value = e.value;
if (PyException.isExceptionInstance(e.value)) {
value = value.__findattr__("code");
}
if (new PyInteger(0).equals(value)) {
LOG.info("Script invoked sys.exit(0)");
return;
}
}
String message = "Python Error. " + e;
throw new ExecException(message, 1121, e);
}
}Example 35
| Project: ggp-base-master File: PythonGamer.java View source code |
// Gamer stubs are lazily loaded because the Python interface takes
// time to initialize, so we only want to load it when necessary, and
// not for light-weight things like returning the player name.
private void lazilyLoadGamerStub() {
if (thePythonGamer == null) {
try {
// Load in the Python gamer, using a Jython intepreter.
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("from " + getPythonGamerModule() + " import " + getPythonGamerName());
PyObject thePyClass = interpreter.get(getPythonGamerName());
PyObject PyGamerObject = thePyClass.__call__();
thePythonGamer = (Gamer) PyGamerObject.__tojava__(Gamer.class);
} catch (Exception e) {
GamerLogger.logError("GamePlayer", "Caught exception in Python initialization:");
GamerLogger.logStackTrace("GamePlayer", e);
}
}
}Example 36
| Project: hadoop-pig-master File: JythonUtils.java View source code |
@SuppressWarnings("unchecked")
public static Object pythonToPig(PyObject pyObject) throws ExecException {
try {
Object javaObj = null;
// Tuple, bag, map, int, long, float, double, chararray, bytearray
if (pyObject instanceof PyTuple) {
PyTuple pyTuple = (PyTuple) pyObject;
Object[] tuple = new Object[pyTuple.size()];
int i = 0;
for (PyObject tupleObject : pyTuple.getArray()) {
tuple[i++] = pythonToPig(tupleObject);
}
javaObj = tupleFactory.newTuple(Arrays.asList(tuple));
} else if (pyObject instanceof PyList) {
DataBag list = bagFactory.newDefaultBag();
for (PyObject bagTuple : ((PyList) pyObject).asIterable()) {
// In jython, list need not be a bag of tuples, as it is in case of pig
// So we fail with cast exception if we dont find tuples inside bag
// This is consistent with java udf (bag should be filled with tuples)
list.add((Tuple) pythonToPig(bagTuple));
}
javaObj = list;
} else if (pyObject instanceof PyDictionary) {
Map<?, PyObject> map = Py.tojava(pyObject, Map.class);
Map<Object, Object> newMap = new HashMap<Object, Object>();
for (Map.Entry<?, PyObject> entry : map.entrySet()) {
newMap.put(entry.getKey(), pythonToPig(entry.getValue()));
}
javaObj = newMap;
} else if (pyObject instanceof PyLong) {
javaObj = pyObject.__tojava__(Long.class);
} else if (pyObject instanceof PyInteger) {
javaObj = pyObject.__tojava__(Integer.class);
} else if (pyObject instanceof PyFloat) {
// J(P)ython is loosely typed, supports only float type,
// hence we convert everything to double to save precision
javaObj = pyObject.__tojava__(Double.class);
} else if (pyObject instanceof PyString) {
javaObj = pyObject.__tojava__(String.class);
} else if (pyObject instanceof PyNone) {
return null;
} else {
javaObj = pyObject.__tojava__(byte[].class);
// if we successfully converted to byte[]
if (javaObj instanceof byte[]) {
javaObj = new DataByteArray((byte[]) javaObj);
} else {
throw new ExecException("Non supported pig datatype found, cast failed");
}
}
if (javaObj.equals(Py.NoConversion)) {
throw new ExecException("Cannot cast into any pig supported type");
}
return javaObj;
} catch (Exception e) {
throw new ExecException("Cannot convert jython type to pig datatype " + e);
}
}Example 37
| Project: jsystem-master File: JythonScriptExecutor.java View source code |
@Override
public void run() {
PythonInterpreter interp = new JythonTestInterpreter();
PyObject result = null;
try {
// get the test
interp.exec(String.format("test = getTestByTag(r'%s', r'%s')", getJythonFile().getAbsolutePath(), tag));
// set up parameters
for (Parameter param : parameters.values()) {
if (!param.getName().contains(".")) {
String cmd = String.format("test.%s = '%s'", param.getName(), param.getValue().toString().replace("\\", "\\\\"));
interp.exec(cmd);
}
}
// run it
interp.exec("result = runTest(test)");
// get the result
result = interp.get("result");
} catch (Throwable e) {
exception = e;
}
int wasSuccesful = ((PyInteger) result.__getattr__("wasSuccessful").__call__()).getValue();
if (exception == null && wasSuccesful != 1) {
try {
interp.exec("errors = result.getErrors()");
String errors = interp.get("errors").toString();
exception = new JythonFailedException("Jython test failed!", errors);
} catch (Throwable e) {
exception = e;
}
}
}Example 38
| Project: L2jServer_Core-master File: JythonScriptEngine.java View source code |
private Object invokeImpl(Object obj, String name, Object... args) throws ScriptException, NoSuchMethodException {
if (name == null) {
throw new NullPointerException("method name is null");
}
setSystemState();
PyObject thiz;
if (obj instanceof PyObject) {
thiz = (PyObject) obj;
} else if (obj == null) {
thiz = myScope;
} else {
thiz = java2py(obj);
}
PyObject func = thiz.__findattr__(name);
if (((func == null) || !func.isCallable()) && (thiz == myScope)) {
systemState.get();
// lookup in built-in functions. This way
// user can call invoke built-in functions.
PyObject builtins = PySystemState.builtins;
func = builtins.__finditem__(name);
}
if ((func == null) || !func.isCallable()) {
throw new NoSuchMethodException(name);
}
PyObject res = func.__call__(wrapArguments(args));
return py2java(res);
}Example 39
| Project: minecraft-mod-python-master File: JavaMod.java View source code |
/**
* Instantiate the python mod instance and send it the pre-initialization
* event.
*
* *event* is the pre-initialization event.
*/
public void preInit(FMLPreInitializationEvent event) {
// Instantiate python mod class.
final String moduleName = this.getPythonModuleName();
final String className = this.getPythonClassName();
final PyString pyClassName = Py.newString(className);
this.log.fine("Load %s.%s", moduleName, className);
final PyObject pyModule = PyMod.python.importModule(moduleName);
final PyObject pyModClass = pyModule.__getattr__(pyClassName);
final PyObject pyModInst = pyModClass.__call__();
this.pythonMod = (IPythonMod) pyModInst.__tojava__(IPythonMod.class);
// Call mod pre-init.
this.log.fine("Pre-initialization.");
this.pythonMod.preInit(event);
}Example 40
| Project: pig-master File: JythonScriptEngine.java View source code |
/**
* does not call script.close()
* @param script
* @param path
* @param pigContext
* @throws ExecException
*/
static void execfile(InputStream script, String path, PigContext pigContext) throws ExecException {
try {
if (pigContext != null) {
String[] argv;
try {
argv = (String[]) ObjectSerializer.deserialize(pigContext.getProperties().getProperty(PigContext.PIG_CMD_ARGS_REMAINDERS));
} catch (IOException e) {
throw new ExecException("Cannot deserialize command line arguments", e);
}
PySystemState state = Py.getSystemState();
state.argv.clear();
if (argv != null) {
for (String str : argv) {
state.argv.append(new PyString(str));
}
} else {
LOG.warn(PigContext.PIG_CMD_ARGS_REMAINDERS + " is empty. This is not expected unless on testing.");
}
}
// determine the current module state
Map<String, String> before = pigContext != null ? getModuleState() : null;
if (before != null) {
// os.py, stax.py and posixpath.py are part of the initial state
// if Lib directory is present and without including os.py, modules
// which import os fail
Set<String> includePyModules = new HashSet<String>();
for (String key : before.keySet()) {
// $py.class is created if Lib folder is writable
if (key.endsWith(".py") || key.endsWith("$py.class")) {
includePyModules.add(key);
}
}
before.keySet().removeAll(includePyModules);
}
// exec the code, arbitrary imports are processed
interpreter.execfile(script, path);
// determine the 'post import' module state
Map<String, String> after = pigContext != null ? getModuleState() : null;
// add the module files to the context
if (after != null && pigContext != null) {
after.keySet().removeAll(before.keySet());
for (Map.Entry<String, String> entry : after.entrySet()) {
String modulename = entry.getKey();
String modulepath = entry.getValue();
if (modulepath.equals(JVM_JAR)) {
continue;
} else if (modulepath.endsWith(".jar") || modulepath.endsWith(".zip")) {
pigContext.addScriptJar(modulepath);
} else {
pigContext.addScriptFile(modulename, modulepath);
}
}
}
} catch (PyException e) {
if (e.match(Py.SystemExit)) {
PyObject value = e.value;
if (PyException.isExceptionInstance(e.value)) {
value = value.__findattr__("code");
}
if (new PyInteger(0).equals(value)) {
LOG.info("Script invoked sys.exit(0)");
return;
}
}
String message = "Python Error. " + e;
throw new ExecException(message, 1121, e);
}
}Example 41
| Project: PonIC-master File: JythonScriptEngine.java View source code |
/**
* does not call script.close()
* @param script
* @param path
* @param pigContext
* @throws ExecException
*/
static void execfile(InputStream script, String path, PigContext pigContext) throws ExecException {
try {
// determine the current module state
Map<String, String> before = pigContext != null ? getModuleState() : null;
// exec the code, arbitrary imports are processed
interpreter.execfile(script, path);
// determine the 'post import' module state
Map<String, String> after = pigContext != null ? getModuleState() : null;
// add the module files to the context
if (after != null && pigContext != null) {
after.keySet().removeAll(before.keySet());
for (Map.Entry<String, String> entry : after.entrySet()) {
String modulename = entry.getKey();
String modulepath = entry.getValue();
if (modulepath.equals(JVM_JAR)) {
continue;
} else if (modulepath.endsWith(".jar") || modulepath.endsWith(".zip")) {
pigContext.scriptJars.add(modulepath);
} else {
pigContext.addScriptFile(modulename, modulepath);
}
}
}
} catch (PyException e) {
if (e.match(Py.SystemExit)) {
PyObject value = e.value;
if (PyException.isExceptionInstance(e.value)) {
value = value.__findattr__("code");
}
if (new PyInteger(0).equals(value)) {
LOG.info("Script invoked sys.exit(0)");
return;
}
}
String message = "Python Error. " + e;
throw new ExecException(message, 1121, e);
}
}Example 42
| Project: red5-master File: JythonScriptFactory.java View source code |
/** {@inheritDoc} */
@SuppressWarnings({ "rawtypes" })
public Object getScriptedObject(ScriptSource scriptSourceLocator, Class[] scriptInterfaces) throws IOException, ScriptCompilationException {
String basePath = "";
/* TODO: how to do this when running under Tomcat?
ContextHandler handler = WebAppContext.getCurrentWebAppContext();
if (handler != null) {
File root = handler.getBaseResource().getFile();
if (root != null && root.exists()) {
basePath = root.getAbsolutePath() + File.separator + "WEB-INF" + File.separator;
}
}
*/
String strScript = scriptSourceLocator.getScriptAsString();
if (scriptInterfaces.length > 0) {
try {
PySystemState state = new PySystemState();
if (!"".equals(basePath)) {
// Add webapp paths that can contain classes and .jar files to python search path
state.path.insert(0, Py.newString(basePath + "classes"));
File jarRoot = new File(basePath + "lib");
if (jarRoot.exists()) {
for (String filename : jarRoot.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.endsWith(".jar"));
}
})) {
state.path.insert(1, Py.newString(basePath + "lib" + File.separator + filename));
}
}
}
PythonInterpreter interp = new PythonInterpreter(null, state);
interp.exec(strScript);
PyObject getInstance = interp.get("getInstance");
if (!(getInstance instanceof PyFunction)) {
throw new ScriptCompilationException("\"getInstance\" is not a function.");
}
PyObject _this;
if (arguments == null) {
_this = ((PyFunction) getInstance).__call__();
} else {
PyObject[] args = new PyObject[arguments.length];
for (int i = 0; i < arguments.length; i++) {
args[i] = PyJavaType.wrapJavaObject(arguments[i]);
}
_this = ((PyFunction) getInstance).__call__(args);
}
return _this.__tojava__(scriptInterfaces[0]);
} catch (Exception ex) {
logger.error("Error while loading script.", ex);
if (ex instanceof IOException) {
throw (IOException) ex;
} else if (ex instanceof ScriptCompilationException) {
throw (ScriptCompilationException) ex;
}
throw new ScriptCompilationException(ex.getMessage());
}
}
logger.error("No scriptInterfaces provided.");
return null;
}Example 43
| Project: red5-mobileconsole-master File: JythonScriptFactory.java View source code |
/** {@inheritDoc} */
@SuppressWarnings({ "rawtypes" })
public Object getScriptedObject(ScriptSource scriptSourceLocator, Class[] scriptInterfaces) throws IOException, ScriptCompilationException {
String basePath = "";
/* TODO: how to do this when running under Tomcat?
ContextHandler handler = WebAppContext.getCurrentWebAppContext();
if (handler != null) {
File root = handler.getBaseResource().getFile();
if (root != null && root.exists()) {
basePath = root.getAbsolutePath() + File.separator + "WEB-INF" + File.separator;
}
}
*/
String strScript = scriptSourceLocator.getScriptAsString();
if (scriptInterfaces.length > 0) {
try {
PySystemState state = new PySystemState();
if (!"".equals(basePath)) {
// Add webapp paths that can contain classes and .jar files to python search path
state.path.insert(0, Py.newString(basePath + "classes"));
File jarRoot = new File(basePath + "lib");
if (jarRoot.exists()) {
for (String filename : jarRoot.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.endsWith(".jar"));
}
})) {
state.path.insert(1, Py.newString(basePath + "lib" + File.separator + filename));
}
}
}
PythonInterpreter interp = new PythonInterpreter(null, state);
interp.exec(strScript);
PyObject getInstance = interp.get("getInstance");
if (!(getInstance instanceof PyFunction)) {
throw new ScriptCompilationException("\"getInstance\" is not a function.");
}
PyObject _this;
if (arguments == null) {
_this = ((PyFunction) getInstance).__call__();
} else {
PyObject[] args = new PyObject[arguments.length];
for (int i = 0; i < arguments.length; i++) {
args[i] = PyJavaType.wrapJavaObject(arguments[i]);
}
_this = ((PyFunction) getInstance).__call__(args);
}
return _this.__tojava__(scriptInterfaces[0]);
} catch (Exception ex) {
logger.error("Error while loading script.", ex);
if (ex instanceof IOException) {
throw (IOException) ex;
} else if (ex instanceof ScriptCompilationException) {
throw (ScriptCompilationException) ex;
}
throw new ScriptCompilationException(ex.getMessage());
}
}
logger.error("No scriptInterfaces provided.");
return null;
}Example 44
| Project: red5-plugins-master File: JythonScriptFactory.java View source code |
/** {@inheritDoc} */
public Object getScriptedObject(ScriptSource scriptSourceLocator, Class[] scriptInterfaces) throws IOException, ScriptCompilationException {
// TODO: how to do this when running under Tomcat?
ContextHandler handler = WebAppContext.getCurrentWebAppContext();
String basePath = "";
if (handler != null) {
File root = handler.getBaseResource().getFile();
if (root != null && root.exists()) {
basePath = root.getAbsolutePath() + File.separator + "WEB-INF" + File.separator;
}
}
String strScript = scriptSourceLocator.getScriptAsString();
if (scriptInterfaces.length > 0) {
try {
PySystemState state = new PySystemState();
if (!"".equals(basePath)) {
// Add webapp paths that can contain classes and .jar files to python search path
state.path.insert(0, Py.newString(basePath + "classes"));
File jarRoot = new File(basePath + "lib");
if (jarRoot.exists()) {
for (String filename : jarRoot.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.endsWith(".jar"));
}
})) {
state.path.insert(1, Py.newString(basePath + "lib" + File.separator + filename));
}
}
}
PythonInterpreter interp = new PythonInterpreter(null, state);
interp.exec(strScript);
PyObject getInstance = interp.get("getInstance");
if (!(getInstance instanceof PyFunction)) {
throw new ScriptCompilationException("\"getInstance\" is not a function.");
}
PyObject _this;
if (arguments == null) {
_this = ((PyFunction) getInstance).__call__();
} else {
PyObject[] args = new PyObject[arguments.length];
for (int i = 0; i < arguments.length; i++) {
args[i] = PyJavaType.wrapJavaObject(arguments[i]);
}
_this = ((PyFunction) getInstance).__call__(args);
}
return _this.__tojava__(scriptInterfaces[0]);
} catch (Exception ex) {
logger.error("Error while loading script.", ex);
if (ex instanceof IOException) {
throw (IOException) ex;
} else if (ex instanceof ScriptCompilationException) {
throw (ScriptCompilationException) ex;
}
throw new ScriptCompilationException(ex.getMessage());
}
}
logger.error("No scriptInterfaces provided.");
return null;
}Example 45
| Project: sikuli-monkey-master File: AndroidRobot.java View source code |
@Override
public ScreenImage captureScreen(Rectangle rect) {
try {
Debug.history("Take a screenshot from the device...");
// PNG
byte[] bytes = _device.takeSnapshot().convertToBytes(new PyObject[0], null);
BufferedImage screen = ImageIO.read(new ByteArrayInputStream(bytes));
BufferedImage part = screen.getSubimage(rect.x, rect.y, rect.width, rect.height);
return new ScreenImage(rect, part);
} catch (IOException e) {
throw new RuntimeException(e);
}
}Example 46
| Project: SonicFieldRepo-master File: Sython.java View source code |
@SuppressWarnings("nls")
public static void main(String[] args) {
try {
// Checks for deadlocks IFF the property SFConstants.FIND_DEADLOCKS is set.
if (SFConstants.FIND_DEADLOCKS) {
findDeadlocks();
}
try (InputStream sis = Sython.class.getClassLoader().getResourceAsStream("com/nerdscentral/sython/sython.py");
InputStreamReader sir = new InputStreamReader(sis);
BufferedReader bsir = new BufferedReader(sir)) {
{
String lin = null;
while ((lin = bsir.readLine()) != null) {
if (lin.trim().length() > 0) {
init(lin);
}
}
}
}
// ==============
try (PythonInterpreter interp = new PythonInterpreter()) {
try (InputStream pis = Sython.class.getClassLoader().getResourceAsStream("com/nerdscentral/sython/processors.txt");
InputStreamReader pir = new InputStreamReader(pis);
BufferedReader bpir = new BufferedReader(pir)) {
String lin = null;
HashMap<String, SFPL_Operator> processors = new HashMap<>();
interp.exec("import __builtin__");
while ((lin = bpir.readLine()) != null) {
if (lin.trim().length() > 0) {
SFPL_Operator op = (SFPL_Operator) Class.forName(lin).newInstance();
String word = op.Word();
processors.put(word, op);
init(" def " + word + "(self, input, *args):");
init(" return self.run(\"" + word + "\",input,args)");
init(" __builtin__." + word + "=" + word);
}
}
List<SFPL_Operator> vols = new ArrayList<>(404);
vols.addAll(SFP_DBs.getAll());
vols.addAll(SFP_Pcnt.getAll());
for (SFPL_Operator op : vols) {
String word = op.Word();
processors.put(word, op);
init(" def " + word + "(self, input):");
init(" return self.run(\"" + word + "\",input,[])");
init(" __builtin__." + word + "=" + word);
}
init("");
System.out.println("Python about to interpret:");
// System.out.println(initCode);
interp.exec(initCode.toString());
PyObject pyo = interp.get("SonicField");
PyDictionary pid = new PyDictionary();
pid.putAll(processors);
PyObject sf = pyo.__call__(pid);
interp.exec("print \"Installing sf object\"");
interp.set("sf", sf);
interp.exec("__builtin__.sf=sf");
}
interp.exec("import __builtin__");
interp.exec("__builtin__.sf=sf");
interp.exec("import sython.concurrent");
interp.exec("print \"Switching To Python Mode\"");
interp.exec("print \"========================\"");
long t0 = System.currentTimeMillis();
for (String f : args) {
interp.exec(f);
}
interp.exec("sython.concurrent.sf_shutdown()");
interp.exec("print \"========================\"");
interp.exec("print \"------- All DONE -------\"");
long t1 = System.currentTimeMillis();
System.out.println("Total Processing Took: " + ((t1 - t0) / 1000) + " seconds");
}
} catch (Throwable t) {
while (t != null) {
t.printStackTrace();
t = t.getCause();
}
System.exit(1);
}
System.exit(0);
}Example 47
| Project: spork-master File: JythonScriptEngine.java View source code |
/**
* does not call script.close()
* @param script
* @param path
* @param pigContext
* @throws ExecException
*/
static void execfile(InputStream script, String path, PigContext pigContext) throws ExecException {
try {
if (pigContext != null) {
String[] argv;
try {
argv = (String[]) ObjectSerializer.deserialize(pigContext.getProperties().getProperty(PigContext.PIG_CMD_ARGS_REMAINDERS));
} catch (IOException e) {
throw new ExecException("Cannot deserialize command line arguments", e);
}
PySystemState state = Py.getSystemState();
state.argv.clear();
if (argv != null) {
for (String str : argv) {
state.argv.append(new PyString(str));
}
} else {
LOG.warn(PigContext.PIG_CMD_ARGS_REMAINDERS + " is empty. This is not expected unless on testing.");
}
}
// determine the current module state
Map<String, String> before = pigContext != null ? getModuleState() : null;
if (before != null) {
// os.py, stax.py and posixpath.py are part of the initial state
// if Lib directory is present and without including os.py, modules
// which import os fail
Set<String> includePyModules = new HashSet<String>();
for (String key : before.keySet()) {
// $py.class is created if Lib folder is writable
if (key.endsWith(".py") || key.endsWith("$py.class")) {
includePyModules.add(key);
}
}
before.keySet().removeAll(includePyModules);
}
// exec the code, arbitrary imports are processed
interpreter.execfile(script, path);
// determine the 'post import' module state
Map<String, String> after = pigContext != null ? getModuleState() : null;
// add the module files to the context
if (after != null && pigContext != null) {
after.keySet().removeAll(before.keySet());
for (Map.Entry<String, String> entry : after.entrySet()) {
String modulename = entry.getKey();
String modulepath = entry.getValue();
if (modulepath.equals(JVM_JAR)) {
continue;
} else if (modulepath.endsWith(".jar") || modulepath.endsWith(".zip")) {
pigContext.addScriptJar(modulepath);
} else {
pigContext.addScriptFile(modulename, modulepath);
}
}
}
} catch (PyException e) {
if (e.match(Py.SystemExit)) {
PyObject value = e.value;
if (PyException.isExceptionInstance(e.value)) {
value = value.__findattr__("code");
}
if (new PyInteger(0).equals(value)) {
LOG.info("Script invoked sys.exit(0)");
return;
}
}
String message = "Python Error. " + e;
throw new ExecException(message, 1121, e);
}
}Example 48
| Project: spork-streaming-master File: JythonScriptEngine.java View source code |
/**
* does not call script.close()
* @param script
* @param path
* @param pigContext
* @throws ExecException
*/
static void execfile(InputStream script, String path, PigContext pigContext) throws ExecException {
try {
if (pigContext != null) {
String[] argv;
try {
argv = (String[]) ObjectSerializer.deserialize(pigContext.getProperties().getProperty(PigContext.PIG_CMD_ARGS_REMAINDERS));
} catch (IOException e) {
throw new ExecException("Cannot deserialize command line arguments", e);
}
PySystemState state = Py.getSystemState();
state.argv.clear();
if (argv != null) {
for (String str : argv) {
state.argv.append(new PyString(str));
}
} else {
LOG.warn(PigContext.PIG_CMD_ARGS_REMAINDERS + " is empty. This is not expected unless on testing.");
}
}
// determine the current module state
Map<String, String> before = pigContext != null ? getModuleState() : null;
if (before != null) {
// os.py, stax.py and posixpath.py are part of the initial state
// if Lib directory is present and without including os.py, modules
// which import os fail
Set<String> includePyModules = new HashSet<String>();
for (String key : before.keySet()) {
// $py.class is created if Lib folder is writable
if (key.endsWith(".py") || key.endsWith("$py.class")) {
includePyModules.add(key);
}
}
before.keySet().removeAll(includePyModules);
}
// exec the code, arbitrary imports are processed
interpreter.execfile(script, path);
// determine the 'post import' module state
Map<String, String> after = pigContext != null ? getModuleState() : null;
// add the module files to the context
if (after != null && pigContext != null) {
after.keySet().removeAll(before.keySet());
for (Map.Entry<String, String> entry : after.entrySet()) {
String modulename = entry.getKey();
String modulepath = entry.getValue();
if (modulepath.equals(JVM_JAR)) {
continue;
} else if (modulepath.endsWith(".jar") || modulepath.endsWith(".zip")) {
pigContext.scriptJars.add(modulepath);
} else {
pigContext.addScriptFile(modulename, modulepath);
}
}
}
} catch (PyException e) {
if (e.match(Py.SystemExit)) {
PyObject value = e.value;
if (PyException.isExceptionInstance(e.value)) {
value = value.__findattr__("code");
}
if (new PyInteger(0).equals(value)) {
LOG.info("Script invoked sys.exit(0)");
return;
}
}
String message = "Python Error. " + e;
throw new ExecException(message, 1121, e);
}
}Example 49
| Project: TauP-master File: TauP_Console.java View source code |
public String raw_input(PyObject prompt) {
String line = null;
try {
line = reader.readLine(prompt.toString());
} catch (IOException io) {
throw new PyException(Py.IOError);
}
if (line == null) {
// Ctrl-D exit
throw new PyException(Py.EOFError);
}
return line.endsWith("\n") ? line.substring(0, line.length() - 1) : line;
}Example 50
| Project: tuscany-sca-2.x-master File: PythonImplementationProvider.java View source code |
public void start() {
final PySystemState pss = new PySystemState();
pss.path.insert(0, new PyString(implementation.getLocation()));
pss.path.insert(0, new PyString(getClass().getProtectionDomain().getCodeSource().getLocation().getFile()));
python = new PythonInterpreter(null, pss);
python.exec("from invoker import *");
final List<PyObject> px = new ArrayList<PyObject>();
for (final ComponentReference r : component.getReferences()) {
final PythonEval pe = pxFactory.createProxy(PythonEval.class, (RuntimeEndpointReference) r.getEndpointReferences().get(0));
px.add(Py.java2py(new PythonEval() {
@Override
public String eval(final String args) throws Exception {
final String v = pe.eval(args);
return v;
}
}));
}
final List<PyObject> pr = new ArrayList<PyObject>();
for (final ComponentProperty p : component.getProperties()) {
final String v = String.valueOf(p.getValue());
pr.add(Py.java2py(new PythonProperty() {
@Override
public String eval() {
return v;
}
}));
}
PyObject mkc = python.get("mkcomponent");
callable = mkc.__call__(new PyString(component.getName()), new PyString(implementation.getScript()), new PyTuple(px.toArray(new PyObject[0])), new PyTuple(pr.toArray(new PyObject[0])));
}Example 51
| Project: Web-Karma-master File: PythonTransformationHelper.java View source code |
public static String getPyObjectValueAsString(PyObject obj) {
if (obj == null)
return "";
PyType type = obj.getType();
if (type.getName().equals("long"))
return Long.toString(obj.asLong());
else if (type.getName().equals("int"))
return Integer.toString(obj.asInt());
else if (type.getName().equals("bool"))
return obj.asInt() != 0 ? "true" : "false";
return obj.asString();
}Example 52
| Project: android-platform_sdk-master File: MonkeyDevice.java View source code |
@MonkeyRunnerExported(doc = "Sends a touch event at the specified location", args = { "x", "y", "type" }, argDocs = { "x coordinate in pixels", "y coordinate in pixels", "touch event type as returned by TouchPressType()" })
public void touch(PyObject[] args, String[] kws) {
ArgParser ap = JythonUtils.createArgParser(args, kws);
Preconditions.checkNotNull(ap);
int x = ap.getInt(0);
int y = ap.getInt(1);
// Default
String type = MonkeyDevice.DOWN_AND_UP;
try {
String tmpType = ap.getString(1);
if (VALID_DOWN_UP_TYPES.contains(tmpType)) {
type = tmpType;
} else {
// not a valid type
type = MonkeyDevice.DOWN_AND_UP;
}
} catch (PyException e) {
type = MonkeyDevice.DOWN_AND_UP;
}
touch(x, y, TOUCH_NAME_TO_ENUM.get(type));
}Example 53
| Project: callingruby-master File: JythonEngine.java View source code |
/**
* call the named method of the given object.
*/
public Object call(Object object, String method, Object[] args) throws BSFException {
try {
PyObject[] pyargs = Py.EmptyObjects;
if (args != null) {
pyargs = new PyObject[args.length];
for (int i = 0; i < pyargs.length; i++) pyargs[i] = Py.java2py(args[i]);
}
if (object != null) {
PyObject o = Py.java2py(object);
return unwrap(o.invoke(method, pyargs));
}
PyObject m = interp.get(method);
if (m == null)
m = interp.eval(method);
if (m != null) {
return unwrap(m.__call__(pyargs));
}
return null;
} catch (PyException e) {
throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "exception from Jython:\n" + e, e);
}
}Example 54
| Project: elassandra-master File: PythonScriptEngineService.java View source code |
public static Object unwrapValue(Object value) {
if (value == null) {
return null;
} else if (value instanceof PyObject) {
// seems like this is enough, inner PyDictionary will do the conversion for us for example, so expose it directly
return ((PyObject) value).__tojava__(Object.class);
}
return value;
}Example 55
| Project: elasticsearch-server-master File: PythonScriptEngineService.java View source code |
public static Object unwrapValue(Object value) {
if (value == null) {
return null;
} else if (value instanceof PyObject) {
// seems like this is enough, inner PyDictionary will do the conversion for us for example, so expose it directly
return ((PyObject) value).__tojava__(Object.class);
}
return value;
}Example 56
| Project: eoulsan-master File: CheetahInterpreter.java View source code |
/**
* Execute script by Python interpreter and replace variable name by value.
* @return final command line
* @throws EoulsanException if an error throws by interpretation.
*/
public String execute() throws EoulsanException {
try (final PythonInterpreter interpreter = new PythonInterpreter()) {
final PyObject nameSpace = createNameSpace(this.variables);
final String template = this.cheetahScript;
interpreter.set("template", template);
interpreter.set("nameSpace", nameSpace);
final String pythonScript = "from Cheetah.Template import Template\n" + "result = str(Template(template, searchList=[nameSpace]))";
interpreter.exec(pythonScript);
// Retrieve standard output
final PyObject cmd = interpreter.get("result");
return cmd.asString().replace('\n', ' ').trim();
}
}Example 57
| Project: kraken-master File: JythonLogScriptRegistryImpl.java View source code |
@Validate
public void start() {
workspaceScripts = new ConcurrentHashMap<String, ConcurrentMap<String, PyObject>>();
// load scripts
ConfigDatabase db = conf.ensureDatabase("kraken-logdb-jython");
ConfigCollection col = db.ensureCollection("scripts");
ConfigIterator it = col.findAll();
try {
for (LogScriptConfig sc : it.getDocuments(LogScriptConfig.class)) {
try {
PyObject o = eval(sc.name, sc.script);
ConcurrentMap<String, PyObject> scripts = new ConcurrentHashMap<String, PyObject>();
ConcurrentMap<String, PyObject> old = workspaceScripts.putIfAbsent(sc.workspace, scripts);
if (old != null)
scripts = old;
scripts.put(sc.name, o);
} catch (Throwable t) {
logger.error("kraken logdb jython: cannot load script [" + sc.name + "]", t);
}
}
} finally {
it.close();
}
// register all
for (String workspace : workspaceScripts.keySet()) {
ConcurrentMap<String, PyObject> scripts = workspaceScripts.get(workspace);
for (String name : scripts.keySet()) try {
PyObject factory = scripts.get(name);
logScriptRegistry.addScriptFactory(workspace, name, new LogScriptFactoryImpl(factory));
} catch (Throwable t) {
logger.error("kraken logdb jython: cannot register script [" + name + "]", t);
}
}
}Example 58
| Project: logdb-master File: JythonTransformerScriptRegistryImpl.java View source code |
@Validate
public void start() {
// load scripts
ConfigDatabase db = conf.ensureDatabase("araqne-logdb-jython");
ConfigIterator it = db.find(ScriptConfig.class, Predicates.field("type", "transformer"));
try {
for (ScriptConfig sc : it.getDocuments(ScriptConfig.class)) {
try {
PyObject o = eval(sc.getName(), sc.getScript());
scripts.put(sc.getName(), o);
} catch (Throwable t) {
logger.error("araqne logdb jython: cannot load logger script [" + sc.getName() + "]", t);
}
}
} finally {
it.close();
}
}Example 59
| Project: platform_sdk-master File: MonkeyDevice.java View source code |
@MonkeyRunnerExported(doc = "Sends a touch event at the specified location", args = { "x", "y", "type" }, argDocs = { "x coordinate in pixels", "y coordinate in pixels", "touch event type as returned by TouchPressType()" })
public void touch(PyObject[] args, String[] kws) {
ArgParser ap = JythonUtils.createArgParser(args, kws);
Preconditions.checkNotNull(ap);
int x = ap.getInt(0);
int y = ap.getInt(1);
TouchPressType type = TouchPressType.fromIdentifier(ap.getString(2));
if (type == null) {
LOG.warning(String.format("Invalid TouchPressType specified (%s) default used instead", ap.getString(2)));
type = TouchPressType.DOWN_AND_UP;
}
impl.touch(x, y, type);
}Example 60
| Project: ProbCog-master File: genDB.java View source code |
/**
* @param args
*/
public static void main(String[] args) {
try {
boolean writeBasicBLND = false, writeBasicMLN = false, writeBLOGDB = false, writeMLNDB = false, writeProxDB = false;
boolean printDB = false;
int numRuns = 1;
int i = 0;
boolean abort = false;
if (args.length < 3) {
abort = true;
} else {
// read args
int tasks = 0;
for (; i < args.length; i++) {
if (args[i].equals("-m")) {
writeMLNDB = true;
++tasks;
} else if (args[i].equals("-b")) {
writeBLOGDB = true;
++tasks;
} else if (args[i].equals("-p")) {
writeProxDB = true;
++tasks;
} else if (args[i].equals("-s")) {
printDB = true;
++tasks;
} else if (args[i].equals("-bm")) {
writeBasicMLN = true;
++tasks;
} else if (args[i].equals("-bb")) {
writeBasicBLND = true;
++tasks;
} else if (args[i].equals("-multi")) {
numRuns = Integer.parseInt(args[++i]);
} else
break;
}
if (tasks == 0) {
abort = true;
System.err.println("\nError: No tasks were specified. Add at least one option.\n");
}
}
if (abort) {
System.out.println("\ngenDB - a database generator");
System.out.println("\n usage: genDB [options] <Jython generator script> <output base filename> [parameters to pass on to generator]\n" + " -m output MLN database (.db)\n" + " -b output BLOG database (.blogdb)\n" + " -p output Proximity database (.proxdb.xml)\n" + " -s print read database structure to stdout\n" + " -bm output basic MLN model (.basic.mln)\n" + " -bb output basic BLN model declarations (.basic.blnd)\n" + " -multi N create N databases with the given parameters (appending numbers to the base filename)\n\n" + " The Jython script must create a Database object named 'db' in the global scope.\n");
return;
}
String jythonscript = args[i++];
String baseOutfilename = args[i++];
int firstScriptArgIndex = i;
Properties props = new Properties();
//props.put("python.path", "C:\\Progra~2\\jython-2.1\\Lib;datagen");
//props.put("python.path", "/usr/wiss/jain/work/code/SRLDB/bin:/usr/wiss/jain/work/code/SRLDB/python");
String jythonpath = System.getenv("JYTHONPATH");
if (jythonpath == null) {
System.err.println("Warning: JYTHONPATH environment variable not set. If modules such as 'datagen' cannot be imported, either manually set sys.path in your generator scripts to include the appropriate directories or set this variable to include ProbCog's 'python' directory.");
jythonpath = "";
} else
jythonpath += File.pathSeparator;
jythonpath += System.getProperty("java.class.path");
props.put("python.path", jythonpath);
Properties sysprops = System.getProperties();
PythonInterpreter.initialize(sysprops, props, null);
int numDigits = (int) Math.ceil(Math.log10((double) numRuns));
String multiOutfileFormat = String.format("%s%%0%dd", baseOutfilename, numDigits);
for (int run = 1; run <= numRuns; run++) {
if (numRuns > 1)
System.out.printf("gerating database %d/%d...", run, numRuns);
PythonInterpreter jython = new PythonInterpreter();
jython.exec("import sys");
jython.exec("sys.argv = ['" + jythonscript + "']");
for (int j = firstScriptArgIndex; j < args.length; j++) {
jython.exec("sys.argv.append('" + args[j] + "')");
}
jython.execfile(jythonscript);
PyObject dbObj = jython.get("db");
if (dbObj == null) {
throw new Exception("\nGenerator script does not define 'db' object!");
}
Database db = (Database) dbObj.__tojava__(Database.class);
db.check();
if (printDB)
db.printData();
String outfilename;
if (numRuns == 1)
outfilename = baseOutfilename;
else
outfilename = String.format(multiOutfileFormat, run);
if (writeMLNDB) {
File file = new java.io.File(outfilename + ".db");
System.out.println("Writing MLN database to " + file);
db.writeMLNDatabase(new PrintStream(file));
}
if (writeBLOGDB) {
File file = new java.io.File(outfilename + ".blogdb");
System.out.println("Writing BLN database to " + file);
db.writeBLOGDatabase(new PrintStream(file));
}
if (writeProxDB) {
File file = new java.io.File(outfilename + ".proxdb.xml");
System.out.println("Writing Proximity database to " + file);
db.writeProximityDatabase(new PrintStream(file));
}
if (writeBasicMLN) {
File file = new File(outfilename + ".basic.mln");
System.out.println("Writing basic MLN declarations to " + file);
db.writeBasicMLN(new PrintStream(file));
}
if (writeBasicBLND) {
File file = new File(outfilename + ".basic.blnd");
System.out.println("Writing basic BLN declarations to " + file);
db.getDataDictionary().writeBasicBLOGModel(new PrintStream(file));
}
}
System.out.println("done!");
} catch (Exception e) {
e.printStackTrace();
}
}Example 61
| Project: scisoft-core-master File: PythonUtils.java View source code |
/**
* Convert tuples/lists of tuples/lists to Java lists of lists. Also convert complex numbers to Apache Commons
* version and Jython strings to strings
*
* @param obj
* @return converted object
*/
public static Object convertToJava(Object obj) {
if (obj == null || obj instanceof PyNone)
return null;
if (obj instanceof PySequenceList) {
obj = ((PySequenceList) obj).toArray();
}
if (obj instanceof PyArray) {
obj = ((PyArray) obj).getArray();
}
if (obj instanceof List<?>) {
@SuppressWarnings("unchecked") List<Object> jl = (List<Object>) obj;
int l = jl.size();
for (int i = 0; i < l; i++) {
Object lo = jl.get(i);
if (lo instanceof PyObject) {
jl.set(i, convertToJava(lo));
}
}
return obj;
}
if (obj.getClass().isArray()) {
int l = Array.getLength(obj);
for (int i = 0; i < l; i++) {
Object lo = Array.get(obj, i);
if (lo instanceof PyObject) {
Array.set(obj, i, convertToJava(lo));
}
}
return obj;
}
if (obj instanceof BigInteger || !(obj instanceof PyObject))
return obj;
if (obj instanceof PyComplex) {
PyComplex z = (PyComplex) obj;
return new Complex(z.real, z.imag);
} else if (obj instanceof PyString) {
return obj.toString();
}
return ((PyObject) obj).__tojava__(Object.class);
}Example 62
| Project: javasec-master File: RmPyServlet.java View source code |
protected static <T> T createInstance(PythonInterpreter interp, File file, Class<T> type) throws ServletException {
Matcher m = FIND_NAME.matcher(file.getName());
if (!m.find()) {
throw new ServletException("I can't guess the name of the class from " + file.getAbsolutePath());
}
String name = m.group(1);
try {
interp.set("__file__", file.getAbsolutePath());
interp.execfile(file.getAbsolutePath());
PyObject cls = interp.get(name);
if (cls == null) {
throw new ServletException("No callable (class or function) named " + name + " in " + file.getAbsolutePath());
}
PyObject pyServlet = cls.__call__();
Object o = pyServlet.__tojava__(type);
if (o == Py.NoConversion) {
throw new ServletException("The value from " + name + " must extend " + type.getSimpleName());
}
@SuppressWarnings("unchecked") T asT = (T) o;
return asT;
} catch (PyException e) {
throw new ServletException(e);
}
}Example 63
| Project: dawn-workflow-master File: PythonScript.java View source code |
private DataMessageComponent getJythonMessage(final List<DataMessageComponent> cache) throws Exception {
PythonInterpreter interpreter;
if (// (Takes a while)
isNewInterpreter) {
interpreter = JythonInterpreterUtils.getInterpreter();
} else {
interpreter = ActorInterpreterUtils.getInterpreterForRun(this);
}
// We save the names of the abstract data sets passed in
// these are read back and passed on sometimes.
List<String> inputs = new ArrayList<String>(7);
for (DataMessageComponent dataMessageComponent : cache) {
if (dataMessageComponent.getList() == null)
continue;
for (String name : dataMessageComponent.getList().keySet()) {
final Object ob = dataMessageComponent.getList().get(name);
interpreter.set(name, ob);
if (ob instanceof Dataset) {
interpreter.exec(name + " = dnp.Sciwrap(" + name + ")");
if (isPassInputs) {
inputs.add(name);
}
}
}
}
final IResource file = getResource();
if (file.exists())
interpreter.execfile(new FileInputStream(file.getLocation().toOSString()));
final DataMessageComponent ret = new DataMessageComponent();
final Map<String, Serializable> data = new HashMap<String, Serializable>(7);
if (outputs == null)
outputs = Collections.emptyList();
final List<String> out = new ArrayList<String>(outputs.size() + inputs.size());
out.addAll(outputs);
out.addAll(inputs);
for (String name : out) {
PyObject ob = interpreter.get(name);
Dataset ds = (Dataset) ob.__tojava__(Dataset.class);
if (ds instanceof PyProxy)
ds = ds.getView(true);
ds.setName(name);
data.put(name, ds);
}
ret.setList(data);
ret.setMeta(MessageUtils.getMeta(cache));
ret.addScalar(MessageUtils.getScalar(cache));
ret.putScalar("Jython Script", getResource().getName());
return ret;
}Example 64
| Project: pploader-master File: PythonPluginLoader.java View source code |
private Plugin loadPlugin(File file, boolean ignoreSoftDependencies, PluginDataFile data) throws InvalidPluginException /*, InvalidDescriptionException, UnknownDependencyException*/
{
Properties props;
System.out.println("[PPLoader] Loading Plugin " + file.getName());
PythonPlugin result = null;
PluginDescriptionFile description = null;
try {
InputStream stream = data.getStream("plugin.yml");
if (stream == null) {
throw new InvalidPluginException(new Exception("You must include plugin.yml!"));
}
description = new PluginDescriptionFile(stream);
if (stream != null)
stream.close();
} catch (IOException ex) {
throw new InvalidPluginException(ex);
} catch (YAMLException ex) {
throw new InvalidPluginException(ex);
} catch (InvalidDescriptionException ex) {
throw new InvalidPluginException(ex);
}
File dataFolder = new File(file.getParentFile(), description.getName());
if (dataFolder.getAbsolutePath().equals(file.getAbsolutePath())) {
throw new InvalidPluginException(new Exception(String.format("Projected datafolder: '%s' for %s is the same file as the plugin itself (%s)", dataFolder, description.getName(), file)));
}
if (dataFolder.exists() && !dataFolder.isDirectory()) {
throw new InvalidPluginException(new Exception(String.format("Projected datafolder: '%s' for %s (%s) exists and is not a directory", dataFolder, description.getName(), file)));
}
List<String> depend;
try {
depend = description.getDepend();
if (depend == null) {
depend = new ArrayList<>();
}
} catch (ClassCastException ex) {
throw new InvalidPluginException(ex);
}
for (String pluginName : depend) {
if (!isPluginLoaded(pluginName)) {
throw new UnknownDependencyException(pluginName);
}
}
props = PySystemState.getBaseProperties();
props = setDefaultPythonPath(props, file.getAbsolutePath());
PySystemState state = new PySystemState();
state.initialize(System.getProperties(), props, null);
PyList pythonpath = state.path;
PyString filepath = new PyString(file.getAbsolutePath());
pythonpath.append(filepath);
String mainfile = "plugin.py";
InputStream instream = null;
try {
instream = data.getStream(mainfile);
if (instream == null) {
mainfile = "main.py";
instream = data.getStream(mainfile);
}
} catch (IOException e) {
throw new InvalidPluginException(e);
}
if (instream == null) {
throw new InvalidPluginException(new FileNotFoundException("Can not find plugin.py or main.py"));
}
try {
PyDictionary table = new PyDictionary();
PythonInterpreter interp = new PythonInterpreter(table, state);
String[] pre_plugin_scripts = { "preload.py" };
String[] post_plugin_scripts = { "postload.py" };
// Run scripts designed to be run before plugin creation
for (String script : pre_plugin_scripts) {
InputStream metastream = this.getClass().getClassLoader().getResourceAsStream("scripts/" + script);
interp.execfile(metastream);
metastream.close();
}
interp.execfile(instream);
instream.close();
String mainclass = description.getMain();
PyObject pyClass = interp.get(mainclass);
if (pyClass == null)
pyClass = interp.get("Plugin");
if (pyClass == null) {
throw new InvalidPluginException(new Exception("Can not find Mainclass."));
} else
result = (PythonPlugin) pyClass.__call__().__tojava__(PythonPlugin.class);
interp.set("PYPLUGIN", result);
result.interp = interp;
// Run scripts designed to be run after plugin creation
for (String script : post_plugin_scripts) {
InputStream metastream = this.getClass().getClassLoader().getResourceAsStream("scripts/" + script);
interp.execfile(metastream);
metastream.close();
}
result.initialize(this, server, description, dataFolder, file);
result.setDataFile(data);
} catch (Throwable t) {
throw new InvalidPluginException(t);
}
if (!loadedplugins.contains(description.getName()))
loadedplugins.add(description.getName());
return result;
}Example 65
| Project: SikuliX-2014-master File: JythonHelper.java View source code |
public static JythonHelper get() {
if (instance == null) {
instance = new JythonHelper();
instance.log(lvl, "init: starting");
try {
cInterpreter = Class.forName("org.python.util.PythonInterpreter");
} catch (Exception ex) {
String sJython = new File(runTime.SikuliJython).getName();
File fJython = new File(runTime.fSikulixDownloadsGeneric, sJython);
instance.log(lvl, "trying to use setup downloaded Jython:\n%s", fJython.getAbsolutePath());
if (fJython.exists()) {
runTime.addToClasspath(fJython.getAbsolutePath());
} else {
instance.log(-1, "Not possible to get a Jython on to the classpath!");
cInterpreter = null;
}
}
try {
cInterpreter = Class.forName("org.python.util.PythonInterpreter");
mGetSystemState = cInterpreter.getMethod("getSystemState", nc);
mExec = cInterpreter.getMethod("exec", new Class[] { String.class });
mExecfile = cInterpreter.getMethod("execfile", new Class[] { String.class });
Constructor PI_new = cInterpreter.getConstructor(nc);
interpreter = PI_new.newInstance(null);
cPyException = Class.forName("org.python.core.PyException");
cList = Class.forName("org.python.core.PyList");
cPy = Class.forName("org.python.core.Py");
cPyFunction = Class.forName("org.python.core.PyFunction");
cPyMethod = Class.forName("org.python.core.PyMethod");
cPyInstance = Class.forName("org.python.core.PyInstance");
cPyObject = Class.forName("org.python.core.PyObject");
cPyString = Class.forName("org.python.core.PyString");
mLen = cList.getMethod("__len__", nc);
mClear = cList.getMethod("clear", nc);
mGet = cList.getMethod("get", new Class[] { int.class });
mSet = cList.getMethod("set", new Class[] { int.class, Object.class });
mAdd = cList.getMethod("add", new Class[] { Object.class });
mRemove = cList.getMethod("remove", new Class[] { int.class });
} catch (Exception ex) {
cInterpreter = null;
}
instance.log(lvl, "init: success");
}
if (cInterpreter == null) {
instance.runTime.terminate(1, "JythonHelper: no Jython on classpath");
}
runTime.isJythonReady = true;
return instance;
}Example 66
| Project: myrobotlab-master File: Python.java View source code |
@Override
public void run() {
try {
while (isRunning()) {
Message msg = inputQueue.take();
try {
// FIXME - remove all msg_ .. its the old way .. :P
// serious bad bug in it which I think I fixed - the
// msgHandle is really the data coming from a callback
// it can originate from the same calling function such
// as Sphinx.send - but we want the callback to
// call a different method - this means the data needs
// to go to a data structure which is keyed by only the
// sending method, but must call the appropriate method
// in Sphinx
StringBuffer msgHandle = new StringBuffer().append("msg_").append(getSafeReferenceName(msg.sender)).append("_").append(msg.sendingMethod);
// StringBuffer methodSignature ???
PyObject compiledObject = null;
if (msg.data == null || msg.data.length == 0) {
compiledObject = getCompiledMethod(msg.method, String.format("%s()", msg.method), interp);
} else {
StringBuffer methodWithParams = new StringBuffer();
methodWithParams.append(String.format("%s(", msg.method));
for (int i = 0; i < msg.data.length; ++i) {
String paramHandle = String.format("%s_p%d", msgHandle, i);
interp.set(paramHandle.toString(), msg.data[i]);
methodWithParams.append(paramHandle);
if (i < msg.data.length - 1) {
methodWithParams.append(",");
}
}
methodWithParams.append(")");
compiledObject = getCompiledMethod(msg.method, methodWithParams.toString(), interp);
}
/*
* if (compiledObject == null){ // NEVER NULL - object
* cache - builds cache if not there
* log.error(String.format( "%s() NOT FOUND",
* msg.method)); }
*/
// commented out recently - no longer using msg handle
// for
// call-backs :)
// log.info(String.format("setting data %s",
// msgHandle));
// interp.set(msgHandle.toString(), msg);
interp.exec(compiledObject);
} catch (Exception e) {
Logging.logError(e);
python.error(String.format("%s %s", e.getClass().getSimpleName(), e.getMessage()));
}
}
} catch (Exception e) {
if (e instanceof InterruptedException) {
info("shutting down %s", getName());
} else {
Logging.logError(e);
}
}
}Example 67
| Project: ptii-master File: PythonScript.java View source code |
///////////////////////////////////////////////////////////////////
//// private methods ////
/* Create an instance of the Main class defined in the script.
* Add all parameters and ports of this actor as attributes of
* the object, so that they become accessible to the methods
* defined in the script. IllegalActionException is thrown if
* there is any error in creating an instance of the Main class
* defined in the script.
*/
private PyObject _createObject() throws IllegalActionException {
// of the Main class object
if (_class == null) {
// Since _class is null, we could have been cloned.
// Evaluate the script so that we do not use a different
// script of another python actor. (This will set _class).
_evaluateScript();
}
PyObject object = _class.__call__();
if (object == null) {
throw new IllegalActionException(this, "Error in creating an instance of the Main class " + "defined in the script.");
}
// set up access to this actor
// first create an attribute "actor" on the object
// the PyObject class does not allow adding a new attribute to the
// object
object.__setattr__("actor", new PyJavaInstance(this));
// give the object access to attributes and ports of this actor
Iterator attributes = attributeList().iterator();
while (attributes.hasNext()) {
Attribute attribute = (Attribute) attributes.next();
String mangledName = _mangleName(attribute.getName());
if (_debugging) {
_debug("set up reference to attribute \"" + attribute.getName() + "\" as \"" + mangledName + "\"");
}
object.__setattr__(new PyString(mangledName), new PyJavaInstance(attribute));
}
Iterator ports = portList().iterator();
while (ports.hasNext()) {
Port port = (Port) ports.next();
String mangledName = _mangleName(port.getName());
if (_debugging) {
_debug("set up reference to port \"" + port.getName() + "\" as \"" + mangledName + "\"");
}
object.__setattr__(new PyString(mangledName), new PyJavaInstance(port));
}
// populate the method map
for (int i = 0; i < _METHOD_NAMES.length; ++i) {
String methodName = _METHOD_NAMES[i];
PyMethod method = null;
try {
method = (PyMethod) object.__findattr__(methodName);
} catch (ClassCastException ex) {
}
_methodMap.put(methodName, method);
}
return object;
}Example 68
| Project: sod-master File: SodUtil.java View source code |
public static synchronized Object loadJython(String tagName, String[] armNames, Element config) throws Exception {
Class mustImplement = load(tagName.substring("jython".length()), armNames);
if (getElement(config, "inline") != null) {
String jythonCode = getNestedText(getElement(config, "inline"));
return inlineJython(tagName + pythonClassNum++, mustImplement, jythonCode);
} else {
String moduleName = getNestedText(SodUtil.getElement(config, "module"));
String className = getNestedText(SodUtil.getElement(config, "class"));
PythonInterpreter interp = getPythonInterpreter();
interp.exec("from " + moduleName + " import " + className);
PyObject jyWaveformProcessClass = interp.get(className);
PyObject pyWaveformProcessObj = jyWaveformProcessClass.__call__(PyJavaType.wrapJavaObject(config));
return mustImplement.cast(pyWaveformProcessObj.__tojava__(mustImplement));
}
}Example 69
| Project: the-fascinator-master File: ReIndexClient.java View source code |
/**
* Evaluate the requested python script and return the resulting object for
* later user.
*
* @param script The path to the script's location
* @return PyObject An evaluated PyObject, null for errors
*
*/
private PyObject evalScript(String script) {
// Find the script file
File file = new File(script);
if (file == null || !file.exists()) {
log.error("Could not find script: '{}'", script);
return null;
}
// Open the file for reading
FileInputStream inStream = null;
try {
inStream = new FileInputStream(file);
} catch (Exception ex) {
log.error("Error accessing script: '{}'", script, ex);
return null;
}
// Run it though an interpreter
PythonInterpreter python = null;
try {
python = PythonInterpreter.threadLocalStateInterpreter(null);
python.execfile(inStream, "scriptname");
} catch (Exception ex) {
log.error("Error evaluating Python script: '{}'", script, ex);
return null;
}
// Get the result and cleanup
PyObject scriptClass = null;
try {
scriptClass = python.get(SCRIPT_CLASS_NAME);
python.cleanup();
} catch (Exception ex) {
log.error("Error accessing class: '{}'", SCRIPT_CLASS_NAME, ex);
return null;
}
// Instantiate and return the result
return scriptClass.__call__();
}Example 70
| Project: zenoss-zep-master File: TriggerPlugin.java View source code |
protected boolean eventSatisfiesRule(RuleContext ruleContext, String triggerUuid, String ruleSource) {
PyObject result;
try {
// check to see if the cache is full and log an error if so
if (this.cacheIsFull(this.triggerRuleCache)) {
++cacheSizeWarningCounter;
if (cacheSizeWarningCounter % 100 == 0) {
logger.error("Trigger rule cache is full ({}); consider reconfiguring zeneventserver, making it larger", this.getTriggerRuleCacheSize());
cacheSizeWarningCounter = 0;
}
}
// use rule to build and evaluate a Python lambda expression
TriggerRuleCache cacheItem = triggerRuleCache.get(triggerUuid);
PyFunction fn = null;
if (cacheItem == null || !cacheItem.getRuleSource().equals(ruleSource)) {
try {
fn = (PyFunction) this.pythonHelper.getPythonInterpreter().eval("lambda evt, dev, elem, sub_elem, zp_det : " + ruleSource);
} catch (PySyntaxError e) {
String fmt = Py.formatException(e.type, e.value);
logger.warn("syntax error exception raised while compiling rule: {}, {}", ruleSource, fmt);
}
// Cache result of trigger evaluation (even if it failed to compile). This will prevent trying to
// recompile the same invalid rule over and over again.
triggerRuleCache.put(triggerUuid, new TriggerRuleCache(ruleSource, fn));
} else {
fn = cacheItem.getPyFunction();
}
if (fn == null) {
logger.debug("Invalid rule source: {}", ruleSource);
return false;
}
// evaluate the rule function
PyObject[] args = { ruleContext.event, ruleContext.device, ruleContext.element, ruleContext.subElement, ruleContext.zpDetails };
result = fn.__call__(args);
} catch (PySyntaxError pysynerr) {
String fmt = Py.formatException(pysynerr.type, pysynerr.value);
logger.warn("syntax error exception raised while compiling rule: {}, {}", ruleSource, fmt);
result = new PyInteger(0);
} catch (PyException pyexc) {
if (!pyexc.match(Py.AttributeError)) {
String fmt = Py.formatException(pyexc.type, pyexc.value);
logger.warn("exception raised while evaluating rule: {}, {}", ruleSource, fmt);
} else if (logger.isDebugEnabled()) {
String fmt = Py.formatException(pyexc.type, pyexc.value);
logger.debug("AttributeError raised while evaluating rule: {}, {}", ruleSource, fmt);
}
result = new PyInteger(0);
}
// object-as-bool evaluator
return result.__nonzero__();
}Example 71
| Project: whitebox-geospatial-analysis-tools-master File: Scripter.java View source code |
private boolean scanDoc() {
try {
// read each line in the doc
//System.lineSeparator());
String[] lines = editor.getText().split("\r\n");
if (lines.length <= 1) {
lines = editor.getText().split("\n");
}
for (String line : lines) {
line = line.replace("\t", "");
if (!line.isEmpty() && !line.startsWith(language.getCommentMarker())) {
if (line.startsWith("import")) {
// import a class
String className = line.replace("import", "").trim();
if (!listOfImportedClasses.contains(className)) {
importClass(className);
}
} else if (line.contains("import") && line.contains("from")) {
// python class import
String className = line.replace("import", ".").replace("from", "").trim().replace(" ", "");
if (!listOfImportedClasses.contains(className)) {
importClass(className);
}
} else if (line.contains("=") && !line.contains("==") && !line.contains("!=")) {
// variable definition
// first find the name of the variable
String[] s1 = line.split("=");
if (s1.length == 2) {
String[] s2 = s1[0].split(" ");
String variableName = s2[s2.length - 1].trim();
if (!listOfImportedVariables.contains(variableName)) {
// now figure out the class
String className = null;
String variableType = "";
if (language == GROOVY) {
variableType = s1[1].replace(";", "").trim();
if ((variableType.startsWith("\"") && variableType.endsWith("\"")) || (variableType.startsWith("\'") && variableType.endsWith("\'"))) {
// it is a string
className = "groovy.lang.GString";
} else if (whitebox.utilities.StringUtilities.isInteger(variableType)) {
className = "java.lang.Integer";
} else if (whitebox.utilities.StringUtilities.isNumeric(variableType)) {
className = "java.lang.Double";
} else if (whitebox.utilities.StringUtilities.isBoolean(variableType)) {
className = "java.lang.Boolean";
} else if (variableType.startsWith("[") && variableType.endsWith("]") && !variableType.contains(":")) {
className = "java.util.List";
} else if (variableType.startsWith("[") && variableType.endsWith("]") && !variableType.contains(":")) {
className = "java.util.MapWithDefault";
} else if (listOfImportedVariables.contains(variableType)) {
// it is being assigned another variable. Use the other variable's class
className = variableClassMap.get(variableType);
} else if (variableType.contains("(")) {
variableType = s1[1].substring(0, s1[1].indexOf("(")).replace(" new ", "").trim();
// is the type known?String className = null;
for (String str : listOfImportedClasses) {
if (str.endsWith("." + variableType)) {
className = str;
break;
}
}
} else if (className == null) {
className = "java.lang.Object";
}
} else if (language == PYTHON) {
variableType = s1[1].trim();
if ((variableType.startsWith("\"") && variableType.endsWith("\"")) || (variableType.startsWith("\'") && variableType.endsWith("\'"))) {
// it is a string
className = "org.python.core.PyString";
} else if (variableType.startsWith("float(") && variableType.endsWith(")")) {
className = "org.python.core.PyFloat";
} else if (variableType.startsWith("int(") && variableType.endsWith(")")) {
className = "org.python.core.PyInteger";
} else if (variableType.startsWith("long(") && variableType.endsWith(")")) {
className = "org.python.core.PyLong";
} else if (variableType.startsWith("complex(") && variableType.endsWith(")")) {
className = "org.python.core.PyComplex";
} else if (whitebox.utilities.StringUtilities.isInteger(variableType)) {
className = "org.python.core.PyLong";
} else if (whitebox.utilities.StringUtilities.isNumeric(variableType)) {
className = "org.python.core.PyFloat";
} else if (whitebox.utilities.StringUtilities.isBoolean(variableType)) {
className = "org.python.core.PyBoolean";
} else if (variableType.startsWith("[") && variableType.endsWith("]")) {
className = "org.python.core.PyList";
} else if (variableType.startsWith("(") && variableType.endsWith(")")) {
className = "org.python.core.PyTuple";
} else if (variableType.contains("(")) {
variableType = s1[1].substring(0, s1[1].indexOf("(")).replace(" new ", "").trim();
// is the type known?String className = null;
for (String str : listOfImportedClasses) {
if (str.endsWith("." + variableType)) {
className = str;
break;
}
}
} else if (listOfImportedVariables.contains(variableType)) {
// it is being assigned another variable. Use the other variable's class
className = variableClassMap.get(variableType);
} else if (className == null) {
className = "org.python.core.PyObject";
}
} else if (language == JAVASCRIPT) {
variableType = s1[1].replace(";", "").trim();
}
importVariableAs(variableName, className);
variableClassMap.put(variableName, className);
}
}
} else if (line.contains("class")) {
String[] s1 = line.split(" ");
// the class name is the one after the class keyword
String className = "";
for (int i = 0; i < s1.length; i++) {
if (s1[i].trim().toLowerCase().equals("class")) {
String[] s2 = s1[i + 1].split("\\(");
className = s2[0];
break;
}
}
if (!className.isEmpty()) {
if (!listOfImportedClasses.contains(className)) {
listOfImportedClasses.add(className);
provider.addCompletion(new BasicCompletion(provider, className));
}
}
}
}
}
return true;
} catch (Exception e) {
return false;
}
}Example 72
| Project: jspringbot-master File: RobotRunnerFactory.java View source code |
public static RobotPythonRunner createRobotRunner(PyObject robotRunnerClass) { PyObject runnerObject = robotRunnerClass.__call__(); return (RobotPythonRunner) runnerObject.__tojava__(RobotPythonRunner.class); }
Example 73
| Project: atom-nuke-master File: JythonEnvironment.java View source code |
@Override
public <T> T instantiate(Class<T> interfaceType, String referenceName) throws ReferenceInstantiationException {
final PyObject pyClass = pythonInterpreter.get(referenceName);
// Create a new object reference of the Jython class store into PyObject
final PyObject newObj = pyClass.__call__();
// to create the java bytecode
return (T) newObj.__tojava__(interfaceType);
}Example 74
| Project: cocoon-master File: PythonInterpreter.java View source code |
public void exec(PyObject code) {
throw new NoSuchMethodError("This is a mock object");
}Example 75
| Project: jDcHub-master File: ScriptTask.java View source code |
public void setLocalVariable(String name, PyObject value) {
this.localVariables.put(name, value);
}Example 76
| Project: MathExpr-master File: PlotterStart.java View source code |
private static PyDictionary createNamespace(Map<String, PyObject> map) { Map<PyObject, PyObject> t = new HashMap<PyObject, PyObject>(); for (Entry<String, PyObject> e : map.entrySet()) t.put(new PyString(e.getKey()), e.getValue()); return new PyDictionary(t); }
Example 77
| Project: openge-master File: ScriptingManager.java View source code |
private static PyObject getMethod(String path, String module, String method) {
// Ziggy: This could probably be moved to callScript()
// since it's not used elsewhere.
PythonInterpreter python = new PythonInterpreter();
python.cleanup();
python.execfile(path + module + ".py");
return python.get(method);
}Example 78
| Project: development_apps_spareparts-master File: ScriptRunner.java View source code |
/**
* Start an interactive python interpreter using the specified set of local
* variables. Use this to interrupt a running test script with a prompt:
*
* @param locals
*/
public static void console(PyObject locals) {
initPython();
InteractiveConsole python = new InteractiveConsole(locals);
python.interact();
}Example 79
| Project: montysolr-master File: JythonObjectFactory.java View source code |
public Object createObject(Object args[], String keywords[]) {
PyObject convertedArgs[] = new PyObject[args.length];
for (int i = 0; i < args.length; i++) {
convertedArgs[i] = Py.java2py(args[i]);
}
return klass.__call__(convertedArgs, keywords).__tojava__(interfaceType);
}Example 80
| Project: smart-cms-master File: JythonObjectFactory.java View source code |
protected T createObject(Object args[], String keywords[]) {
PyObject convertedArgs[] = new PyObject[args.length];
for (int i = 0; i < args.length; i++) {
convertedArgs[i] = Py.java2py(args[i]);
}
return (T) klass.__call__(convertedArgs, keywords).__tojava__(interfaceType);
}Example 81
| Project: zk-master File: JythonInterpreter.java View source code |
protected Object get(String name) {
//Bug 2208873: Don't use _ip.get(String, Object) since it
//doesn't handle null well
PyObject val = _ip.get(name);
return val != null ? Py.tojava(val, Object.class) : null;
}Example 82
| Project: airavata-master File: StandaloneNotificationSender.java View source code |
@Override
public void workflowStarted(PyObject[] args, String[] keywords) {
List<InputNode> inputs = GraphUtil.getInputNodes(this.workflow.getGraph());
for (InputNode inputNode : inputs) {
inputNode.setState(NodeExecutionState.FINISHED);
}
}Example 83
| Project: rhq-master File: PythonSourceProvider.java View source code |
public PyObject __call__(PyObject args[], String keywords[]) { if (args[0].toString().startsWith(RHQ_PATH_EXTENSION_PREFIX)) { currentPathPrefix = args[0].toString().substring(RHQ_PATH_EXTENSION_PREFIX.length()); return this; } throw Py.ImportError("unable to handle"); }