KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > python > util > PythonObjectInputStream


1 // Copyright 2000 Finn Bock
2

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 JavaDoc resolveObject(Object JavaDoc o) throws IOException {
15         Class JavaDoc 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 JavaDoc resolveClass(ObjectStreamClass v)
28                       throws IOException, ClassNotFoundException JavaDoc {
29         String JavaDoc clsName = v.getName();
30         //System.out.println(clsName);
31
if (clsName.startsWith("org.python.proxies")) {
32             int idx = clsName.lastIndexOf('$');
33             if (idx > 19)
34                clsName = clsName.substring(19, idx);
35             //System.out.println("new:" + clsName);
36

37             idx = clsName.indexOf('$');
38             if (idx >= 0) {
39                 String JavaDoc 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 JavaDoc cls = pycls.__tojava__(Class JavaDoc.class);
45
46                 if (cls != null && cls != Py.NoConversion)
47                     return (Class JavaDoc) cls;
48             }
49         }
50         try {
51             return super.resolveClass(v);
52         } catch (ClassNotFoundException JavaDoc exc) {
53             PyObject m = importModule(clsName);
54             //System.out.println("m:" + m);
55
Object JavaDoc cls = m.__tojava__(Class JavaDoc.class);
56             //System.out.println("cls:" + cls);
57
if (cls != null && cls != Py.NoConversion)
58                 return (Class JavaDoc) cls;
59             throw exc;
60         }
61     }
62
63
64     private static PyObject importModule(String JavaDoc 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