Source

jython-db4o / db4o / pydb4o.py

Full commit
__author__ = 'Sean Summers <SeanSummers@gmail.com>'

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')
        return tuple(reversed(lineage))

    def fields(s):
        fields = []
        [fields.extend(cls.declaredFields) for cls in s.lineage()]
        return fields

    def data(s):
        return [s._fieldValue(f, s._obj) for f in s.fields()]

    @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)