@Override protected Class<?> findClass(String name) throws ClassNotFoundException { PySystemState sys = Py.getSystemState(); ClassLoader sysClassLoader = sys.getClassLoader(); if (sysClassLoader != null) { // sys.classLoader overrides this class loader! return sysClassLoader.loadClass(name); } // Search the sys.path for a .class file matching the named class. PyList path = sys.path; for (int i = 0; i < path.__len__(); i++) { byte[] buffer; PyObject entry = replacePathItem(sys, i, path); if (entry instanceof SyspathArchive) { SyspathArchive archive = (SyspathArchive) entry; buffer = getBytesFromArchive(archive, name); } else { if (!(entry instanceof PyUnicode)) { entry = entry.__str__(); } String dir = entry.toString(); buffer = getBytesFromDir(dir, name); } if (buffer != null) { definePackageForClass(name); return defineClass(name, buffer, 0, buffer.length); } } // couldn't find the .class file on sys.path throw new ClassNotFoundException(name); }
@Override protected Enumeration<URL> findResources(String res) throws IOException { List<URL> resources = new ArrayList<URL>(); PySystemState sys = Py.getSystemState(); if (res.charAt(0) == SLASH_CHAR) { res = res.substring(1); } String entryRes = res; if (File.separatorChar != SLASH_CHAR) { res = res.replace(SLASH_CHAR, File.separatorChar); entryRes = entryRes.replace(File.separatorChar, SLASH_CHAR); } PyList path = sys.path; for (int i = 0; i < path.__len__(); i++) { PyObject entry = replacePathItem(sys, i, path); if (entry instanceof SyspathArchive) { SyspathArchive archive = (SyspathArchive) entry; ZipEntry ze = archive.getEntry(entryRes); if (ze != null) { try { resources.add(new URL("jar:file:" + archive.asUriCompatibleString() + "!/" + entryRes)); } catch (MalformedURLException e) { throw new RuntimeException(e); } } continue; } if (!(entry instanceof PyUnicode)) { entry = entry.__str__(); } String dir = sys.getPath(entry.toString()); try { File resource = new File(dir, res); if (!resource.exists()) { continue; } resources.add(resource.toURI().toURL()); } catch (MalformedURLException e) { throw new RuntimeException(e); } } return Collections.enumeration(resources); }
/** * make sure post properties override pre properties * * @throws Exception */ public void testInitialize_PrePostProperties() throws Exception { Properties preProps = createPreProperties(); preProps.setProperty(FIRST_PROP, PRE); preProps.setProperty(SECOND_PROP, PRE); Properties postProps = createPostProperties(); postProps.setProperty(SECOND_PROP, POST); PySystemState.initialize(preProps, postProps); Properties registry = PySystemState.registry; String first = registry.getProperty(FIRST_PROP, ANY); String second = registry.getProperty(SECOND_PROP, ANY); assertEquals(PRE, first); assertEquals(POST, second); }
/** * make sure a property from the user registry overrides the same property from the installed * registry * * @throws Exception */ public void testInitialize_Registry_User() throws Exception { // prepare both registry files String installedContent = FIRST_PROP.concat("=").concat(INSTALLED); appendToInstalledRegistry(installedContent); String userContent = FIRST_PROP.concat("=").concat(USER); addUserRegistry(userContent); // test with empty pre an post properties Properties preProps = createPreProperties(); Properties postProps = createPostProperties(); PySystemState.initialize(preProps, postProps); Properties registry = PySystemState.registry; String first = registry.getProperty(FIRST_PROP, ANY); assertEquals(USER, first); }
/** * make sure a pre property overrides any registry properties with the same name * * @throws Exception */ public void testInitialize_Pre_Registries() throws Exception { // prepare both registry files String contentToAppend = FIRST_PROP.concat("=").concat(INSTALLED); appendToInstalledRegistry(contentToAppend); String userContent = FIRST_PROP.concat("=").concat(USER); addUserRegistry(userContent); // set same property on pre properties Properties preProps = createPreProperties(); preProps.setProperty(FIRST_PROP, PRE); Properties postProps = createPostProperties(); PySystemState.initialize(preProps, postProps); Properties registry = PySystemState.registry; String first = registry.getProperty(FIRST_PROP, ANY); assertEquals(PRE, first); }
static PyObject replacePathItem(PySystemState sys, int idx, PyList paths) { PyObject path = paths.__getitem__(idx); if (path instanceof SyspathArchive) { // already an archive return path; } try { // this has the side affect of adding the jar to the PackageManager during the // initialization of the SyspathArchive path = new SyspathArchive(sys.getPath(path.toString())); } catch (Exception e) { return path; } paths.__setitem__(idx, path); return path; }
/** <i>Internal use only. Do not call this method explicit.</i> */ public static void classDictInit(PyObject dict) { dict.invoke("clear"); dict.__setitem__("__name__", new PyString("exceptions")); dict.__setitem__("__doc__", new PyString(__doc__)); ThreadState ts = Py.getThreadState(); if (ts.getSystemState() == null) { // TODO: is this check still useful?? ts.setSystemState(Py.defaultSystemState); } // Push frame PyFrame frame = new PyFrame(null, new PyStringMap()); frame.f_back = ts.frame; if (frame.f_builtins == null) { if (frame.f_back != null) { frame.f_builtins = frame.f_back.f_builtins; } else { frame.f_builtins = PySystemState.getDefaultBuiltins(); } } ts.frame = frame; dict.__setitem__("BaseException", PyBaseException.TYPE); buildClass(dict, "KeyboardInterrupt", "BaseException", "Program interrupted by user."); buildClass( dict, "SystemExit", "BaseException", SystemExit(), "Request to exit from the interpreter."); buildClass( dict, "Exception", "BaseException", "Common base class for all non-exit exceptions."); buildClass( dict, "StandardError", "Exception", "Base class for all standard Python exceptions that do not represent\n" + "interpreter exiting."); buildClass(dict, "SyntaxError", "StandardError", SyntaxError(), "Invalid syntax."); buildClass(dict, "IndentationError", "SyntaxError", "Improper indentation."); buildClass(dict, "TabError", "IndentationError", "Improper mixture of spaces and tabs."); buildClass( dict, "EnvironmentError", "StandardError", EnvironmentError(), "Base class for I/O related errors."); buildClass(dict, "IOError", "EnvironmentError", "I/O operation failed."); buildClass(dict, "OSError", "EnvironmentError", "OS system call failed."); buildClass(dict, "RuntimeError", "StandardError", "Unspecified run-time error."); buildClass( dict, "NotImplementedError", "RuntimeError", "Method or function hasn't been implemented yet."); buildClass( dict, "SystemError", "StandardError", "Internal error in the Python interpreter.\n\n" + "Please report this to the Python maintainer, " + "along with the traceback,\n" + "the Python version, and the hardware/OS " + "platform and version."); buildClass( dict, "ReferenceError", "StandardError", "Weak ref proxy used after referent went away."); buildClass(dict, "EOFError", "StandardError", "Read beyond end of file."); buildClass( dict, "ImportError", "StandardError", "Import can't find module, or can't find name in module."); buildClass(dict, "TypeError", "StandardError", "Inappropriate argument type."); buildClass( dict, "ValueError", "StandardError", "Inappropriate argument value (of correct type)."); buildClass(dict, "UnicodeError", "ValueError", "Unicode related error."); buildClass( dict, "UnicodeEncodeError", "UnicodeError", UnicodeEncodeError(), "Unicode encoding error."); buildClass( dict, "UnicodeDecodeError", "UnicodeError", UnicodeDecodeError(), "Unicode decoding error."); buildClass( dict, "UnicodeTranslateError", "UnicodeError", UnicodeTranslateError(), "Unicode translation error."); buildClass(dict, "AssertionError", "StandardError", "Assertion failed."); buildClass(dict, "ArithmeticError", "StandardError", "Base class for arithmetic errors."); buildClass(dict, "OverflowError", "ArithmeticError", "Result too large to be represented."); buildClass(dict, "FloatingPointError", "ArithmeticError", "Floating point operation failed."); buildClass( dict, "ZeroDivisionError", "ArithmeticError", "Second argument to a division or modulo operation " + "was zero."); buildClass(dict, "LookupError", "StandardError", "Base class for lookup errors."); buildClass(dict, "IndexError", "LookupError", "Sequence index out of range."); buildClass(dict, "KeyError", "LookupError", KeyError(), "Mapping key not found."); buildClass(dict, "AttributeError", "StandardError", "Attribute not found."); buildClass(dict, "NameError", "StandardError", "Name not found globally."); buildClass( dict, "UnboundLocalError", "NameError", "Local name referenced but not bound to a value."); buildClass(dict, "MemoryError", "StandardError", "Out of memory."); buildClass(dict, "BufferError", "StandardError", "Buffer error."); buildClass(dict, "StopIteration", "Exception", "Signal the end from iterator.next()."); buildClass(dict, "GeneratorExit", "BaseException", "Request that a generator exit."); buildClass(dict, "Warning", "Exception", "Base class for warning categories."); buildClass(dict, "UserWarning", "Warning", "Base class for warnings generated by user code."); buildClass( dict, "DeprecationWarning", "Warning", "Base class for warnings about deprecated features."); buildClass( dict, "PendingDeprecationWarning", "Warning", "Base class for warnings about features which will be deprecated\n" + "in the future."); buildClass(dict, "SyntaxWarning", "Warning", "Base class for warnings about dubious syntax."); buildClass( dict, "RuntimeWarning", "Warning", "Base class for warnings about dubious runtime behavior."); buildClass( dict, "FutureWarning", "Warning", "Base class for warnings about constructs that will change semantically\n" + "in the future."); buildClass( dict, "ImportWarning", "Warning", "Base class for warnings about probable mistakes in module imports"); buildClass( dict, "UnicodeWarning", "Warning", "Base class for warnings about Unicode related problems, mostly\n" + "related to conversion problems."); buildClass( dict, "BytesWarning", "Warning", "Base class for warnings about bytes and buffer related problems, mostly\n" + "related to conversion from str or comparing to str."); // Initialize ZipImportError here, where it's safe to; it's // needed immediately zipimport.initClassExceptions(dict); ts.frame = ts.frame.f_back; }
public void setErr(PyObject outStream) { systemState.stderr = outStream; }
/** * Set the Python object to use for the standard output stream * * @param outStream Python file-like object to use as output stream */ public void setOut(PyObject outStream) { systemState.stdout = outStream; }
/** * Initializes the jython runtime. This should only be called once, and should be called before * any other python objects are created (including a PythonInterpreter). * * @param preProperties A set of properties. Typically System.getProperties() is used. * @param postProperties An other set of properties. Values like python.home, python.path and all * other values from the registry files can be added to this property set. PostProperties will * override system properties and registry properties. * @param argv Command line argument. These values will assigned to sys.argv. */ public static void initialize( Properties preProperties, Properties postProperties, String[] argv) { PySystemState.initialize(preProperties, postProperties, argv); }
public void cleanup() { systemState.callExitFunc(); }