Exemplo n.º 1
0
        remoteIndexer1to2,
        item.normalize(reflect.qual(cls)),
        1,
        2)
    registerUpgrader(
        remoteIndexer2to3,
        item.normalize(reflect.qual(cls)),
        2,
        3)
del cls

_declareLegacyIndexerItem(PyLuceneIndexer, 3)

# Copy attributes.  Rely on pyLuceneIndexer4to5 to reset the index due to
# sorting changes.
registerAttributeCopyingUpgrader(PyLuceneIndexer, 3, 4)

_declareLegacyIndexerItem(PyLuceneIndexer, 4)

def pyLuceneIndexer4to5(old):
    """
    Copy attributes, reset index due because information about deleted
    documents has been lost, and power up for IFulltextIndexer so other code
    can find this item.
    """
    new = old.upgradeVersion(PyLuceneIndexer.typeName, 4, 5,
                             indexCount=old.indexCount,
                             installedOn=old.installedOn,
                             indexDirectory=old.indexDirectory)
    new.reset()
    new.store.powerUp(new, ixmantissa.IFulltextIndexer)
Exemplo n.º 2
0
    delivery = MessageDelivery(composer=old.composer,
                               message=old.message,
                               store=old.store)
    new = old.upgradeVersion(old.typeName,
                             2,
                             3,
                             delivery=delivery,
                             message=old.message,
                             fromAddress=old.fromAddress,
                             toAddress=old.toAddress,
                             tries=old.tries,
                             status=UNSENT)
    return new


registerAttributeCopyingUpgrader(DeliveryToAddress, 1, 2)
registerUpgrader(deliveryToAddress2to3, DeliveryToAddress.typeName, 2, 3)


class FromAddressConfigFragment(LiveElement):
    """
    Fragment which contains some stuff that helps users configure their from
    addresses, such as an L{xmantissa.liveform.LiveForm} for adding new ones,
    and an L{xmantissa.scrolltable.ScrollingFragment} for looking at and
    editing existing ones
    """
    implements(ixmantissa.INavigableFragment)
    fragmentName = 'from-address-config'
    title = 'From Addresses'

    def __init__(self, composePrefs):
Exemplo n.º 3
0
        t2 = store.getItemByID(t.storeID)
        self.assertNotIdentical(t, t2)
        self.assertTrue(isinstance(t2, UpgradedItem))


class UpgradedItem(Item):
    """
    A simple item which is the current version of L{nonUpgradedItem}.
    """
    schemaVersion = 3
    ref = reference()


nonUpgradedItem = declareLegacyItem(UpgradedItem.typeName, 1,
                                    dict(ref=reference()))

nonUpgradedItem2 = declareLegacyItem(UpgradedItem.typeName, 2,
                                     dict(ref=reference()))

registerAttributeCopyingUpgrader(UpgradedItem, 1, 2)


def item2to3(old):
    """
    Upgrade an nonUpgradedItem to UpgradedItem
    """
    return old.upgradeVersion(UpgradedItem.typeName, 2, 3, ref=old.ref)


registerUpgrader(item2to3, UpgradedItem.typeName, 2, 3)
    salt = text(defaultFactory=getSalt)
    expired = boolean(default=False)

    def authenticate(self, employee: IEmployee, password: str) -> bool:
        if employee.active_directory_name:
            from TimeClock.Database.LDAPBackedAuthenticationMethod import LDAPBackedAuthenticationMethod
            return LDAPBackedAuthenticationMethod.fromCacheAuthenticationMethod(employee, self).authenticate(employee, password)
            # try:
            #     valid = AD.authenticate(employee.active_directory_name, password)
            #     if valid:
            #         newpw = str(sha512((password + self.salt).encode('charmap')).hexdigest())
            #         if self.password != newpw:
            #             self.password = newpw
            #     return valid
            # except ldap3.core.exceptions.LDAPException:
            #     return str(sha512((password + self.salt).encode('charmap')).hexdigest()) == self.password
        else:
            return str(sha512((password + self.salt).encode('charmap')).hexdigest()) == self.password

    def setPassword(self, pw):
        newpw = str(sha512((pw + self.salt).encode('charmap')).hexdigest())
        self.password = newpw
        self.expired = False
        return self

registerAttributeCopyingUpgrader(
    CacheAuthenticationMethod,
    1,
    2
)
Exemplo n.º 5
0
                ChoiceParameter(
                    'itemsPerPage',
                    list((c, c, c == self.itemsPerPage) for c in (10, 20, 30)),
                    'Items Per Page'))

    def getSections(self):
        authapp = self.store.findUnique(AuthenticationApplication, default=None)
        if authapp is None:
            return None
        return (authapp,)

    def getTabs(self):
        return (webnav.Tab('General', self.storeID, 1.0, authoritative=True),)


upgrade.registerAttributeCopyingUpgrader(DefaultPreferenceCollection, 1, 2)


class PreferenceCollectionLiveForm(LiveForm):
    """
    L{xmantissa.liveform.LiveForm} subclass which switches
    the docfactory, the jsClass, and overrides the submit
    button renderer.
    """
    jsClass = u'Mantissa.Preferences.PrefCollectionLiveForm'

    def __init__(self, *a, **k):
        super(PreferenceCollectionLiveForm, self).__init__(*a, **k)
        self.docFactory = getLoader('liveform-compact')

    def submitbutton(self, request, tag):
Exemplo n.º 6
0
# -*- test-case-name: axiom.test.test_upgrading.PathUpgrade.testUpgradePath -*-

from axiom.attributes import path

from axiom.item import Item

from axiom.upgrade import registerAttributeCopyingUpgrader

class Path(Item):
    schemaVersion = 2
    typeName = 'test_upgrade_path'
    thePath = path()

registerAttributeCopyingUpgrader(Path, 1, 2)
Exemplo n.º 7
0
# -*- test-case-name: axiom.test.test_upgrading.DuringUpgradeTests.test_overridenInitializerInUpgrader -*-

from axiom.attributes import integer, inmemory
from axiom.item import Item, normalize
from axiom.upgrade import registerAttributeCopyingUpgrader

class Simple(Item):
    # Don't import the old version, otherwise its schema will get loaded.  This
    # is valid in the upgrade tests, but not at other times. -exarkun
    typeName = normalize(
        "axiom.test.upgrade_fixtures.override_init_old.Simple")
    schemaVersion = 2

    dummy = integer()
    verify = inmemory()

    def __init__(self, **stuff):
        """
        Override Item's __init__ to re-retrieve this Item from the store.
        """
        Item.__init__(self, **stuff)
        self.verify = (self, self.store.getItemByID(self.storeID))

registerAttributeCopyingUpgrader(Simple, 1, 2)
Exemplo n.º 8
0
            from twisted.internet import reactor
            _listen = reactor.listenTCP
        return _listen(self.portNumber,
                       self.factory.getFactory(),
                       interface=self.interface.encode('ascii'))


declareLegacyItem(typeName=normalize(qual(TCPPort)),
                  schemaVersion=1,
                  attributes=dict(portNumber=integer(),
                                  factory=reference(),
                                  parent=inmemory(),
                                  _listen=inmemory(),
                                  listeningPort=inmemory()))

registerAttributeCopyingUpgrader(TCPPort, 1, 2)


class SSLPort(PortMixin, Item):
    """
    An Axiom Service Item which will bind a TCP port to a protocol factory when
    it is started.
    """
    schemaVersion = 2

    portNumber = integer(doc="""
    The TCP port number on which to listen.
    """)

    interface = text(doc="""
    The hostname to bind to.
Exemplo n.º 9
0
@implementer(ISubAccount)
class SubAccount(Item):
    schemaVersion = 2
    name = text()
    sub = integer()
    active = boolean(default=True)
    def getEmployees(self) -> [IEmployee]:
        return [i for i in self.powerupsFor(IEmployee) if ISolomonEmployee(i).status == Solomon.ACTIVE]
    def addEmployee(self, employee: IEmployee):
        employee.powerUp(self, ISubAccount)
        self.powerUp(employee, IEmployee)

registerAttributeCopyingUpgrader(
    SubAccount,
    1,
    2
)

@coerce
def newArea(_) -> ISubAccount:
    from TimeClock.Axiom.Store import Store
    return SubAccount(store=Store)


@overload
def findSubAccount(s: int) -> ISubAccount:
    from TimeClock.Axiom.Store import Store
    ret = list(Store.query(SubAccount, SubAccount.sub == s))
    if ret:
        return ret[0]
Exemplo n.º 10
0
        Ask L{Composer} to redirect C{self.message}

        @param fromAddress: the address to send from
        @type fromAddress: L{smtpout.FromAddress}

        @param toAddresses: L{mimeutil.EmailAddress} instances
        @type toAddresses: sequence
        """
        self.composer.redirect(fromAddress, toAddresses, self.message)


class ComposeBenefactor(item.Item):
    endowed = attributes.integer(default=0)
    powerupNames = ["xquotient.compose.Composer"]

registerAttributeCopyingUpgrader(ComposePreferenceCollection, 1, 2)

item.declareLegacyItem(ComposePreferenceCollection.typeName, 2,
                       dict(installedOn=attributes.reference(),
                            preferredSmarthost=attributes.text(),
                            smarthostUsername=attributes.text(),
                            smarthostPassword=attributes.text(),
                            smarthostPort=attributes.integer(),
                            smarthostAddress=attributes.text()))

def composePreferenceCollection2to3(old):
    """
    Create an L{smtpout.FromAddress} out of the appropriate
    L{userbase.LoginMethod} in the store, using L{_getFromAddressFromStore}.
    This probably should happen in the L{Composer} 2->3 upgrader, but we also
    make an L{smtpout.FromAddress} item out the smarthost attributes of C{old}
Exemplo n.º 11
0
        # Instead, items need to act as plugins for something so that there
        # mere existence in the database causes them to show up for
        # configuration.
        sections = []
        for cls in GrabberConfiguration, spam.Filter:
            item = self.store.findUnique(cls, default=None)
            if item is not None:
                sections.append(item)
        if sections:
            return sections
        return None

    def getTabs(self):
        return (webnav.Tab('Mail', self.storeID, 0.0),)

registerAttributeCopyingUpgrader(QuotientPreferenceCollection, 1, 2)

declareLegacyItem(QuotientPreferenceCollection.typeName, 2,
                  dict(installedOn=attributes.reference(),
                       preferredMimeType=attributes.text(),
                       preferredMessageDisplay=attributes.text(),
                       showRead=attributes.boolean(),
                       showMoreDetail=attributes.boolean()))

def quotientPreferenceCollection2To3(old):
    """
    Remove the preference attributes of
    L{xquotient.quotientapp.QuotientPreferenceCollection}, and install
    a L{xquotient.exmess.MessageDisplayPreferenceCollection}, because
    the attributes have either been moved there, or removed entirely
    """
Exemplo n.º 12
0

for cls in [HypeIndexer, XapianIndexer, PyLuceneIndexer]:
    _declareLegacyIndexerItem(cls, 2)

    registerUpgrader(remoteIndexer1to2, item.normalize(reflect.qual(cls)), 1,
                     2)
    registerUpgrader(remoteIndexer2to3, item.normalize(reflect.qual(cls)), 2,
                     3)
del cls

_declareLegacyIndexerItem(PyLuceneIndexer, 3)

# Copy attributes.  Rely on pyLuceneIndexer4to5 to reset the index due to
# sorting changes.
registerAttributeCopyingUpgrader(PyLuceneIndexer, 3, 4)

_declareLegacyIndexerItem(PyLuceneIndexer, 4)


def pyLuceneIndexer4to5(old):
    """
    Copy attributes, reset index due because information about deleted
    documents has been lost, and power up for IFulltextIndexer so other code
    can find this item.
    """
    new = old.upgradeVersion(PyLuceneIndexer.typeName,
                             4,
                             5,
                             indexCount=old.indexCount,
                             installedOn=old.installedOn,
Exemplo n.º 13
0
                    'itemsPerPage',
                    list((c, c, c == self.itemsPerPage) for c in (10, 20, 30)),
                    'Items Per Page'))

    def getSections(self):
        authapp = self.store.findUnique(AuthenticationApplication,
                                        default=None)
        if authapp is None:
            return None
        return (authapp, )

    def getTabs(self):
        return (webnav.Tab('General', self.storeID, 1.0, authoritative=True), )


upgrade.registerAttributeCopyingUpgrader(DefaultPreferenceCollection, 1, 2)


class PreferenceCollectionLiveForm(LiveForm):
    """
    L{xmantissa.liveform.LiveForm} subclass which switches
    the docfactory, the jsClass, and overrides the submit
    button renderer.
    """
    jsClass = u'Mantissa.Preferences.PrefCollectionLiveForm'

    def __init__(self, *a, **k):
        super(PreferenceCollectionLiveForm, self).__init__(*a, **k)
        self.docFactory = getLoader('liveform-compact')

    def submitbutton(self, request, tag):
Exemplo n.º 14
0
    Create the extra state tracking items necessary for efficiently determining
    distinct source addresses.
    """
    newInbox = oldInbox.upgradeVersion(
        'quotient_inbox', 1, 2,
        installedOn=oldInbox.installedOn,
        uiComplexity=oldInbox.uiComplexity)
    return newInbox
registerUpgrader(upgradeInbox1to2, 'quotient_inbox', 1, 2)

declareLegacyItem(Inbox.typeName, 2,
                  dict(installedOn=attributes.reference(),
                       uiComplexity=attributes.integer(),
                       catalog=attributes.reference()))

registerAttributeCopyingUpgrader(Inbox, 2, 3)

declareLegacyItem(Inbox.typeName, 3,
                  dict(installedOn=attributes.reference(),
                       catalog=attributes.reference(),
                       uiComplexity=attributes.integer(),
                       showMoreDetail=attributes.boolean()))

def inbox3to4(old):
    """
    Copy over all attributes except for 'installedOn' and 'catalog', which
    have been deleted.

    To avoid triggering an Axiom bug where installOn will load the Inbox
    instance being upgraded and re-entrantly run its remaining upgraders,
    rely on inbox4to5 to set the 'filter' attribute which was added in this
Exemplo n.º 15
0
        sq.setLimit(5000)
        sq.refineByStatus(TRAINED_STATUS)
        work = iter(list(sq))


        # XXX This really should use in-database state, otherwise a restart in
        # the middle will muck things up.
        def go():
            for msg in work:
                for f in filters:
                    f.train(msg._spam, msg)
                yield None
            self.reclassify()
        return coiterate(go())

registerAttributeCopyingUpgrader(Filter, 1, 2)

item.declareLegacyItem(Filter.typeName, 2,
    dict(installedOn = attributes.reference(),
         usePostiniScore = attributes.boolean(default=False,allowNone=False),
         postiniThreshhold = attributes.ieee754_double(default=0.03)))



def _filter2to3(old):
    """
    add dependencies as attributes, remove installedOn
    """
    filter = old.upgradeVersion(old.typeName, 2, 3)
    s = old.store
    filter.usePostiniScore = old.usePostiniScore
Exemplo n.º 16
0
        # mere existence in the database causes them to show up for
        # configuration.
        sections = []
        for cls in GrabberConfiguration, spam.Filter:
            item = self.store.findUnique(cls, default=None)
            if item is not None:
                sections.append(item)
        if sections:
            return sections
        return None

    def getTabs(self):
        return (webnav.Tab('Mail', self.storeID, 0.0), )


registerAttributeCopyingUpgrader(QuotientPreferenceCollection, 1, 2)

declareLegacyItem(
    QuotientPreferenceCollection.typeName, 2,
    dict(installedOn=attributes.reference(),
         preferredMimeType=attributes.text(),
         preferredMessageDisplay=attributes.text(),
         showRead=attributes.boolean(),
         showMoreDetail=attributes.boolean()))


def quotientPreferenceCollection2To3(old):
    """
    Remove the preference attributes of
    L{xquotient.quotientapp.QuotientPreferenceCollection}, and install
    a L{xquotient.exmess.MessageDisplayPreferenceCollection}, because
Exemplo n.º 17
0
# -*- test-case-name: axiom.test.test_upgrading.PathUpgrade.testUpgradePath -*-

from axiom.attributes import path

from axiom.item import Item

from axiom.upgrade import registerAttributeCopyingUpgrader


class Path(Item):
    schemaVersion = 2
    typeName = 'test_upgrade_path'
    thePath = path()


registerAttributeCopyingUpgrader(Path, 1, 2)
Exemplo n.º 18
0
from TimeClock.ITimeClock.IDatabase.IWorkLocation import IWorkLocation


@implementer(IWorkLocation)
class WorkLocation(Item):
    schemaVersion = 2
    workLocationID = text()
    description = text()
    active = boolean(default=True)
    @coerce
    def getEmployees(self) -> [IEmployee]:
        return [i for i in self.powerupsFor(IEmployee) if ISolomonEmployee(i).status == Solomon.ACTIVE]

registerAttributeCopyingUpgrader(
    WorkLocation,
    1,
    2
)

def findWorkType(i):
    ret = list(Store.Store.query(WorkLocation, WorkLocation.workLocationID == i))
    if ret:
        return ret[0]
    r = Solomon.getWorkLocation(i)
    if r:
        return Store.Store.findOrCreate(WorkLocation, workLocationID=i, description=r['Descr'])

registerAdapter(findWorkType, str, IWorkLocation)
registerAdapter(lambda x: WorkLocation(store=Store.Store), Null, IWorkLocation)
Exemplo n.º 19
0
def deliveryToAddress2to3(old):
    delivery = MessageDelivery(composer=old.composer,
                               message=old.message,
                               store=old.store)
    new = old.upgradeVersion(old.typeName, 2, 3,
                             delivery=delivery,
                             message=old.message,
                             fromAddress=old.fromAddress,
                             toAddress=old.toAddress,
                             tries=old.tries,
                             status=UNSENT)
    return new



registerAttributeCopyingUpgrader(DeliveryToAddress, 1, 2)
registerUpgrader(deliveryToAddress2to3, DeliveryToAddress.typeName, 2, 3)



class FromAddressConfigFragment(LiveElement):
    """
    Fragment which contains some stuff that helps users configure their from
    addresses, such as an L{xmantissa.liveform.LiveForm} for adding new ones,
    and an L{xmantissa.scrolltable.ScrollingFragment} for looking at and
    editing existing ones
    """
    implements(ixmantissa.INavigableFragment)
    fragmentName = 'from-address-config'
    title = 'From Addresses'
Exemplo n.º 20
0
    """
    newInbox = oldInbox.upgradeVersion(
        "quotient_inbox", 1, 2, installedOn=oldInbox.installedOn, uiComplexity=oldInbox.uiComplexity
    )
    return newInbox


registerUpgrader(upgradeInbox1to2, "quotient_inbox", 1, 2)

declareLegacyItem(
    Inbox.typeName,
    2,
    dict(installedOn=attributes.reference(), uiComplexity=attributes.integer(), catalog=attributes.reference()),
)

registerAttributeCopyingUpgrader(Inbox, 2, 3)

declareLegacyItem(
    Inbox.typeName,
    3,
    dict(
        installedOn=attributes.reference(),
        catalog=attributes.reference(),
        uiComplexity=attributes.integer(),
        showMoreDetail=attributes.boolean(),
    ),
)


def inbox3to4(old):
    """
Exemplo n.º 21
0
class UpgradedItem(Item):
    """
    A simple item which is the current version of L{nonUpgradedItem}.
    """
    schemaVersion = 3
    ref = reference()



nonUpgradedItem = declareLegacyItem(
    UpgradedItem.typeName, 1,
    dict(ref=reference()))



nonUpgradedItem2 = declareLegacyItem(
    UpgradedItem.typeName, 2,
    dict(ref=reference()))

registerAttributeCopyingUpgrader(UpgradedItem, 1, 2)


def item2to3(old):
    """
    Upgrade an nonUpgradedItem to UpgradedItem
    """
    return old.upgradeVersion(UpgradedItem.typeName, 2, 3, ref=old.ref)

registerUpgrader(item2to3, UpgradedItem.typeName, 2, 3)
Exemplo n.º 22
0
registerUpgrader(ircbotconfig1to2, IRCBotConfig.typeName, 1, 2)



def ircbotconfig2to3(old):
    return old.upgradeVersion(
        IRCBotConfig.typeName, 2, 3,
        hostname=old.hostname,
        portNumber=old.portNumber,
        nickname=old.nickname,
        channels=old._channels.split(u','),
        ignores=old._ignores.split(u','))

registerUpgrader(ircbotconfig2to3, IRCBotConfig.typeName, 2, 3)
registerAttributeCopyingUpgrader(IRCBotConfig, 3, 4)
registerAttributeCopyingUpgrader(IRCBotConfig, 4, 5)



class IRCBotService(Item):
    implements(IService)

    typeName = 'eridanus_ircbotservice'
    schemaVersion = 1

    powerupInterfaces = [IService]

    name = None

    serviceID = bytes(doc="""
Exemplo n.º 23
0
        """
        factory = ServerFactory()
        def protocol():
            proto = CredReceiver()
            proto.portal = Portal(
                self.loginSystem,
                [self.loginSystem,
                 OneTimePadChecker(self._oneTimePads)])
            return proto
        factory.protocol = protocol
        return factory



registerAttributeCopyingUpgrader(
    AMPConfiguration, 1, 2,
    postCopy=lambda new: new.store.powerUp(new, IOneTimePadGenerator))



class ProtocolUnknown(Exception):
    """
    An attempt was made to establish a connection over an AMP route via the
    L{Connect} command to a protocol name for which no factory could be
    located.
    """



class Connect(Command):
    """
Exemplo n.º 24
0
from axiom.test.historic.stubloader import StubbedTest
from axiom.errors import ItemNotFound
from axiom.item import Item
from axiom.attributes import text
from axiom.upgrade import (
    registerAttributeCopyingUpgrader, upgradeExplicitOid, _hasExplicitOid)


class Dummy(Item):
    typeName = 'axiom_storeid_dummy'
    schemaVersion = 2

    attribute = text(doc='text', allowNone=False)


registerAttributeCopyingUpgrader(Dummy, 1, 2)


class Dummy2(Item):
    typeName = 'axiom_storeid_dummy2'
    schemaVersion = 1

    attribute = text(doc='text', allowNone=False)



class StoreIDTransitionTest(StubbedTest):
    def test_transition(self):
        """
        Test that the items survived the transition to explicit oids.
        """
Exemplo n.º 25
0
            from twisted.internet import reactor
            _listen = reactor.listenTCP
        return _listen(self.portNumber, self.factory.getFactory(),
                       interface=self.interface.encode('ascii'))

declareLegacyItem(
    typeName=normalize(qual(TCPPort)),
    schemaVersion=1,
    attributes=dict(
        portNumber=integer(),
        factory=reference(),
        parent=inmemory(),
        _listen=inmemory(),
        listeningPort=inmemory()))

registerAttributeCopyingUpgrader(TCPPort, 1, 2)



class SSLPort(PortMixin, Item):
    """
    An Axiom Service Item which will bind a TCP port to a protocol factory when
    it is started.
    """
    schemaVersion = 2

    portNumber = integer(doc="""
    The TCP port number on which to listen.
    """)

    interface = text(doc="""
Exemplo n.º 26
0
                                              allowNone=True)

    def createResourceWith(self, crud):
        """
        Create a L{_PublicFrontPage} resource wrapping this object.
        """
        return _PublicFrontPage(self, crud)


item.declareLegacyItem(
    FrontPage.typeName, 1,
    dict(publicViews=attributes.integer(),
         privateViews=attributes.integer(),
         prefixURL=attributes.text(allowNone=False)))

upgrade.registerAttributeCopyingUpgrader(FrontPage, 1, 2)


class PublicAthenaLivePage(_PublicPageMixin, website.MantissaLivePage):
    """
    PublicAthenaLivePage is a publicly viewable Athena-enabled page which slots
    a single fragment into the center of the page.
    """
    docFactory = ThemedDocumentFactory('shell', 'templateResolver')
    unsupportedBrowserLoader = ThemedDocumentFactory('athena-unsupported',
                                                     'templateResolver')

    fragment = None

    def __init__(self,
                 store,
Exemplo n.º 27
0
        def protocol():
            proto = CredReceiver()
            proto.portal = Portal(
                self.loginSystem,
                [self.loginSystem,
                 OneTimePadChecker(self._oneTimePads)])
            return proto

        factory.protocol = protocol
        return factory


registerAttributeCopyingUpgrader(
    AMPConfiguration,
    1,
    2,
    postCopy=lambda new: new.store.powerUp(new, IOneTimePadGenerator))


class ProtocolUnknown(Exception):
    """
    An attempt was made to establish a connection over an AMP route via the
    L{Connect} command to a protocol name for which no factory could be
    located.
    """


class Connect(Command):
    """
    Command to establish a new route to an L{IBoxReceiver} as specified by a
Exemplo n.º 28
0
# -*- test-case-name: axiom.test.test_upgrading.PathUpgrade.test_postCopy -*-

from axiom.attributes import path

from axiom.item import Item

from axiom.upgrade import registerAttributeCopyingUpgrader


class Path(Item):
    """
    Trivial Item class for testing upgrading.
    """
    schemaVersion = 2
    typeName = 'test_upgrade_path'
    thePath = path()


def fixPath(it):
    """
    An example postcopy function, for fixing up an item after its attributes
    have been copied.
    """
    it.thePath = it.thePath.child("foo")


registerAttributeCopyingUpgrader(Path, 1, 2, postCopy=fixPath)
Exemplo n.º 29
0
    def getDescription(self) -> str:
        return self.description

    def getBenefit(self) -> IBenefit:
        ben = Solomon.getBenefitByClass(self.name.upper())
        if ben is not None:
            return IBenefit(ben)

    @staticmethod
    def fromSolomon(entry):
        et = IEntryType(entry['BenClassId'])
        if not et.getDescription():
            et.description = entry['Descr']
            et.id = entry['Id']
        return et


registerAttributeCopyingUpgrader(
    EntryType,
    1,
    2
)


def findEntry(s):
    return Store.Store.findOrCreate(EntryType, name=s.title())


registerAdapter(findEntry, str, IEntryType)
registerAdapter(EntryType.fromSolomon, dict, IEntryType)
Exemplo n.º 30
0
        sq.refineByStatus(TRAINED_STATUS)
        work = iter(list(sq))

        # XXX This really should use in-database state, otherwise a restart in
        # the middle will muck things up.
        def go():
            for msg in work:
                for f in filters:
                    f.train(msg._spam, msg)
                yield None
            self.reclassify()

        return coiterate(go())


registerAttributeCopyingUpgrader(Filter, 1, 2)

item.declareLegacyItem(
    Filter.typeName, 2,
    dict(installedOn=attributes.reference(),
         usePostiniScore=attributes.boolean(default=False, allowNone=False),
         postiniThreshhold=attributes.ieee754_double(default=0.03)))


def _filter2to3(old):
    """
    add dependencies as attributes, remove installedOn
    """
    filter = old.upgradeVersion(old.typeName, 2, 3)
    s = old.store
    filter.usePostiniScore = old.usePostiniScore
Exemplo n.º 31
0
        allowNone=True)

    def createResourceWith(self, crud):
        """
        Create a L{_PublicFrontPage} resource wrapping this object.
        """
        return _PublicFrontPage(self, crud)

item.declareLegacyItem(
    FrontPage.typeName,
    1,
    dict(publicViews = attributes.integer(),
         privateViews = attributes.integer(),
         prefixURL = attributes.text(allowNone=False)))

upgrade.registerAttributeCopyingUpgrader(FrontPage, 1, 2)



class PublicAthenaLivePage(_PublicPageMixin, website.MantissaLivePage):
    """
    PublicAthenaLivePage is a publicly viewable Athena-enabled page which slots
    a single fragment into the center of the page.
    """
    docFactory = ThemedDocumentFactory('shell', 'templateResolver')
    unsupportedBrowserLoader = ThemedDocumentFactory(
        'athena-unsupported', 'templateResolver')

    fragment = None

    def __init__(self, store, fragment, staticContent=None, forUser=None,
Exemplo n.º 32
0
    def duration(self) -> ITimeDelta:
        return self.period.duration()

    def getEmployee(self):
        if self.employee is not None:
            return self.employee
        for e in self.store.query(Employee):
            if self in list(e.powerupsFor(ITimeEntry)):
                self.employee = e
                return


registerAttributeCopyingUpgrader(
    TimeEntry,
    1,
    2,
    TimeEntry.getEmployee
)

registerAttributeCopyingUpgrader(
    TimeEntry,
    2,
    3,
)

registerAttributeCopyingUpgrader(
    TimeEntry,
    3,
    4,
)
Exemplo n.º 33
0
    return newsword


registerUpgrader(sword2to3, "test_app_sword", 2, 3)


####### DOUBLE-LEGACY UPGRADE SPECTACULAR !! ###########

# declare legacy class.

from axiom.item import declareLegacyItem


declareLegacyItem(typeName="test_app_player", schemaVersion=2, attributes=dict(name=text(allowNone=True)))

registerAttributeCopyingUpgrader(Adventurer, 2, 3)

declareLegacyItem(
    typeName="test_app_sword",
    schemaVersion=2,
    attributes=dict(name=text(), damagePerHit=integer(), owner=reference(), activated=inmemory()),
)


def upgradePlayerAndSword(oldplayer):
    newplayer = oldplayer.upgradeVersion("test_app_player", 1, 2)
    newplayer.name = oldplayer.name

    oldsword = oldplayer.sword

    newsword = oldsword.upgradeVersion(
Exemplo n.º 34
0
# -*- test-case-name: axiom.test.test_upgrading.PathUpgrade.test_postCopy -*-

from axiom.attributes import path

from axiom.item import Item

from axiom.upgrade import registerAttributeCopyingUpgrader

class Path(Item):
    """
    Trivial Item class for testing upgrading.
    """
    schemaVersion = 2
    typeName = 'test_upgrade_path'
    thePath = path()

def fixPath(it):
    """
    An example postcopy function, for fixing up an item after its attributes
    have been copied.
    """
    it.thePath = it.thePath.child("foo")

registerAttributeCopyingUpgrader(Path, 1, 2, postCopy=fixPath)