1 3 package org.python.util; 4 5 import java.io.*; 6 import org.python.core.*; 7 8 public class PythonObjectInputStream extends ObjectInputStream { 9 public PythonObjectInputStream(InputStream istr) throws IOException { 10 super(istr); 11 enableResolveObject(true); 12 } 13 14 protected Object resolveObject(Object o) throws IOException { 15 Class cls = o.getClass(); 16 if (cls == PyNone.class) 17 return Py.None; 18 else if (cls == PyEllipsis.class) 19 return Py.Ellipsis; 20 else if (cls == PyNotImplemented.class) 21 return Py.NotImplemented; 22 else if (o instanceof PySingleton) 23 throw new IOException("Unserializing a singleton"); 24 return o; 25 } 26 27 protected Class resolveClass(ObjectStreamClass v) 28 throws IOException, ClassNotFoundException { 29 String clsName = v.getName(); 30 if (clsName.startsWith("org.python.proxies")) { 32 int idx = clsName.lastIndexOf('$'); 33 if (idx > 19) 34 clsName = clsName.substring(19, idx); 35 37 idx = clsName.indexOf('$'); 38 if (idx >= 0) { 39 String mod = clsName.substring(0, idx); 40 clsName = clsName.substring(idx+1); 41 42 PyObject module = importModule(mod); 43 PyObject pycls = module.__getattr__(clsName.intern()); 44 Object cls = pycls.__tojava__(Class .class); 45 46 if (cls != null && cls != Py.NoConversion) 47 return (Class ) cls; 48 } 49 } 50 try { 51 return super.resolveClass(v); 52 } catch (ClassNotFoundException exc) { 53 PyObject m = importModule(clsName); 54 Object cls = m.__tojava__(Class .class); 56 if (cls != null && cls != Py.NoConversion) 58 return (Class ) cls; 59 throw exc; 60 } 61 } 62 63 64 private static PyObject importModule(String name) { 65 PyObject silly_list = new PyTuple(new PyString[] { 66 Py.newString("__doc__"), 67 }); 68 return __builtin__.__import__(name, null, null, silly_list); 69 } 70 } 71 | Popular Tags |