コード例 #1
0
    def test_annotation_basic_standard_lifecycle(self):
        # life cycle for a standard item.
        annotations = IAnnotations(self.portal)
        dummy = IDummy(self.portal)
        self.assertIsNone(dummy.field1)
        self.assertIsNone(dummy.field2)

        annotations = IAnnotations(self.portal)
        self.assertNotIn('repodono.storage.tests.test_annotation.Dummy',
                         annotations.keys())

        # assign some values
        dummy.field1 = u'Test'

        # Now the annotation will be in assigned.
        value = annotations['repodono.storage.tests.test_annotation.Dummy']
        self.assertTrue(isinstance(value, PersistentMapping))
        self.assertEqual(value, {'field1': u'Test'})

        # assign more values.
        dummy.field2 = 1
        dummy.field3 = 1

        # only fields defined in the interface are persisted.
        self.assertEqual(value, {'field1': u'Test', 'field2': 1})

        old = dummy.uninstall()
        self.assertNotIn('repodono.storage.tests.test_annotation.Dummy',
                         annotations.keys())
        self.assertFalse(isinstance(old, PersistentMapping))
        self.assertEqual(old, {'field1': u'Test', 'field2': 1})
コード例 #2
0
    def test_annotation_basic_standard_lifecycle(self):
        # life cycle for a standard item.
        annotations = IAnnotations(self.portal)
        dummy = IDummy(self.portal)
        self.assertIsNone(dummy.field1)
        self.assertIsNone(dummy.field2)

        annotations = IAnnotations(self.portal)
        self.assertNotIn("repodono.storage.tests.test_annotation.Dummy", annotations.keys())

        # assign some values
        dummy.field1 = u"Test"

        # Now the annotation will be in assigned.
        value = annotations["repodono.storage.tests.test_annotation.Dummy"]
        self.assertTrue(isinstance(value, PersistentMapping))
        self.assertEqual(value, {"field1": u"Test"})

        # assign more values.
        dummy.field2 = 1
        dummy.field3 = 1

        # only fields defined in the interface are persisted.
        self.assertEqual(value, {"field1": u"Test", "field2": 1})

        old = dummy.uninstall()
        self.assertNotIn("repodono.storage.tests.test_annotation.Dummy", annotations.keys())
        self.assertFalse(isinstance(old, PersistentMapping))
        self.assertEqual(old, {"field1": u"Test", "field2": 1})
コード例 #3
0
    def test_annotation_schema_standard_lifecycle(self):
        dummy = IDummy2(self.portal)

        self.assertIsNone(dummy.field1)
        self.assertIsNone(dummy.field2)
        self.assertIsNone(dummy.field3)

        # Failed assignments will not trigger addition of mapping.
        annotations = IAnnotations(self.portal)
        self.assertNotIn('repodono.storage.tests.test_annotation.Dummy2',
                         annotations.keys())

        # assign some values
        dummy.field1 = u'Test'
        dummy.field2 = u'Value'
        dummy.field3 = 1

        annotations = IAnnotations(self.portal)
        value = annotations['repodono.storage.tests.test_annotation.Dummy2']
        self.assertEqual(value, {
            'field1': u'Test',
            'field2': u'Value',
            'field3': 1
        })

        dummy.uninstall()
        self.assertNotIn('repodono.storage.tests.test_annotation.Dummy2',
                         annotations.keys())
コード例 #4
0
ファイル: vote.py プロジェクト: adam139/emc.kb
 def __init__(self, context):
     self.context = context
     
     annotations = IAnnotations(context)
     if APPROVED_KEY not in annotations.keys():
         annotations[APPROVED_KEY] = PersistentList()        
     #投赞成票的用户id 队列
     self.approved = annotations[APPROVED_KEY]
     if DISAPPROVED_KEY not in annotations.keys():
         annotations[DISAPPROVED_KEY] = PersistentList()        
     #投反对票的用户id 队列        
     self.disapproved = annotations[DISAPPROVED_KEY]        
コード例 #5
0
    def test_annotation_not_field_no_mapping(self):
        # Assignment of unrelated fields will not trigger addition of
        # mapping
        dummy = IDummy3(self.portal)
        dummy.not_schema = u"Some value"
        # Failed assignments will not trigger addition of mapping.
        annotations = IAnnotations(self.portal)
        self.assertNotIn("repodono.storage.tests.test_annotation.Dummy2", annotations.keys())

        # Likewise with a method defined in schema interface.
        dummy.foo = u"Some value"
        # Failed assignments will not trigger addition of mapping.
        annotations = IAnnotations(self.portal)
        self.assertNotIn("repodono.storage.tests.test_annotation.Dummy2", annotations.keys())
コード例 #6
0
 def ztest_copy_tiles(self):
     view = tile_views.MetaTileManager(self.portal, self.request)
     self.request.form.update({'metaId': self.slot_id})
     annotations = IAnnotations(self.portal)
     self.assertEqual(
         len([
             k for k in annotations.keys()
             if k.startswith(TILE_ANNOTATIONS_KEY_PREFIX)
         ]), 3)
     view.copy_meta()
     self.assertEqual(
         len([
             k for k in annotations.keys()
             if k.startswith(TILE_ANNOTATIONS_KEY_PREFIX)
         ]), 6)
コード例 #7
0
ファイル: to0002.py プロジェクト: CMcStone/ftw.blog
def upgrade_to_v2(context):
    """Updates profile
    """
    ppcas = 'plone.portlets.contextassignments'
    catalog = getToolByName(context, 'portal_catalog')
    count = 0
    for brain in catalog(portal_type=['BlogEntry', 'BlogCategory', 'Blog']):
        obj = brain.getObject()
        annotations = IAnnotations(obj)
        if ppcas in annotations.keys():
            if 'blog.portlets' in annotations[ppcas]:
                count += 1
                if len(annotations[ppcas]) == 1:
                    del annotations[ppcas]
                else:
                    del annotations[ppcas]['blog.portlets']

    logger.info("%s %s annotations removed" % (str(count), ppcas))
    loadMigrationProfile(context, 'profile-ftw.blog.upgrades:to_v2')

    # remove blog_settings actions
    portal_actions = getToolByName(context, 'portal_actions')

    category = portal_actions.get('object_buttons', None)
    action_id = 'blog_settings'
    if category and action_id in category:
        del category[action_id]
コード例 #8
0
    def get_gismap(self):
        """Given an object, it will return the interactive map+embed type
        assigned.

        It returns a mapping of
        <gismap uid A>:
            [gismap, embed_type],
        <gismap uid B>:
            [gismap, embed_type],
        """
        annot = IAnnotations(self.context).get(KEY, {})

        uids_cat = getToolByName(self.context, 'uid_catalog')
        info = {}
        for uid in annot.keys():
            brains = uids_cat.searchResults(UID=uid)
            if not brains:
                msg = "Couldn't find interactive map with UID %s" % uid
                logger.warning(msg)
                continue
            gismap = brains[0].getObject()
            if gismap is None:
                msg = "Couldn't find object for brain with UID %s" % uid
                logger.warning(msg)
                continue

            info[uid] = (gismap, annot.get(uid, None))

        return info
コード例 #9
0
ファイル: history.py プロジェクト: 4teamwork/opengever.core
class HistoryStorage(object):

    key = 'disposition_history'

    def __init__(self, context):
        self.context = context
        self._annotations = IAnnotations(self.context)
        if self.key not in self._annotations.keys():
            self._annotations[self.key] = PersistentList()

    @property
    def _storage(self):
        return self._annotations[self.key]

    def add(self, transition, actor_id, dossiers):
        """Adds a new history entry to the storage.
        transition: string
        actor_id: user_id as string
        dossiers: a list of dossier representations.
        """

        dossier_list = PersistentList(
            [dossier.get_storage_representation() for dossier in dossiers])
        self._storage.append(
            PersistentDict({'transition': transition,
                            'actor_id': actor_id,
                            'date': datetime.now(),
                            'dossiers': dossier_list}))

    def get_history(self):
        entries = [DispositionHistory.get(mapping)
                   for mapping in self._storage]
        entries.reverse()
        return entries
コード例 #10
0
ファイル: subscribers.py プロジェクト: plone/plone.app.blocks
def onLayoutEdited(obj, event):
    """
    need to get the layout because you need to know what are
    acceptible storage values
    """
    lookup = ILayoutAware(obj)
    layout = lookup.content_layout()

    if not layout:
        return

    tree = fromstring(layout)
    tile_keys = []
    for el in utils.bodyTileXPath(tree):
        tile_url = el.attrib.get('data-tile', '')
        if 'plone.app.standardtiles.field' in tile_url:
            continue
        tile_keys.append(
            ANNOTATIONS_KEY_PREFIX +
            '.' +
            tile_url.split('?')[0].split('/')[-1]
        )

    annotations = IAnnotations(obj)
    for key in list(annotations.keys()):
        if key.startswith(ANNOTATIONS_KEY_PREFIX) and key not in tile_keys:
            del annotations[key]
コード例 #11
0
ファイル: misc.py プロジェクト: eea/eea.climateadapt.plone
    def results(self):
        portal = api.portal.get()
        annot = IAnnotations(portal)['broken_links_data']
        latest_dates = sorted(annot.keys())[-5:]
        res = {}
        broken_links = []

        for date in latest_dates:
            for info in annot[date]:
                info = info.copy()
                try:
                    obj = self.context.restrictedTraverse(info['object_url'])
                except:
                    continue

                state = get_state(obj)
                if state not in ['private', 'archived']:
                    info['date'] = date.Date() if isinstance(
                        date, DateTime) else date
                    if (isinstance(date, str) and date == 'pre_nov7_data'):
                        continue

                    broken_links.append(info)

        for link in broken_links:
            res[link['url']] = link

        return res
コード例 #12
0
ファイル: indexing.py プロジェクト: CGTIC/Plone_SP
def LayoutSearchableText(obj):
    text = [obj.id]
    try:
        text.append(obj.text.output)
    except AttributeError:
        pass
    try:
        text.append(safe_unicode(obj.title))
    except AttributeError:
        pass
    try:
        text.append(safe_unicode(obj.description))
    except AttributeError:
        pass

    behavior_data = ILayoutAware(obj)
    # get data from tile data
    annotations = IAnnotations(obj)
    for key in annotations.keys():
        if key.startswith(ANNOTATIONS_KEY_PREFIX):
            data = annotations[key]
            for field_name in ('title', 'label', 'content'):
                val = data.get(field_name)
                if isinstance(val, basestring):
                    text.append(val)
    if not behavior_data.contentLayout and behavior_data.content:
        dom = fromstring(behavior_data.content)
        for el in dom.cssselect('.mosaic-text-tile .mosaic-tile-content'):
            text.append(tostring(el))

    return concat(*text)
コード例 #13
0
ファイル: setuphandlers.py プロジェクト: PMR2/pmr2.app
def purge_unassigned_notes(context):
    # this indiscriminately purge all notes not found within an file's
    # specified exposure file type.
    # XXX implement an alternate option that will retain any specified
    # notes
    # XXX don't make this method available in the upgrade step just yet.
    from zope.annotation.interfaces import IAnnotations

    prefix = 'pmr2.annotation.notes-'
    catalog = getToolByName(context, 'portal_catalog')
    files = catalog(portal_type='ExposureFile')
    for b in files:
        file = b.getObject()
        ftpath = file.file_type
        if not ftpath:
            continue

        cftviews = filetypes[ftpath]  # file type views for current file

        # remove unreferenced annotations
        # XXX this assumes users don't manually assign views after
        # specifying file types.
        annotations = IAnnotations(file)
        for k in annotations.keys():
            if not k.startswith(prefix):
                continue
            viewname = k[len(prefix):]
            if not viewname in cftviews:
                del annotations[k]
コード例 #14
0
    def test_annotation_not_field_no_mapping(self):
        # Assignment of unrelated fields will not trigger addition of
        # mapping
        dummy = IDummy3(self.portal)
        dummy.not_schema = u'Some value'
        # Failed assignments will not trigger addition of mapping.
        annotations = IAnnotations(self.portal)
        self.assertNotIn('repodono.storage.tests.test_annotation.Dummy2',
                         annotations.keys())

        # Likewise with a method defined in schema interface.
        dummy.foo = u'Some value'
        # Failed assignments will not trigger addition of mapping.
        annotations = IAnnotations(self.portal)
        self.assertNotIn('repodono.storage.tests.test_annotation.Dummy2',
                         annotations.keys())
コード例 #15
0
 def get_number(self, obj):
     ann = IAnnotations(obj)
     if SEQUENCE_NUMBER_ANNOTATION_KEY not in ann.keys():
         generator = getAdapter(obj, ISequenceNumberGenerator)
         value = generator.generate()
         ann[SEQUENCE_NUMBER_ANNOTATION_KEY] = value
     return ann.get(SEQUENCE_NUMBER_ANNOTATION_KEY)
コード例 #16
0
ファイル: follow.py プロジェクト: adam139/emc.kb
 def __init__(self, context):
     self.context = context
     
     annotations = IAnnotations(context)
     if FOLLOWED_KEY not in annotations.keys():
         annotations[FOLLOWED_KEY] = PersistentList()          
     self.followed = annotations[FOLLOWED_KEY]
コード例 #17
0
ファイル: misc.py プロジェクト: eea/eea.climateadapt.plone
def compute_broken_links(site):
    """ Script that will get called by cron once per day
    """

    results = []
    annot = IAnnotations(site)['broken_links_data']
    now = DateTime()
    links = get_links(site)

    if isinstance(annot, list):
        # store old data
        old_data = annot
        annot = PersistentMapping()
        IAnnotations(site)['broken_links_data'] = annot
        annot['pre_nov7_data'] = old_data

    for info in links:
        res = check_link(info['link'])
        if res is not None:
            res['object_url'] = info['object_url']
            results.append(res)

    annot[now] = results
    dates = annot.keys()

    if len(dates) >= 5:  # maximum no. of dates stored
        # delete oldest data except 'pre_nov7_data'
        del annot[sorted(dates)[0]]

    IAnnotations(site)._p_changed = True
    transaction.commit()
コード例 #18
0
ファイル: traversal.py プロジェクト: CGTIC/Plone_SP
class DeleteTile(TileTraverser):
    """Implements the @@delete-tile traversal view

    Traversing to /path/to/obj/@@delete-tile will list all tiles.
    Traversing to /path/to/obj/@@delete-tile/tile-id will delete tile.
    """

    tileId = None

    def __init__(self, context, request):
        super(DeleteTile, self).__init__(context, request)
        self.annotations = IAnnotations(self.context)

    def __call__(self):
        self.deleted = False
        if self.tileId is not None:
            del self.annotations['%s.%s' % (
                ANNOTATIONS_KEY_PREFIX, self.tileId)]
        return self.index()

    def tiles(self):
        for item in self.annotations.keys():
            if item.startswith(ANNOTATIONS_KEY_PREFIX):
                yield item[len(ANNOTATIONS_KEY_PREFIX) + 1:]

    def publishTraverse(self, request, name):
        """Allow traversal to @@delete-tile/tilename
        """

        if self.tileId is None:
            self.tileId = name

        return self
コード例 #19
0
class DeleteTile(TileTraverser):
    """Implements the @@delete-tile traversal view

    Traversing to /path/to/obj/@@delete-tile will list all tiles.
    Traversing to /path/to/obj/@@delete-tile/tile-id will delete tile.
    """

    tileId = None

    def __init__(self, context, request):
        super(DeleteTile, self).__init__(context, request)
        self.annotations = IAnnotations(self.context)

    def __call__(self):
        self.deleted = False
        if self.tileId is not None:
            del self.annotations['%s.%s' %
                                 (ANNOTATIONS_KEY_PREFIX, self.tileId)]
        return self.index()

    def tiles(self):
        for item in self.annotations.keys():
            if item.startswith(ANNOTATIONS_KEY_PREFIX):
                yield item[len(ANNOTATIONS_KEY_PREFIX) + 1:]

    def publishTraverse(self, request, name):
        """Allow traversal to @@delete-tile/tilename
        """

        if self.tileId is None:
            self.tileId = name

        return self
コード例 #20
0
ファイル: daviz.py プロジェクト: jean/eea.daviz
    def get_daviz(self):
        """Given an object, it will return the daviz+charts assigned

        It returns a mapping of
        <daviz uid A>:
            [daviz, (chart_id, chart title, embed_type, fallback_image)],
        <daviz uid B>:
            [daviz, (chart_id, chart title, embed_type, fallback_image)],
        """
        annot = IAnnotations(self.context).get('DAVIZ_CHARTS', {})

        uids_cat = getToolByName(self.context, 'uid_catalog')
        info = {}
        for uid in annot.keys():
            brains = uids_cat.searchResults(UID=uid)
            if not brains:
                logger.warning("Couldn't find visualization with UID %s" % uid)
                continue
            daviz = brains[0].getObject()
            tabs = getMultiAdapter((daviz, self.request),
                                   name="daviz-view.html").tabs

            annot_info = annot.get(uid, {})
            charts = []

            for chart_id in annot_info.keys():
                for tab in tabs:
                    if tab['name'] == chart_id:
                        #code = None #for the future, needs api in daviz
                        embed_type = annot_info[chart_id]
                        charts.append((chart_id, tab['title'], embed_type,
                                       tab['fallback-image']))
            info[uid] = (daviz, charts)

        return info
コード例 #21
0
ファイル: daviz.py プロジェクト: jean/eea.daviz
    def get_daviz(self):
        """Given an object, it will return the daviz+charts assigned

        It returns a mapping of
        <daviz uid A>:
            [daviz, (chart_id, chart title, embed_type, fallback_image)],
        <daviz uid B>:
            [daviz, (chart_id, chart title, embed_type, fallback_image)],
        """
        annot = IAnnotations(self.context).get('DAVIZ_CHARTS', {})

        uids_cat = getToolByName(self.context, 'uid_catalog')
        info = {}
        for uid in annot.keys():
            brains = uids_cat.searchResults(UID=uid)
            if not brains:
                logger.warning("Couldn't find visualization with UID %s" % uid)
                continue
            daviz = brains[0].getObject()
            tabs = getMultiAdapter((daviz, self.request),
                                   name="daviz-view.html").tabs

            annot_info = annot.get(uid, {})
            charts = []

            for chart_id in annot_info.keys():
                for tab in tabs:
                    if tab['name'] == chart_id:
                        #code = None #for the future, needs api in daviz
                        embed_type = annot_info[chart_id]
                        charts.append((chart_id, tab['title'], embed_type,
                                       tab['fallback-image']))
            info[uid] = (daviz, charts)

        return info
コード例 #22
0
def get_content_links(obj):
    refs = set()
    if ILayoutAware.providedBy(obj):
        behavior_data = ILayoutAware(obj)
        # get data from tile data
        annotations = IAnnotations(obj)
        for key in annotations.keys():
            if key.startswith(ANNOTATIONS_KEY_PREFIX):
                data = annotations[key]
                refs |= get_tile_data_links(obj, data)
        if not behavior_data.contentLayout and behavior_data.content:
            dom = fromstring(behavior_data.content)
            for el in dom.cssselect('.mosaic-text-tile .mosaic-tile-content'):
                links = extractLinks(tostring(el))
                refs |= li.getObjectsFromLinks(obj, links)
    try:
        # scan more than just this we probably should...
        value = obj.text.raw
        links = extractLinks(value)
        refs |= li.getObjectsFromLinks(obj, links)
    except AttributeError:
        pass

    if getattr(obj, 'image'):
        if IReferenceNamedImage.providedBy(obj.image):
            sub_obj = uuidToObject(obj.image.reference)
            if sub_obj:
                objid = get_ref(obj)
                if objid:
                    refs.add(RelationValue(objid))
    return refs
コード例 #23
0
ファイル: to0002.py プロジェクト: spanish/ftw.blog
def upgrade_to_v2(context):
    """Updates profile
    """
    ppcas = 'plone.portlets.contextassignments'
    catalog = getToolByName(context, 'portal_catalog')
    count = 0
    for brain in catalog(portal_type=['BlogEntry', 'BlogCategory', 'Blog']):
        obj = brain.getObject()
        annotations = IAnnotations(obj)
        if ppcas in annotations.keys():
            if 'blog.portlets' in annotations[ppcas]:
                count += 1
                if len(annotations[ppcas]) == 1:
                    del annotations[ppcas]
                else:
                    del annotations[ppcas]['blog.portlets']

    logger.info("%s %s annotations removed" % (str(count), ppcas))
    loadMigrationProfile(context, 'profile-ftw.blog.upgrades:to_v2')

    # remove blog_settings actions
    portal_actions = getToolByName(context, 'portal_actions')

    category = portal_actions.get('object_buttons', None)
    action_id = 'blog_settings'
    if category and action_id in category:
        del category[action_id]
コード例 #24
0
    def remove_number(self, obj, **keys):
        """Remove the entry in the local storage for the combinated key.
        """
        key = self.get_key(obj, keys)

        ann = IAnnotations(obj)
        if key in ann.keys():
            del ann[key]
コード例 #25
0
ファイル: survey.py プロジェクト: PMR2/nap.consent
 def cleanUp(self):
     numDelete = 0
     users = IAnnotations(api.portal.get())[Survey.KEY]
     for userId in users.keys():
         user = users.pop(userId)
         del user
         numDelete += 1
     return numDelete
コード例 #26
0
ファイル: favorite.py プロジェクト: adam139/emc.memberArea
    def __init__(self, context):
        self.context = context
        annotations = IAnnotations(context)
        if FAVORITE_KEY not in annotations.keys():
            # You know what happens if we don't use persistent classes here?
            annotations[FAVORITE_KEY] = PersistentList()

        self.favorite = annotations[FAVORITE_KEY]    
コード例 #27
0
def clear_cached_localroles(userid):
    """Given user id (not login name), clear cached localroles"""
    prefix = 'collective.teamwork.user.localrole.checkLocalRolesAllowed'
    request = getRequest()
    anno = IAnnotations(request)
    relevant = [k for k in anno.keys() if k.startswith(prefix) and userid in k]
    for key in relevant:
        del anno[key]
コード例 #28
0
def clear_cached_localroles(userid):
    """Given user id (not login name), clear cached localroles"""
    prefix = 'collective.teamwork.user.localrole.checkLocalRolesAllowed'
    request = getRequest()
    anno = IAnnotations(request)
    relevant = [k for k in anno.keys() if k.startswith(prefix) and userid in k]
    for key in relevant:
        del anno[key]
コード例 #29
0
ファイル: favorite.py プロジェクト: MWatHIT/emc_project
    def __init__(self, context):
        self.context = context
        annotations = IAnnotations(context)
        if FAVORITE_KEY not in annotations.keys():
            # You know what happens if we don't use persistent classes here?
            annotations[FAVORITE_KEY] = PersistentList()

        self.favorite = annotations[FAVORITE_KEY]    
コード例 #30
0
    def remove_number(self, obj, **keys):
        """Remove the entry in the local storage for the combinated key.
        """
        key = self.get_key(obj, keys)

        ann = IAnnotations(obj)
        if key in ann.keys():
            del ann[key]
コード例 #31
0
    def test_annotations(self):

        self.folder.invokeFactory('Document', 'd1')
        target = self.folder['d1']

        targetAnnotations = IAnnotations(target)
        targetAnnotations[u'test.key'] = 123
        targetAnnotations[u'other.key'] = 456

        draft = Draft()

        draftAnnotations = IAnnotations(draft)
        draftAnnotations[u'some.key'] = 234

        proxy = DraftProxy(draft, target)

        proxyAnnotations = IAnnotations(proxy)

        self.assertEqual(123, proxyAnnotations[u'test.key'])
        self.assertEqual(234, proxyAnnotations[u'some.key'])

        proxyAnnotations[u'test.key'] = 789

        self.assertEqual(789, proxyAnnotations[u'test.key'])
        self.assertEqual(123, targetAnnotations[u'test.key'])

        # Annotations API

        self.assertEqual(789, proxyAnnotations.get(u'test.key'))

        keys = proxyAnnotations.keys()
        self.assertTrue(u'test.key' in keys)
        self.assertTrue(u'some.key' in keys)
        self.assertTrue(u'other.key' in keys)

        self.assertEqual(789, proxyAnnotations.setdefault(u'test.key', -1))
        self.assertEqual(234, proxyAnnotations.setdefault(u'some.key', -1))
        self.assertEqual(456, proxyAnnotations.setdefault(u'other.key', -1))
        self.assertEqual(-1, proxyAnnotations.setdefault(u'new.key', -1))

        del proxyAnnotations[u'test.key']
        self.assertFalse(u'test.key' in proxyAnnotations)
        self.assertFalse(u'test.key' in draftAnnotations)
        self.assertTrue(u'test.key' in targetAnnotations)
        self.assertTrue(u'test.key' in draft._proxyAnnotationsDeleted)

        del proxyAnnotations[u'some.key']
        self.assertFalse(u'some.key' in proxyAnnotations)
        self.assertFalse(u'some.key' in draftAnnotations)
        self.assertFalse(u'some.key' in targetAnnotations)
        self.assertTrue(u'some.key' in draft._proxyAnnotationsDeleted)

        # this key was never in the proxy/draft
        del proxyAnnotations[u'other.key']
        self.assertFalse(u'other.key' in proxyAnnotations)
        self.assertFalse(u'other.key' in draftAnnotations)
        self.assertTrue(u'other.key' in targetAnnotations)
        self.assertTrue(u'other.key' in draft._proxyAnnotationsDeleted)
コード例 #32
0
 def _initStructure(self):
     """
     Data is stored in the object's annotations.
     Create the structure or return it
     """
     ann = IAnnotations(self.context)
     if not STORAGE_KEY in ann.keys():
         ann[STORAGE_KEY] = PersistentList()
     return ann[STORAGE_KEY]
コード例 #33
0
 def __init__(self, context):
     self.context = context
     annotations = IAnnotations(context)
     if KEY not in annotations.keys():
         annotations[KEY] = PersistentDict({
             "voted": PersistentList(),
             'votes': PersistentDict()
             })
     self.annotations = annotations[KEY]
コード例 #34
0
ファイル: tests.py プロジェクト: CGTIC/Plone_SP
 def test_annotations(self):
     
     self.folder.invokeFactory('Document', 'd1')
     target = self.folder['d1']
     
     targetAnnotations = IAnnotations(target)
     targetAnnotations[u"test.key"] = 123
     targetAnnotations[u"other.key"] = 456
     
     draft = Draft()
     
     draftAnnotations = IAnnotations(draft)
     draftAnnotations[u"some.key"] = 234
     
     proxy = DraftProxy(draft, target)
     
     proxyAnnotations = IAnnotations(proxy)
     
     self.assertEquals(123, proxyAnnotations[u"test.key"])
     self.assertEquals(234, proxyAnnotations[u"some.key"])
     
     proxyAnnotations[u"test.key"] = 789
     
     self.assertEquals(789, proxyAnnotations[u"test.key"])
     self.assertEquals(123, targetAnnotations[u"test.key"])
     
     # Annotations API
     
     self.assertEquals(789, proxyAnnotations.get(u"test.key"))
     
     keys = proxyAnnotations.keys()
     self.failUnless(u"test.key" in keys)
     self.failUnless(u"some.key" in keys)
     self.failUnless(u"other.key" in keys)
             
     self.assertEquals(789, proxyAnnotations.setdefault(u"test.key", -1))
     self.assertEquals(234, proxyAnnotations.setdefault(u"some.key", -1))
     self.assertEquals(456, proxyAnnotations.setdefault(u"other.key", -1))
     self.assertEquals(-1, proxyAnnotations.setdefault(u"new.key", -1))
     
     del proxyAnnotations[u"test.key"]
     self.failIf(u"test.key" in proxyAnnotations)
     self.failIf(u"test.key" in draftAnnotations)
     self.failUnless(u"test.key" in targetAnnotations)
     self.failUnless(u"test.key" in draft._proxyAnnotationsDeleted)
     
     del proxyAnnotations[u"some.key"]
     self.failIf(u"some.key" in proxyAnnotations)
     self.failIf(u"some.key" in draftAnnotations)
     self.failIf(u"some.key" in targetAnnotations)
     self.failUnless(u"some.key" in draft._proxyAnnotationsDeleted)
     
     del proxyAnnotations[u"other.key"] # this key was never in the proxy/draft
     self.failIf(u"other.key" in proxyAnnotations)
     self.failIf(u"other.key" in draftAnnotations)
     self.failUnless(u"other.key" in targetAnnotations)
     self.failUnless(u"other.key" in draft._proxyAnnotationsDeleted)
コード例 #35
0
ファイル: contentstorage.py プロジェクト: Vinsurya/Plone
 def _initStructure(self):
     """
     Data is stored in the object's annotations.
     Create the structure or return it
     """
     ann = IAnnotations(self.context)
     if not STORAGE_KEY in ann.keys():
         ann[STORAGE_KEY] = PersistentList()
     return ann[STORAGE_KEY]
コード例 #36
0
 def __init__(self, context):
     self.context = context
     annotations = IAnnotations(context)
     if KEY not in annotations.keys():
         # You know what happens if we don't use persistent classes here?
         annotations[KEY] = PersistentDict({
             "voted": PersistentList(),
             'votes': PersistentDict()
         })
     self.annotations = annotations[KEY]
コード例 #37
0
 def __init__(self, context):
     self.context = context
     annotations = IAnnotations(context)
     if KEY not in annotations.keys():
         # You know what happens if we don't use persistent classes here?
         annotations[KEY] = PersistentDict({
             "voted": PersistentList(),
             'votes': PersistentDict()
             })
     self.annotations = annotations[KEY]
コード例 #38
0
ファイル: storage.py プロジェクト: hellfish2/opengever.core
    def _get_user_storage(self):
        userid = getSecurityManager().getUser().getId()
        data = IAnnotations(getSite())
        if ANNOTATIONS_KEY not in data.keys():
            data[ANNOTATIONS_KEY] = OOBTree()

        storage = data[ANNOTATIONS_KEY]
        if userid not in storage.keys():
            storage.insert(userid, PersistentDict())

        return storage.get(userid)
コード例 #39
0
ファイル: storage.py プロジェクト: hellfish2/opengever.core
    def _get_user_storage(self):
        userid = getSecurityManager().getUser().getId()
        data = IAnnotations(getSite())
        if ANNOTATIONS_KEY not in data.keys():
            data[ANNOTATIONS_KEY] = OOBTree()

        storage = data[ANNOTATIONS_KEY]
        if userid not in storage.keys():
            storage.insert(userid, PersistentDict())

        return storage.get(userid)
コード例 #40
0
    def get_field_data(self):
        from plone.dexterity.interfaces import IDexterityFTI
        from plone.behavior.interfaces import IBehaviorAssignable

        data = {}

        schema = getUtility(IDexterityFTI,
                            name=self.obj.portal_type).lookupSchema()
        for name, field in getFieldsInOrder(schema):
            data[name] = getattr(self.obj, name, None)

        behavior_assignable = IBehaviorAssignable(self.obj)
        for behavior in behavior_assignable.enumerateBehaviors():
            binst = behavior.interface(self.obj)
            bdata = {}
            for name, field in getFieldsInOrder(behavior.interface):
                bdata[name] = getattr(binst, name, None)
            data[behavior.interface.__identifier__] = bdata

        if ILayoutAware.providedBy(self.obj):
            from plone.tiles.data import ANNOTATIONS_KEY_PREFIX
            from plone.app.blocks.utils import getLayout
            from repoze.xmliter.utils import getHTMLSerializer
            from plone.app.blocks import tiles
            from plone.app.blocks import gridsystem
            from lxml.html import tostring
            tdata = {}
            annotations = IAnnotations(self.obj, {})
            for key in annotations.keys():
                if key.startswith(ANNOTATIONS_KEY_PREFIX):
                    adata = annotations[key]
                    tdata[key] = adata
            data['tile_data'] = tdata

            req = site.REQUEST
            layout = getLayout(self.obj)
            dom = getHTMLSerializer(layout)

            try:
                tiles.renderTiles(req,
                                  dom.tree,
                                  site=site,
                                  baseURL=self.obj.absolute_url() +
                                  '/layout_view')
            except TypeError:
                tiles.renderTiles(req,
                                  dom.tree,
                                  baseURL=self.obj.absolute_url() +
                                  '/layout_view')
            gridsystem.merge(req, dom.tree)

            data['rendered_layout'] = tostring(dom.tree)

        return data
コード例 #41
0
def hasCrops(ob):
    #
    # Check if object has crops defined
    #
    annotations = IAnnotations(ob).get(PAI_STORAGE_KEY)
    if annotations != None:
        if 'image_mini' not in annotations.keys():
            return False
        else:
            return False
    else:
        return False
コード例 #42
0
 def fix_at_parent_for_discussions(obj, path):
     annotations = IAnnotations(obj, None)
     if not annotations:
         return
     if 'plone.app.discussion:conversation' not in annotations.keys():
         return
     conversation = annotations['plone.app.discussion:conversation']
     if 'broken' in str(conversation.__parent__):
         conversation.__parent__ = obj
         log.info(f'Fix conversation for {obj.absolute_url()}')
     else:
         log.info(f'Conversation parent ok: {conversation.__parent__}')
コード例 #43
0
    def test_annotation_schema_fail_no_mapping(self):
        dummy = IDummy2(self.portal)

        # standard schema validation kicks in
        with self.assertRaises(schema.interfaces.RequiredMissing):
            dummy.field1 = None
        with self.assertRaises(schema.interfaces.WrongType):
            dummy.field3 = u"test"

        # No mapping persisted.
        annotations = IAnnotations(self.portal)
        self.assertNotIn("repodono.storage.tests.test_annotation.Dummy2", annotations.keys())
コード例 #44
0
def set_counters(data):
    portal = getUtility(ISiteRoot)
    ann = IAnnotations(portal)

    if FILING_NO_KEY in ann.keys():
        entries = []
        for k, v in ann.get(FILING_NO_KEY).items():
            entries.append({'key': k, 'counter': v.value})
        return entries

    else:
        return {}
コード例 #45
0
ファイル: daviz.py プロジェクト: davilima6/eea.daviz
def handle_daviz_delete(context, event):
    """ Remove annotations from assessmentparts when a daviz has been deleted
    """
    context_uid = context.UID()
    refs = context.getBRefs()

    for o in refs:
        annot = IAnnotations(o).get(KEY, {})
        if context_uid in annot.keys():
            del annot[context_uid]
            annot._p_changed = True
            o._p_changed = True
コード例 #46
0
ファイル: daviz.py プロジェクト: eea/eea.daviz
def handle_daviz_delete(context, event):
    """ Remove annotations from assessmentparts when a daviz has been deleted
    """
    context_uid = context.UID()
    refs = context.getBRefs('relatesTo')

    for o in refs:
        annot = IAnnotations(o).get(KEY, {})
        if context_uid in annot.keys():
            del annot[context_uid]
            annot._p_changed = True
            o._p_changed = True
コード例 #47
0
ファイル: voting.py プロジェクト: starzel/Plone-Tutorial
 def __init__(self, context):
     self.context = context
     annotations = IAnnotations(context)
     if KEY not in annotations.keys():
         # Was passiert, wenn man kein PersistentDict oder List verwendet?
         annotations[KEY] = PersistentDict({
             "version": 1,
             "voted": PersistentList(),
             })
     self.annotations = annotations[KEY]
     if not self.annotations.has_key('version') or self.annotations['version'] == 1:
         self.annotations['version'] = 2
         self.annotations['votes'] = PersistentDict()
コード例 #48
0
 def get_next(self, key):
     portal = getUtility(ISiteRoot)
     ann = IAnnotations(portal)
     if SEQUENCE_NUMBER_ANNOTATION_KEY not in ann.keys():
         ann[SEQUENCE_NUMBER_ANNOTATION_KEY] = PersistentDict()
     map = ann.get(SEQUENCE_NUMBER_ANNOTATION_KEY)
     if key not in map:
         map[key] = Increaser(0)
     # increase
     inc = map[key]
     inc.set(inc() + 1)
     map[key] = inc
     return inc()
コード例 #49
0
    def test_annotation_schema_fail_no_mapping(self):
        dummy = IDummy2(self.portal)

        # standard schema validation kicks in
        with self.assertRaises(schema.interfaces.RequiredMissing):
            dummy.field1 = None
        with self.assertRaises(schema.interfaces.WrongType):
            dummy.field3 = u'test'

        # No mapping persisted.
        annotations = IAnnotations(self.portal)
        self.assertNotIn('repodono.storage.tests.test_annotation.Dummy2',
                         annotations.keys())
コード例 #50
0
def handle_gismap_delete(context, event):
    """ Remove annotations from assessmentparts when an interactive map
        has been deleted
    """
    context_uid = context.UID()
    refs = context.getBRefs()

    for o in refs:
        annot = IAnnotations(o).get(KEY, {})
        if context_uid in annot.keys():
            del annot[context_uid]
            annot._p_changed = True
            o._p_changed = True
コード例 #51
0
    def test_annotation_schema_standard_lifecycle(self):
        dummy = IDummy2(self.portal)

        self.assertIsNone(dummy.field1)
        self.assertIsNone(dummy.field2)
        self.assertIsNone(dummy.field3)

        # Failed assignments will not trigger addition of mapping.
        annotations = IAnnotations(self.portal)
        self.assertNotIn("repodono.storage.tests.test_annotation.Dummy2", annotations.keys())

        # assign some values
        dummy.field1 = u"Test"
        dummy.field2 = u"Value"
        dummy.field3 = 1

        annotations = IAnnotations(self.portal)
        value = annotations["repodono.storage.tests.test_annotation.Dummy2"]
        self.assertEqual(value, {"field1": u"Test", "field2": u"Value", "field3": 1})

        dummy.uninstall()
        self.assertNotIn("repodono.storage.tests.test_annotation.Dummy2", annotations.keys())
コード例 #52
0
ファイル: daviz.py プロジェクト: eea/eea.daviz
    def get_daviz(self):
        """Given an object, it will return the daviz+charts assigned

        It returns a mapping of
        <daviz uid A>:
            [daviz, (chart_id, chart title, embed_type, fallback_image)],
        <daviz uid B>:
            [daviz, (chart_id, chart title, embed_type, fallback_image)],
        """
        annot = IAnnotations(self.context).get('DAVIZ_CHARTS', {})

        uids_cat = getToolByName(self.context, 'uid_catalog')
        p_redirect = getToolByName(self.context, 'portal_redirection')
        info = {}
        parent = aq_parent(self.context)
        for uid in annot.keys():
            brains = uids_cat.searchResults(UID=uid)
            if not brains:
                msg = "Couldn't find visualization with UID %s" % uid
                logger.warning(msg)
                continue
            brain = brains[0]
            daviz = brain.getObject()
            if not daviz:  # brain does not lead to object?
                # 94042 check for object from redirection tool as the daviz
                # relation might end up being renamed
                if HAS_ASYNC:
                    a_sync = getUtility(IAsyncService)
                    try:
                        a_sync.queueJob(fix_broken_relationships, parent)
                    except Exception, e:
                        logger.exception("%s", e)
                daviz = p_redirect.getRedirectObject(brain.getURL(1))
                if daviz is None:
                    msg = "Couldn't find object for brain with UID %s" % uid
                    logger.warning(msg)
                    continue
            tabs = getMultiAdapter((daviz, self.request),
                                       name="daviz-view.html").tabs

            annot_info = annot.get(uid, {})
            charts = []

            for chart_id in annot_info.keys():
                for tab in tabs:
                    if tab['name'] == chart_id:
                        #code = None #for the future, needs api in daviz
                        embed_type = annot_info[chart_id]
                        charts.append((chart_id, tab['title'], embed_type,
                                       tab['fallback-image']))
            info[uid] = (daviz, charts)
コード例 #53
0
def copy_annotation(source, target):
    """Copy Zope annotations from source to target.
    """
    # Metadata and subscriptions are stored as annotations. This
    # migrates them.
    source_anno = IAnnotations(source)
    target_anno = IAnnotations(target)
    for key in list(source_anno.keys()):
        target_anno[key] = copy.deepcopy(source_anno[key])
    # Copy the old annotations to the version, it is possible we are
    # upgrading a 2.1 version that is not yet upgraded.
    old_annotations = getattr(aq_base(source), '_portal_annotations_', None)
    if old_annotations is not None:
        target._portal_annotations_ = old_annotations
コード例 #54
0
class Appraisal(object):
    """Adapter for disposition objects, which stores the archival appraisal
    for each dossiers in the annotations of the context (disposition).
    """

    key = 'disposition_appraisal'

    def __init__(self, context):
        self.context = context
        self._annotations = IAnnotations(self.context)
        if self.key not in self._annotations.keys():
            self._annotations[self.key] = PersistentDict()

    @property
    def storage(self):
        return self._annotations[self.key]

    def initialize(self, dossier):
        intid = getUtility(IIntIds).getId(dossier)
        self.storage[intid] = self.is_archival_worthy(dossier)

    def is_archival_worthy(self, dossier):
        """Checks the preselection in the archive_value field and return
        if the dossier should be archived or not.
        """
        return ILifeCycle(dossier).archival_value != ARCHIVAL_VALUE_UNWORTHY

    def get(self, dossier):
        intid = getUtility(IIntIds).getId(dossier)
        return self.storage.get(intid)

    def update(self, dossier=None, intid=None, archive=True):
        if not intid and not dossier:
            raise ValueError('dossier or intid needed.')

        if not intid:
            intid = getUtility(IIntIds).getId(dossier)

        self.storage[intid] = archive

    def drop(self, dossier):
        intid = getUtility(IIntIds).getId(dossier)
        self.storage.pop(intid)

    def write_to_dossier(self, dossier):
        if self.get(dossier):
            ILifeCycle(dossier).archival_value = ARCHIVAL_VALUE_WORTHY

        else:
            ILifeCycle(dossier).archival_value = ARCHIVAL_VALUE_UNWORTHY
コード例 #55
0
def copy_annotation(source, target):
    """Copy Zope annotations from source to target.
    """
    # Metadata and subscriptions are stored as annotations. This
    # migrates them.
    source_anno = IAnnotations(source)
    target_anno = IAnnotations(target)
    for key in source_anno.keys():
        target_anno[key] = copy.deepcopy(source_anno[key])
    # Copy the old annotations to the version, it is possible we are
    # upgrading a 2.1 version that is not yet upgraded.
    old_annotations = getattr(aq_base(source), '_portal_annotations_', None)
    if old_annotations is not None:
        target._portal_annotations_ = old_annotations