public PyObject __iternext__() { while (true) { PyObject element = nextElement(iterator); if (element != null) { if (!predicateSatisfied) { // the predicate is not satisfied yet (or still satisfied in the case of drop beeing // false), so we need to check it if (predicate.__call__(element).__nonzero__() != drop) { predicateSatisfied = drop; return element; } predicateSatisfied = !drop; } else { if (drop) { return element; } else { // end iteration if predicate is false and drop is false return null; } } } else { // end iteration return null; } } }
public 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); }
public void equip(CreatureObject actor, SWGObject item) { String template = ((item.getAttachment("customServerTemplate") == null) ? item.getTemplate() : (item.getTemplate().split("shared_")[0] + "shared_" + ((String) item.getAttachment("customServerTemplate")) + ".iff")); String serverTemplate = template.replace(".iff", ""); PyObject func = core.scriptService.getMethod( "scripts/" + serverTemplate.split("shared_", 2)[0].replace("shared_", ""), serverTemplate.split("shared_", 2)[1], "equip"); if (func != null) func.__call__(Py.java2py(core), Py.java2py(actor), Py.java2py(item)); // TODO: bio-link (assign it by objectID with setAttachment and then just display the customName // for that objectID). if (!actor.getEquipmentList().contains(item)) { actor.addObjectToEquipList(item); processItemAtrributes(actor, item, true); } }
private void encode_obj(PyList rval, PyObject obj, int indent_level) { /* Encode Python object obj to a JSON term, rval is a PyList */ if (obj == Py.None) { rval.append(new PyString("null")); } else if (obj == Py.True) { rval.append(new PyString("true")); } else if (obj == Py.False) { rval.append(new PyString("false")); } else if (obj instanceof PyString) { rval.append(encode_string(obj)); } else if (obj instanceof PyInteger || obj instanceof PyLong) { rval.append(obj.__str__()); } else if (obj instanceof PyFloat) { rval.append(encode_float(obj)); } else if (obj instanceof PyList || obj instanceof PyTuple) { encode_list(rval, obj, indent_level); } else if (obj instanceof PyDictionary) { encode_dict(rval, (PyDictionary) obj, indent_level); } else { PyObject ident = checkCircularReference(obj); if (defaultfn == Py.None) { throw Py.TypeError(String.format(".80s is not JSON serializable", obj.__repr__())); } PyObject newobj = defaultfn.__call__(obj); encode_obj(rval, newobj, indent_level); if (ident != null) { markers.__delitem__(ident); } } }
@Override public void run() throws ScriptExecutionException { try { m_testRunner.__call__(); } catch (final PyException e) { throw new JythonScriptExecutionException("calling TestRunner", e); } }
/** * Shut down the engine. * * <p>We don't use m_interpreter.cleanup(), which delegates to PySystemState.callExitFunc, as * callExitFunc logs problems to stderr. Instead we duplicate the callExitFunc behaviour raise our * own exceptions. * * @throws EngineException If the engine could not be shut down. */ @Override public void shutdown() throws EngineException { final PyObject exitfunc = m_systemState.__findattr__("exitfunc"); if (exitfunc != null) { try { exitfunc.__call__(); } catch (final PyException e) { throw new JythonScriptExecutionException("calling script exit function", e); } } }
public PyObject __iternext__() { while (currentKey.equals(targetKey)) { currentValue = nextElement(iterator); if (currentValue == null) { return null; } if (keyFunc == null) { currentKey = currentValue; } else { currentKey = keyFunc.__call__(currentValue); } } targetKey = currentKey; return new PyTuple(currentKey, new GroupByIterator()); }
/** {@inheritDoc} */ @Override public WorkerRunnable createWorkerRunnable() throws EngineException { final PyObject pyTestRunner; try { // Script does per-thread initialisation here and // returns a callable object. pyTestRunner = m_testRunnerFactory.__call__(); } catch (final PyException e) { throw new JythonScriptExecutionException("creating per-thread TestRunner object", e); } if (!pyTestRunner.isCallable()) { throw new JythonScriptExecutionException( "The result of '" + TEST_RUNNER_CALLABLE_NAME + "()' is not callable"); } return new JythonWorkerRunnable(pyTestRunner); }
/** * Ensure that if the test runner has a {@code __del__} attribute, it is called when the thread * is shutdown. Normally Jython defers this to the Java garbage collector, so we might have done * something like * * <blockquote> * * <pre> * m_testRunner = null; * Runtime.getRuntime().gc(); * </pre> * * </blockquote> * * instead. However this would have a number of problems: * * <ol> * <li>Some JVM's may chose not to finalise the test runner in response to {@code gc()}. * <li>{@code __del__} would be called by a GC thread. * <li>The standard Jython finalizer wrapping around {@code __del__} logs to {@code stderr}. * </ol> * * <p>Instead, we call any {@code __del__} ourselves. After calling this method, the {@code * PyObject} that underlies this class is made invalid. */ @Override public void shutdown() throws ScriptExecutionException { final PyObject del = m_testRunner.__findattr__("__del__"); if (del != null) { try { del.__call__(); } catch (final PyException e) { throw new JythonScriptExecutionException("deleting TestRunner instance", e); } finally { // To avoid the (pretty small) chance of the test runner being // finalised and __del__ being run twice, we disable it. // Unfortunately, Jython caches the __del__ attribute and makes // it impossible to turn it off at a class level. Instead we do // this: m_testRunner.__setattr__("__class__", m_dieQuietly); } } }
public PyObject __iternext__() { while (true) { PyObject element = nextElement(iterator); if (element != null) { // the boolean value of calling predicate with the element // or if predicate is null/None of the element itself boolean booleanValue = predicate != null ? predicate.__call__(element).__nonzero__() : element.__nonzero__(); if (booleanValue == filterTrue) { // if the boolean value is the same as filterTrue return // the element // for ifilter filterTrue is always true, for // ifilterfalse always false return element; } } else { return null; } } }
public void unequip(CreatureObject actor, SWGObject item) { String template = ((item.getAttachment("customServerTemplate") == null) ? item.getTemplate() : (item.getTemplate().split("shared_")[0] + "shared_" + ((String) item.getAttachment("customServerTemplate")) + ".iff")); String serverTemplate = template.replace(".iff", ""); PyObject func = core.scriptService.getMethod( "scripts/" + serverTemplate.split("shared_", 2)[0].replace("shared_", ""), serverTemplate.split("shared_", 2)[1], "unequip"); if (func != null) func.__call__(Py.java2py(core), Py.java2py(actor), Py.java2py(item)); if (actor.getEquipmentList().contains(item)) { actor.removeObjectFromEquipList(item); processItemAtrributes(actor, item, false); } }
/** * Creates a jython object instance for the script cache. * * @param key the path to the jython script * @return an instantiated jython object * @throws Exception if the jython object failed to be instantiated */ @Override public Object createEntry(Object key) throws Exception { // log.debug("createEntry({})", key); String path = key.toString(); int qmarkPos = path.lastIndexOf("?"); if (qmarkPos != -1) { path = path.substring(0, qmarkPos); } int slashPos = path.indexOf("/"); String portalId = path.substring(0, slashPos); PyObject scriptObject = null; InputStream in = velocityService.getResource(path); if (in == null) { log.debug("Failed to load script: '{}'", path); } else { // add current and default portal directories to python sys.path addSysPaths(portalId, Py.getSystemState()); // setup the python interpreter PythonInterpreter python = PythonInterpreter.threadLocalStateInterpreter(null); // expose services for backward compatibility - deprecated python.set("Services", scriptingServices); // python.setLocals(scriptObject); JythonLogger jythonLogger = new JythonLogger(path); python.setOut(jythonLogger); python.setErr(jythonLogger); python.execfile(in, path); String scriptClassName = StringUtils.capitalize(FilenameUtils.getBaseName(path)) + "Data"; PyObject scriptClass = python.get(scriptClassName); if (scriptClass != null) { scriptObject = scriptClass.__call__(); } else { log.debug("Failed to find class '{}'", scriptClassName); } python.cleanup(); } return scriptObject; }
@SuppressWarnings("nls") public static void main(String[] args) { try { // Launch Thread Watchdog // Checks for deadlocks new Thread( new Runnable() { @Override public void run() { ThreadMXBean bean = ManagementFactory.getThreadMXBean(); while (true) { long[] threadIds = bean.findDeadlockedThreads(); // Returns null if no threads are deadlocked. if (threadIds != null) { System.err.println("DEADLOCK"); System.err.println("========"); ThreadInfo[] infos = bean.getThreadInfo(threadIds); for (ThreadInfo info : infos) { System.err.println("STACK:"); StackTraceElement[] stack = info.getStackTrace(); for (StackTraceElement x : stack) { System.err.println(" " + x); } } System.exit(1); } try { Thread.sleep(1000); } catch (InterruptedException e) { // nop } } } }) .start(); // Create Java/Jython interface // ============================ 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); } } } } // Load operators // ============== 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); }
public PyObject invoke( PyObject arg1, PyObject arg2, PyObject arg3, PyObject arg4, PyObject arg5, PyObject arg6) { return errcheck.__call__(invoker.invoke(arg1, arg2, arg3, arg4, arg5, arg6)); }
public PyObject invoke(PyObject arg1, PyObject arg2, PyObject arg3) { return errcheck.__call__(invoker.invoke(arg1, arg2, arg3)); }
public PyObject invoke(PyObject arg1) { return errcheck.__call__(invoker.invoke(arg1)); }
public PyObject invoke() { return errcheck.__call__(invoker.invoke()); }
public T createObject(Object arg1, Object arg2, Object arg3) { return (T) klass .__call__(Py.java2py(arg1), Py.java2py(arg2), Py.java2py(arg3)) .__tojava__(interfaceType); }
private void write(PyString s) throws IOException { chunks.addLast(s); callback.__call__(s); }
/** * Open file and return a stream. Raise IOError upon failure. This is a port to Java of the * CPython _io.open (Modules/_io/_iomodule.c) following the same logic, but expressed with the * benefits of Java syntax. * * @param args array of arguments from Python call via Jython framework * @param kwds array of keywords from Python call via Jython framework * @return the stream object */ public static PyObject open(PyObject[] args, String[] kwds) { // Get the arguments to variables ArgParser ap = new ArgParser("open", args, kwds, openKwds, 1); PyObject file = ap.getPyObject(0); String m = ap.getString(1, "r"); int buffering = ap.getInt(2, -1); final String encoding = ap.getString(3, null); final String errors = ap.getString(4, null); final String newline = ap.getString(5, null); boolean closefd = Py.py2boolean(ap.getPyObject(6, Py.True)); // Decode the mode string OpenMode mode = new OpenMode(m) { @Override public void validate() { super.validate(); validate(encoding, errors, newline); } }; mode.checkValid(); /* * Create the Raw file stream. Let the constructor deal with the variants and argument * checking. */ PyFileIO raw = new PyFileIO(file, mode, closefd); /* * From the Python documentation for io.open() buffering = 0 to switch buffering off (only * allowed in binary mode), 1 to select line buffering (only usable in text mode), and an * integer > 1 to indicate the size of a fixed-size buffer. * * When no buffering argument is given, the default buffering policy works as follows: * Binary files are buffered in fixed-size chunks; "Interactive" text files (files for which * isatty() returns True) use line buffering. Other text files use the policy described * above for binary files. * * In Java, it seems a stream never is *known* to be interactive, but we ask anyway, and * maybe one day we shall know. */ boolean line_buffering = false; if (buffering == 0) { if (!mode.binary) { throw Py.ValueError("can't have unbuffered text I/O"); } return raw; } else if (buffering == 1) { // The stream is to be read line-by-line. line_buffering = true; // Force default size for actual buffer buffering = -1; } else if (buffering < 0 && raw.isatty()) { // No buffering argument given but stream is inteeractive. line_buffering = true; } if (buffering < 0) { /* * We are still being asked for the default buffer size. CPython establishes the default * buffer size using fstat(fd), but Java appears to give no clue. A useful study of * buffer sizes in NIO is http://www.evanjones.ca/software/java-bytebuffers.html . This * leads us to the fixed choice of _DEFAULT_BUFFER_SIZE (=8KB). */ buffering = _DEFAULT_BUFFER_SIZE; } /* * We now know just what particular class of file we are opening, and therefore what stack * (buffering and text encoding) we should build. */ if (buffering == 0) { // Not buffering, return the raw file object return raw; } else { // We are buffering, so wrap raw into a buffered file PyObject bufferType = null; PyObject io = imp.load("io"); if (mode.updating) { bufferType = io.__getattr__("BufferedRandom"); } else if (mode.writing || mode.appending) { bufferType = io.__getattr__("BufferedWriter"); } else { // = reading bufferType = io.__getattr__("BufferedReader"); } PyInteger pyBuffering = new PyInteger(buffering); PyObject buffer = bufferType.__call__(raw, pyBuffering); if (mode.binary) { // If binary, return the just the buffered file return buffer; } else { // We are opening in text mode, so wrap buffered file in a TextIOWrapper. PyObject textType = io.__getattr__("TextIOWrapper"); PyObject[] textArgs = { buffer, ap.getPyObject(3, Py.None), ap.getPyObject(4, Py.None), ap.getPyObject(5, Py.None), Py.newBoolean(line_buffering) }; PyObject wrapper = textType.__call__(textArgs); wrapper.__setattr__("mode", new PyString(m)); return wrapper; } } }
private PyString encode_string(PyObject obj) { /* Return the JSON representation of a string */ return (PyString) encoder.__call__(obj); }
public T createObject() { return (T) klass.__call__().__tojava__(interfaceType); }