Commits

Sean Summers committed a99f0fb

working json export

Comments (0)

Files changed (4)

 *.pkc
 *.idx
 *.swp
+*.db4o
 import com.db4o.Db4oEmbedded.newConfiguration
 import com.db4o.Db4oEmbedded.openFile
 import com.db4o.internal.StoredClassImpl
-import collections
 
 def readonlyConfiguration():
     ''' create a read only DB4O configuration object (to feed db()) '''
         pass
     return config
 
-def db4o(db4ofilename, db4oConfig = None):
+def db(db4ofilename, db4oConfig = None):
     ''' return db4o container for a file, optionally with a configuration (readonly, if not provided) '''
     if not db4oConfig: db4oConfig = readonlyConfiguration()
     return com.db4o.Db4oEmbedded.openFile(db4oConfig, db4ofilename)
 
-def db4oClasses(db, blacklist = BLACKLIST):
-    ''' generate StoredClass list for a given db4o container '''
-    classes = (c for c in db.storedClasses())
-    return (c for c in classes if not c.name.startswith(blacklist) if blacklist else classes)
+def dbClasses(db, blacklist = BLACKLIST):
+    ''' generate StoredClass list for a given db4o container, filtering out blacklist '''
+    return (c for c in db.storedClasses() if not c.name.startswith(blacklist))
 
-def db4oClass(db, o):
+def objClass(db, o):
     ''' return StoredClass for a given class name '''
     return o if isinstance(o, com.db4o.internal.StoredClassImpl) else db.storedClass(o)
 
-def db4oClasspath(db, o):
+def objClassFields(db, o):
+    ''' return instance fields for a given StoredClass '''
+    return objClass(db, o).storedFields
+
+def objClasspath(db, o):
     ''' generate full class lineage for a given StoredClass '''
-    c = db4oClass(db, o)
+    c = objClass(db, o)
     while c:
         yield c
         c = c.parentStoredClass
 
-def db4oClassFields(db, o):
-    ''' return instance fields for a given StoredClass '''
-    return dbClass(db, o).storedFields
-
-def db4oObjFields(db, o):
+def objFields(db, o):
     ''' return all fields for a given StoredClass (including parent fields [heritage order]) '''
-    fields = collections.deque()
-    for dbo in db4oClasspath(db, o):
-        f = dbo.storedFields
-        f.reverse()
-        fields.extendleft(f)
+    fields = []
+    [fields.extend(cls.storedFields) for cls in reversed(tuple(objClasspath(db, o)))]
     return tuple(fields)
 
-def db4oAll(db):
+def objByID(db, oid, depth = 2):
+    ''' return an activated object by ID '''
+    obj = db.getByID(oid)
+    db.activate(obj, depth)
+    return obj
+
+def objAll(db):
     ''' return all objects stored in this container '''
     return db.queryByExample(None)
 
-def db4oIDs(db, o = None):
+def objIDs(db, o = None):
     ''' return a list of all object IDs in this container, for a specified class (or all) '''
-    return db4oClass(db, o).IDs
+    return objClass(db, o).IDs
     
 def objCount(db, o = None):
     ''' return a count of objects in this container, for a specified class (or all) '''
-    return len(db4oIDs(db, o) if o else db4oAll(db).IDs)
+    return len(objIDs(db, o) if o else objAll(db).IDs)
 
-def objByID(db, oid):
-    ''' return an object by ID '''
-    obj = db.getByID(oid)
-    db.activate(obj, 2)
-    return obj
-
 __author__ = 'Sean Summers <SeanSummers@gmail.com>'
 
-import collections
+import util
+import java.util.Date
+import json
 
 class Db4oObj(object):
     def __init__(s, o):
         if o.class.name <> 'com.db4o.reflect.generic.GenericObject':
             raise TypeError, 'must be a valid db4o GenericObject'
         s._obj = o
+
     def lineage(s):
         lineage = []
         cls = s._obj.genericClass
         while cls.declaredFields:
             lineage.append(cls)
             cls = getattr(cls, 'superclass')
-        lineage.reverse()
-        return lineage
+        return tuple(reversed(lineage))
+
     def fields(s):
         fields = []
         [fields.extend(cls.declaredFields) for cls in s.lineage()]
         return fields
+
     def data(s):
-        return collections.OrderedDict((field.name, s._obj.get(x)) for x, field in enumerate(s.fields()))
-        
+        return [s._fieldValue(f, s._obj) for f in s.fields()]
 
-def db4oOne(db, o):
-    from com.db4o.reflect.generic import GenericObject
-    from collections import OrderedDict
-    import java.util.Date
-    if not isinstance(o, GenericObject):
-        o = db.getByID(o)
-    oi = db.getObjectInfo(o)
-    oname = o.genericClass.name
-    oc = db4oClass(db, oname)
-    data = OrderedDict()
-    data['db4oInfo'] = OrderedDict([(a,b) for a,b in
-        ('id', oi.ID),
-        ('class', oname),
-        ('identifier', oi.identifier),
-        ('internalID', oi.internalID),
-        ('commitTimestamp', getattr(oi, 'commitTimestamp', None)),
-        ('version', getattr(oi, 'version', None)),
-        ('UUID', oi.UUID) if b])
-    for f in db4oObjFields(db, o):
-        d = oc.storedField(f.name, None).get(o)
-        if d is not None:
-            data[f.name] = d if not isinstance(d, GenericObject) else db4oOne(db, d)
-            if isinstance(data[f.name], java.util.Date):
-                data[f.name] = json8601Date(d)
-    return data
-        
-if __name__ == '__main__':
-    from pprint import pprint
-    from org.json import JSONObject
-    dbfile = './test.db4o'
-    a = db4o(dbfile)
-    b = db4oOne(a, 27562559)
-    #c = JSONObject(b)
-    pprint(dict(b))
-    #print c
+    @staticmethod
+    def _fieldValue(field, o):
+        ''' given a field and object, return its value (recursing as necessary) '''
+        value = field.get(o)
+        if getattr(value, 'class', None) and getattr(value.class, 'name', None) == 'com.db4o.reflect.generic.GenericObject':
+            value = tuple(Db4oObj._fieldValue(f, value) for f in value.genericClass.declaredFields)
+        if field.name == 'ts': value = java.util.Date(value) # to match M3
+        return (field.name, value)
+
+    def toJson(s):
+        data = dict(s.data())
+        if data.has_key('contract'):
+            contract = dict(data['contract'])
+            data.update(contractName = contract['name'], contractCode = contract['value'])
+            del data['contract']
+        return json.dumps(data,default=util.encode_jud)
+
 __author__ = 'Sean Summers <SeanSummers@gmail.com>'
 
 import java.util.Date
-class json8601Date(java.util.Date):
-    import java.text.SimpleDateFormat
-    rfc3339j = java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz")
-    def __init__(s, javaDate):
-       super(java.util.Date,javaDate)
-    def toJSONString(s):
-       return s.rfc3339j.format(s)
+import java.util.GregorianCalendar
+import javax.xml.bind.DatatypeConverter
 
 def encode_jud(o):
-    import java.util.Date
-    from java.text import SimpleDateFormat
-    rfc3339j = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
-    if isinstance(o,java.util.Date):
-        r = rfc3339j.format(o) # java.lang.String.format("%tFT%<tT%<tz",o) #TZ badness
-        return ':'.join((r[:-2],r[-2:]))
+    if isinstance(o, java.util.Date):
+        return toISO8601(o)
     raise TypeError(repr(o) + ' is not JSON serializable')
 
+def toISO8601(aDate):
+    c = java.util.GregorianCalendar.getInstance()
+    c.setTime(aDate)
+    return javax.xml.bind.DatatypeConverter.printDateTime(c)
+
+def fromISO8601(aDateISO8601String):
+    return javax.xml.bind.DatatypeConverter.parseDateTime(aDateISO8601String).getTime()
+
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.