Exemplo n.º 1
0
 def test_dict(self):
     self.assertEqual(
         {
             u"foo": True,
             u"bar": None,
             u"baz": 3
         },
         json_compatible({
             "foo": True,
             "bar": None,
             "baz": 3
         }),
     )
     self.assertEqual('{"foo": "bar"}',
                      json.dumps(json_compatible({"foo": "bar"})))
     self.assertIsInstance(
         json_compatible(list({"foo": "bar"})[0]),
         six.text_type,
         "Dict keys should be converted recursively.",
     )
     self.assertIsInstance(
         json_compatible(list({"foo": "bar"}.values())[0]),
         six.text_type,
         "Dict values should be converted recursively.",
     )
 def __call__(self):
     data = []
     for value in self.get_value():
         if not value:
             continue
         content = value.to_object
         if not content:
             continue
         if not api.user.has_permission("View", obj=content):
             continue
         if content.effective().isFuture() and not api.user.has_permission(
                 "Modify portal content", obj=self.context):
             # effective date is in the future.
             # Users that can edit current context, should see it because otherwise
             # they will not see it in edit form.
             continue
         summary = getMultiAdapter((content, getRequest()),
                                   ISerializeToJsonSummary)()
         if content.effective().Date() != "1969/12/31":
             summary["effective"] = json_compatible(content.effective())
         else:
             summary["effective"] = None
         if content.portal_type == "Event":
             summary["start"] = json_compatible(
                 getattr(content, "start", ""))
             summary["end"] = json_compatible(getattr(content, "end", ""))
         if getattr(content, "icona", ""):
             summary["icona"] = content.icona
         data.append(json_compatible(summary))
     return data
Exemplo n.º 3
0
    def __call__(self):
        result = {
            '@context': 'http://www.w3.org/ns/hydra/context.jsonld',
            '@id': self.context.absolute_url(),
            '@type': self.context.portal_type,
            'parent': {
                '@id': aq_parent(aq_inner(self.context)).absolute_url(),
                'title': aq_parent(aq_inner(self.context)).title,
                'description': aq_parent(aq_inner(self.context)).description
            },
            'created': json_compatible(self.context.created()),
            'modified': json_compatible(self.context.modified()),
            'UID': self.context.UID(),
        }

        for schema in iterSchemata(self.context):

            read_permissions = mergedTaggedValueDict(
                schema, READ_PERMISSIONS_KEY)

            for name, field in getFields(schema).items():

                if not self.check_permission(read_permissions.get(name)):
                    continue

                serializer = queryMultiAdapter(
                    (field, self.context, self.request),
                    IFieldSerializer)
                value = serializer()
                result[json_compatible(name)] = value

        return result
Exemplo n.º 4
0
    def test_long(self):
        def _long(val):
            return int(val)

        self.assertEqual(_long(10), json_compatible(_long(10)))
        self.assertIsInstance(json_compatible(_long(10)), int)
        self.assertEqual("10", json.dumps(json_compatible(_long(10))))
Exemplo n.º 5
0
    def __call__(self):
        parent = aq_parent(aq_inner(self.context))
        parent_summary = getMultiAdapter(
            (parent, self.request), ISerializeToJsonSummary)()
        result = {
            # '@context': 'http://www.w3.org/ns/hydra/context.jsonld',
            '@id': self.context.absolute_url(),
            'id': self.context.id,
            '@type': self.context.portal_type,
            'parent': parent_summary,
            'created': json_compatible(self.context.created()),
            'modified': json_compatible(self.context.modified()),
            'review_state': self._get_workflow_state(),
            'UID': self.context.UID(),
        }

        for schema in iterSchemata(self.context):

            read_permissions = mergedTaggedValueDict(
                schema, READ_PERMISSIONS_KEY)

            for name, field in getFields(schema).items():

                if not self.check_permission(read_permissions.get(name)):
                    continue

                serializer = queryMultiAdapter(
                    (field, self.context, self.request),
                    IFieldSerializer)
                value = serializer()
                result[json_compatible(name)] = value

        return result
Exemplo n.º 6
0
 def __call__(self):
     field_name = self.field.__name__
     if (field_name == 'categories_evenements' or
        field_name.startswith('taxonomy_')) and \
        field_name != 'taxonomy_category':
         lang = self.context.language
         taxonomy_ids = self.get_value()
         if not taxonomy_ids:
             return []
         if isinstance(taxonomy_ids, basestring):
             taxonomy_ids = [taxonomy_ids]
         domain = 'collective.taxonomy.{0}'.format(
             field_name.replace('taxonomy_', '').replace('_', ''))
         sm = getSiteManager()
         utility = sm.queryUtility(ITaxonomy, name=domain)
         taxonomy_list = [taxonomy_id for taxonomy_id in taxonomy_ids]
         text = []
         if len(taxonomy_list) > 0:
             for taxonomy_id in taxonomy_list:
                 text.append(
                     safe_utf8(
                         utility.translate(taxonomy_id,
                                           context=self.context,
                                           target_language=lang)))
             return json_compatible(text)
     else:
         return json_compatible(self.get_value())
Exemplo n.º 7
0
    def __call__(self):
        result = {
            '@context': 'http://www.w3.org/ns/hydra/context.jsonld',
            '@id': self.context.absolute_url(),
            '@type': self.context.portal_type,
            'parent': {
                '@id': aq_parent(aq_inner(self.context)).absolute_url(),
                'title': aq_parent(aq_inner(self.context)).title,
                'description': aq_parent(aq_inner(self.context)).description
            },
            'created': json_compatible(self.context.created()),
            'modified': json_compatible(self.context.modified()),
            'UID': self.context.UID(),
        }

        for schema in iterSchemata(self.context):

            read_permissions = mergedTaggedValueDict(schema,
                                                     READ_PERMISSIONS_KEY)

            for name, field in getFields(schema).items():

                if not self.check_permission(read_permissions.get(name)):
                    continue

                serializer = queryMultiAdapter(
                    (field, self.context, self.request), IFieldSerializer)
                value = serializer()
                result[json_compatible(name)] = value

        return result
Exemplo n.º 8
0
    def _include_base_data(self, obj):
        """ """
        result = {}

        if self._get_param("include_base_data", True):
            result = {
                # '@context': 'http://www.w3.org/ns/hydra/context.jsonld',
                "@id":
                obj.absolute_url(),
                "id":
                obj.id,
                "@type":
                obj.portal_type,
                "created":
                json_compatible(obj.created()),
                "modified":
                json_compatible(obj.modified()),
                "review_state":
                self._get_workflow_state(obj),
                "UID":
                obj.UID(),
                "title":
                obj.Title(),
                "is_folderish":
                bool(getattr(aq_base(obj), 'isPrincipiaFolderish', False)),
            }
        return result
Exemplo n.º 9
0
 def __call__(self):
     field_name = self.field.__name__
     if (field_name == 'categories_evenements' or
        field_name.startswith('taxonomy_')) and \
        field_name != 'taxonomy_category':
         lang = self.context.language
         taxonomy_ids = self.get_value()
         if not taxonomy_ids:
             return []
         if isinstance(taxonomy_ids, basestring):
             taxonomy_ids = [taxonomy_ids]
         domain = 'collective.taxonomy.{0}'.format(
             field_name.replace('taxonomy_', '').replace('_', ''))
         sm = getSiteManager()
         utility = sm.queryUtility(ITaxonomy, name=domain)
         taxonomy_list = [taxonomy_id for taxonomy_id in taxonomy_ids]
         text = []
         if len(taxonomy_list) > 0:
             for taxonomy_id in taxonomy_list:
                 text.append(
                     safe_utf8(
                         utility.translate(
                             taxonomy_id,
                             context=self.context,
                             target_language=lang
                         )
                     )
                 )
             return json_compatible(text)
     else:
         return json_compatible(self.get_value())
Exemplo n.º 10
0
    def test_can_only_add_invitations_with_Workspace_related_roles(self, browser):
        self.login(self.workspace_admin, browser=browser)
        with browser.expect_http_error(401):
            data = json.dumps(json_compatible({
                'user': {'token': self.regular_user.id},
                'role': {'token': 'Reader'}
            }))
            browser.open(
                self.workspace.absolute_url() + '/@participations/invitations',
                method='POST',
                data=data,
                headers=http_headers(),
                )

        with browser.expect_http_error(500):
            data = json.dumps(json_compatible({
                'user': {'token': self.regular_user.id},
                'role': {'token': 'Site Administrator'}
            }))
            browser.open(
                self.workspace.absolute_url() + '/@participations/invitations',
                method='POST',
                data=data,
                headers=http_headers(),
                )
Exemplo n.º 11
0
    def __call__(self):
        field_list = self.request.form.get('items.fl', '').strip()
        if field_list:
            field_list = field_list.split(',')
        else:
            field_list = ['@type', 'title', 'description', 'review_state']

        obj = IContentListingObject(self.context)
        summary = json_compatible({
            '@id': obj.getURL(),
        })

        for field in field_list:
            accessor = FIELD_ACCESSORS.get(field)
            if accessor is None:
                continue
            if isinstance(accessor, str):
                value = getattr(obj, accessor, None)
                if callable(value):
                    value = value()
            else:
                value = accessor(obj)
            summary[field] = json_compatible(value)

        if ('title' in summary
                and ITranslatedTitleSupport.providedBy(self.context)):
            # Update title to contain translated title in negotiated language
            attr = 'title_{}'.format(get_preferred_language_code())
            summary['title'] = getattr(self.context, attr)

        return summary
Exemplo n.º 12
0
    def __call__(self):
        parent = aq_parent(aq_inner(self.context))
        parent_summary = getMultiAdapter(
            (parent, self.request), ISerializeToJsonSummary)()
        result = {
            # '@context': 'http://www.w3.org/ns/hydra/context.jsonld',
            '@id': self.context.absolute_url(),
            'id': self.context.id,
            '@type': self.context.portal_type,
            'parent': parent_summary,
            'created': json_compatible(self.context.created()),
            'modified': json_compatible(self.context.modified()),
            'review_state': self._get_workflow_state(),
            'UID': self.context.UID(),
        }

        for schema in iterSchemata(self.context):

            read_permissions = mergedTaggedValueDict(
                schema, READ_PERMISSIONS_KEY)

            for name, field in getFields(schema).items():

                if not self.check_permission(read_permissions.get(name)):
                    continue

                serializer = queryMultiAdapter(
                    (field, self.context, self.request),
                    IFieldSerializer)
                value = serializer()
                result[json_compatible(name)] = value

        return result
Exemplo n.º 13
0
    def __call__(self):
        field_list = self.request.form.get('items.fl', '').strip()
        if field_list:
            field_list = field_list.split(',')
        else:
            field_list = ['@type', 'title', 'description', 'review_state']

        obj = IContentListingObject(self.context)
        summary = json_compatible({
            '@id': obj.getURL(),
        })

        for field in field_list:
            accessor = FIELD_ACCESSORS.get(field)
            if accessor is None:
                continue
            if isinstance(accessor, str):
                value = getattr(obj, accessor, None)
                if callable(value):
                    value = value()
            else:
                value = accessor(obj)
            summary[field] = json_compatible(value)

        if ('title' in summary and
                ITranslatedTitleSupport.providedBy(self.context)):
            # Update title to contain translated title in negotiated language
            attr = 'title_{}'.format(get_preferred_language_code())
            summary['title'] = getattr(self.context, attr)

        return summary
 def test_richtext_from_text(self):
     value = RichTextValue(u'Hall\xf6chen',
                           mimeType='text/plain',
                           outputMimeType='text/html')
     self.assertEquals(u'<p>Hallöchen</p>', json_compatible(value))
     self.assertEquals(u'"<p>Hall\\u00f6chen</p>"',
                       json.dumps(json_compatible(value)))
Exemplo n.º 15
0
    def __call__(self, version=None, include_items=True):
        version = "current" if version is None else version

        obj = self.getVersion(version)
        parent = aq_parent(aq_inner(obj))
        parent_summary = getMultiAdapter(
            (parent, self.request), ISerializeToJsonSummary
        )()
        result = {
            # '@context': 'http://www.w3.org/ns/hydra/context.jsonld',
            "@id": obj.absolute_url(),
            "id": obj.id,
            "@type": obj.portal_type,
            "parent": parent_summary,
            "created": json_compatible(obj.created()),
            "modified": json_compatible(obj.modified()),
            "review_state": self._get_workflow_state(obj),
            "UID": obj.UID(),
            "version": version,
            "layout": self.context.getLayout(),
            "is_folderish": False,
        }

        # Insert next/prev information
        nextprevious = NextPrevious(obj)
        result.update(
            {"previous_item": nextprevious.previous, "next_item": nextprevious.next}
        )

        # Insert expandable elements
        result.update(expandable_elements(self.context, self.request))

        # Insert field values
        for schema in iterSchemata(self.context):
            read_permissions = mergedTaggedValueDict(schema, READ_PERMISSIONS_KEY)

            for name, field in getFields(schema).items():

                if not self.check_permission(read_permissions.get(name), obj):
                    continue

                # serialize the field
                serializer = queryMultiAdapter(
                    (field, obj, self.request), IFieldSerializer
                )
                value = serializer()
                result[json_compatible(name)] = value

        target_url = getMultiAdapter(
            (self.context, self.request), IObjectPrimaryFieldTarget
        )()
        if target_url:
            result["targetUrl"] = target_url

        result["allow_discussion"] = getMultiAdapter(
            (self.context, self.request), name="conversation_view"
        ).enabled()

        return result
 def test_persistent_list(self):
     value = PersistentList(['foo'])
     self.assertEquals(['foo'], json_compatible(value))
     self.assertEquals('["foo"]', json.dumps(json_compatible(value)))
     self.assertIsInstance(json_compatible(value)[0],
                           unicode,
                           'PersistentList values should be converted'
                           ' recursively.')
Exemplo n.º 17
0
 def test_tuple(self):
     # Tuples are converted to list (json would do that anyway and
     # it is easier to implement it with map).
     self.assertEqual(['foo', None], json_compatible(('foo', None)))
     self.assertEqual('["foo"]', json.dumps(json_compatible(('foo', ))))
     self.assertIsInstance(
         json_compatible(('foo', ))[0], six.text_type,
         'Tuple values should be converted recursively.')
 def test_persistent_mapping(self):
     value = PersistentMapping({'foo': 'bar'})
     self.assertEquals({u'foo': u'bar'}, json_compatible(value))
     self.assertEquals('{"foo": "bar"}', json.dumps(json_compatible(value)))
     self.assertIsInstance(json_compatible(value.keys()[0]), unicode,
                           'Dict keys should be converted recursively.')
     self.assertIsInstance(json_compatible(value.values()[0]), unicode,
                           'Dict values should be converted recursively.')
Exemplo n.º 19
0
 def test_persistent_list(self):
     value = PersistentList(['foo'])
     self.assertEqual(['foo'], json_compatible(value))
     self.assertEqual('["foo"]', json.dumps(json_compatible(value)))
     self.assertIsInstance(
         json_compatible(value)[0], six.text_type,
         'PersistentList values should be converted'
         ' recursively.')
Exemplo n.º 20
0
 def test_list(self):
     self.assertEqual(["foo"], json_compatible(["foo"]))
     self.assertEqual('["foo"]', json.dumps(json_compatible(["foo"])))
     self.assertIsInstance(
         json_compatible(["foo"])[0],
         str,
         "List values should be converted recursively.",
     )
 def test_tuple(self):
     # Tuples are converted to list (json would do that anyway and
     # it is easier to implement it with map).
     self.assertEquals(['foo', None], json_compatible(('foo', None)))
     self.assertEquals('["foo"]', json.dumps(json_compatible(('foo', ))))
     self.assertIsInstance(json_compatible(('foo',))[0],
                           unicode,
                           'Tuple values should be converted recursively.')
Exemplo n.º 22
0
 def __call__(self):
     accessor = self.field.getAccessor(self.context)
     refs = accessor()
     if refs is None:
         return None
     if self.field.multiValued:
         return json_compatible(refs)
     else:
         return json_compatible(refs)
Exemplo n.º 23
0
    def test_error_when_type_unknown(self):
        err_regex = r'^No converter for making <object object at [^>]*>' + \
                    r' \(<(class|type) \'object\'>\) JSON compatible.$'

        with self.assertRaisesRegexp(TypeError, err_regex):
            json_compatible(object())

        with self.assertRaisesRegexp(TypeError, err_regex):
            json_compatible({'foo': [object()]})
Exemplo n.º 24
0
 def __call__(self):
     accessor = self.field.getAccessor(self.context)
     refs = accessor()
     if self.field.multiValued:
         return [json_compatible(r.absolute_url()) for r in refs]
     else:
         if refs is None:
             return None
         return json_compatible(refs.absolute_url())
Exemplo n.º 25
0
 def __call__(self):
     accessor = self.field.getAccessor(self.context)
     refs = accessor()
     if self.field.multiValued:
         return [json_compatible(r.absolute_url()) for r in refs]
     else:
         if refs is None:
             return None
         return json_compatible(refs.absolute_url())
Exemplo n.º 26
0
 def __call__(self):
     value = self.get_value()
     if value:
         output = value.raw
         return {
             u"data": json_compatible(output),
             u"content-type": json_compatible(value.mimeType),
             u"encoding": json_compatible(value.encoding),
         }
Exemplo n.º 27
0
 def test_persistent_list(self):
     value = PersistentList(["foo"])
     self.assertEqual(["foo"], json_compatible(value))
     self.assertEqual('["foo"]', json.dumps(json_compatible(value)))
     self.assertIsInstance(
         json_compatible(value)[0],
         str,
         "PersistentList values should be converted" " recursively.",
     )
    def test_error_when_type_unknown(self):
        err_regex = r'^No converter for making <object object at [^>]*>' + \
                    r' \(<type \'object\'>\) JSON compatible.$'

        with self.assertRaisesRegexp(TypeError, err_regex):
            json_compatible(object())

        with self.assertRaisesRegexp(TypeError, err_regex):
            json_compatible({'foo': [object()]})
Exemplo n.º 29
0
    def serialize_item(self, proxy):
        json_data = {}
        json_schema = {}
        fti = proxy.fti

        overview = queryMultiAdapter((proxy, self.controlpanel.request),
                                     name='overview')
        form = overview.form_instance
        json_schema = get_jsonschema_for_controlpanel(
            self.controlpanel, self.controlpanel.context,
            self.controlpanel.request, form)

        for name, item in form.fields.items():
            serializer = queryMultiAdapter(
                (item.field, fti, self.controlpanel.request), IFieldSerializer)
            if serializer:
                value = serializer()
            else:
                value = getattr(fti, name, None)
            json_data[json_compatible(name)] = value

        behaviors = queryMultiAdapter((proxy, self.controlpanel.request),
                                      name='behaviors')
        form = behaviors.form_instance
        behaviors_schema = get_jsonschema_for_controlpanel(
            self.controlpanel, self.controlpanel.context,
            self.controlpanel.request, form)

        behaviors_schema['fieldsets'][0]['id'] = 'behaviors'
        behaviors_schema['fieldsets'][0]['title'] = translate(
            'Behaviors', domain="plone", context=self.controlpanel.request)
        json_schema['fieldsets'].extend(behaviors_schema['fieldsets'])
        json_schema['properties'].update(behaviors_schema['properties'])

        for name, item in form.fields.items():
            behaviors = getattr(fti, 'behaviors', [])
            json_data[json_compatible(name)] = name in behaviors

        # JSON schema
        return {
            "@id":
            "{}/{}/{}/{}".format(self.controlpanel.context.absolute_url(),
                                 SERVICE_ID, self.controlpanel.__name__,
                                 proxy.__name__),
            "title":
            fti.Title(),
            "description":
            fti.Description(),
            "group":
            self.controlpanel.group,
            "schema":
            json_schema,
            "data":
            json_data,
            "items": []
        }
Exemplo n.º 30
0
    def test_long(self):
        def _long(val):
            if six.PY2:
                return int(val)
            else:
                return int(val)

        self.assertEqual(_long(10), json_compatible(_long(10)))
        self.assertIsInstance(json_compatible(_long(10)), int)
        self.assertEqual('10', json.dumps(json_compatible(_long(10))))
 def test_persistent_mapping(self):
     value = PersistentMapping({'foo': 'bar'})
     self.assertEquals({u'foo': u'bar'}, json_compatible(value))
     self.assertEquals('{"foo": "bar"}', json.dumps(json_compatible(value)))
     self.assertIsInstance(json_compatible(value.keys()[0]),
                           unicode,
                           'Dict keys should be converted recursively.')
     self.assertIsInstance(json_compatible(value.values()[0]),
                           unicode,
                           'Dict values should be converted recursively.')
Exemplo n.º 32
0
 def __call__(self):
     mimetypes_registry = getToolByName(self.context, "mimetypes_registry")
     data = super(TextFieldSerializer, self).__call__()
     content_type = json_compatible(mimetypes_registry(data)[2].normalized())
     if content_type == u'text/html':
         data = handle_html(self.context, data)
     return {
         "content-type": json_compatible(content_type),
         "data": data,
     }
Exemplo n.º 33
0
    def test_error_when_type_unknown(self):
        err_regex = (
            r"^No converter for making <object object at [^>]*>"
            + r" \(<(class|type) \'object\'>\) JSON compatible.$"
        )

        with self.assertRaisesRegex(TypeError, err_regex):
            json_compatible(object())

        with self.assertRaisesRegex(TypeError, err_regex):
            json_compatible({"foo": [object()]})
Exemplo n.º 34
0
 def __call__(self):
     value = self.get_value()
     if getattr(value, 'to_object', False):
         obj = value.to_object
         result = {
             'title': obj.title,
             'path': '/'.join(obj.getPhysicalPath()),
             'phone': obj.phone,
             'cell_phone': obj.cell_phone,
         }
         result.update(get_address(obj))
         return json_compatible(result)
     return json_compatible(value, self.context)
Exemplo n.º 35
0
 def __call__(self):
     value = self.get_value()
     if getattr(value, 'to_object', False):
         obj = value.to_object
         result = {
             'title': obj.title,
             'path': '/'.join(obj.getPhysicalPath()),
             'phone': obj.phone,
             'cell_phone': obj.cell_phone,
         }
         result.update(get_address(obj))
         return json_compatible(result)
     return json_compatible(value, self.context)
Exemplo n.º 36
0
    def get_working_copy_info(self):
        baseline = self.baseline()
        working_copy = self.working_copy()

        sm = getSecurityManager()

        # No Working Copy exists
        if baseline is None and working_copy is None:
            return (None, None)

        # Baseline is None (context is the baseline), and working copy exists
        if baseline is None and working_copy:
            self.ref = working_copy

            if (
                sm.checkPermission(ModifyPortalContent, self.context)
                or sm.checkPermission(CheckoutPermission, self.context)
                or sm.checkPermission(ModifyPortalContent, working_copy)
            ):
                return (
                    None,
                    {
                        "@id": working_copy.absolute_url(),
                        "title": working_copy.title,
                        "created": json_compatible(self.created()),
                        "creator_url": self.creator_url(),
                        "creator_name": self.creator_name(),
                    },
                )
            else:
                return (None, None)

        # Baseline exist (context is the working copy), and working copy exists
        if baseline and working_copy:
            self.ref = baseline

            if sm.checkPermission(
                ModifyPortalContent, self.context
            ) or sm.checkPermission(CheckoutPermission, baseline):
                return (
                    {"@id": baseline.absolute_url(), "title": baseline.title},
                    {
                        "@id": working_copy.absolute_url(),
                        "title": working_copy.title,
                        "created": json_compatible(self.created()),
                        "creator_url": self.creator_url(),
                        "creator_name": self.creator_name(),
                    },
                )
            else:
                return (None, None)
Exemplo n.º 37
0
 def test_persistent_mapping(self):
     value = PersistentMapping({"foo": "bar"})
     self.assertEqual({"foo": "bar"}, json_compatible(value))
     self.assertEqual('{"foo": "bar"}', json.dumps(json_compatible(value)))
     self.assertIsInstance(
         json_compatible(list(value)[0]),
         str,
         "Dict keys should be converted recursively.",
     )
     self.assertIsInstance(
         json_compatible(list(value.values())[0]),
         str,
         "Dict values should be converted recursively.",
     )
 def test_dict(self):
     self.assertEquals({u'foo': True,
                        u'bar': None,
                        u'baz': 3},
                       json_compatible({'foo': True,
                                        'bar': None,
                                        'baz': 3}))
     self.assertEquals('{"foo": "bar"}',
                       json.dumps(json_compatible({'foo': 'bar'})))
     self.assertIsInstance(json_compatible({'foo': 'bar'}.keys()[0]),
                           unicode,
                           'Dict keys should be converted recursively.')
     self.assertIsInstance(json_compatible({'foo': 'bar'}.values()[0]),
                           unicode,
                           'Dict values should be converted recursively.')
Exemplo n.º 39
0
 def test_dict(self):
     self.assertEquals({u'foo': True,
                        u'bar': None,
                        u'baz': 3},
                       json_compatible({'foo': True,
                                        'bar': None,
                                        'baz': 3}))
     self.assertEquals('{"foo": "bar"}',
                       json.dumps(json_compatible({'foo': 'bar'})))
     self.assertIsInstance(json_compatible({'foo': 'bar'}.keys()[0]),
                           unicode,
                           'Dict keys should be converted recursively.')
     self.assertIsInstance(json_compatible({'foo': 'bar'}.values()[0]),
                           unicode,
                           'Dict values should be converted recursively.')
Exemplo n.º 40
0
    def test_modify_a_users_loca_roles(self, browser):
        self.login(self.workspace_admin, browser=browser)

        browser.open(
            self.workspace.absolute_url() + '/@participations',
            method='GET',
            headers=http_headers(),
        )

        entry = get_entry_by_token(browser.json.get('items'), self.workspace_guest.id)
        self.assertEquals('WorkspaceGuest', entry.get('role'))

        data = json.dumps(json_compatible({
            'role': {'token': 'WorkspaceMember'}
        }))
        browser.open(
            entry['@id'],
            method='PATCH',
            data=data,
            headers=http_headers(),
            )

        browser.open(
            self.workspace.absolute_url() + '/@participations',
            method='GET',
            headers=http_headers(),
        )

        entry = get_entry_by_token(browser.json.get('items'), self.workspace_guest.id)
        self.assertEquals('WorkspaceMember', entry.get('role'))
Exemplo n.º 41
0
    def reply(self):
        if self.transition is None:
            self.request.response.setStatus(400)
            return dict(error=dict(
                type='BadRequest',
                message='Missing transition'))

        data = json_body(self.request)
        if data.keys() not in [[], ['comment']]:
            self.request.response.setStatus(400)
            return dict(error=dict(
                type='BadRequest',
                message='Invalid body'))

        wftool = getToolByName(self.context, 'portal_workflow')

        # Disable CSRF protection
        if 'IDisableCSRFProtection' in dir(plone.protect.interfaces):
            alsoProvides(self.request,
                         plone.protect.interfaces.IDisableCSRFProtection)

        try:
            wftool.doActionFor(self.context, self.transition, **data)
        except WorkflowException as e:
            self.request.response.setStatus(400)
            return dict(error=dict(
                type='WorkflowException',
                message=translate(e.message, context=self.request)))

        history = wftool.getInfoFor(self.context, "review_history")
        return json_compatible(history[-1])
Exemplo n.º 42
0
    def test_modify_role_of_invitation(self, browser):
        self.login(self.workspace_admin, browser=browser)

        storage = getUtility(IInvitationStorage)
        iid = storage.add_invitation(
            self.workspace, self.regular_user.getId(),
            self.workspace_admin.getId(), 'WorkspaceGuest')

        data = json.dumps(json_compatible({
            'role': {'token': 'WorkspaceAdmin'}
        }))

        browser.open(
            self.workspace.absolute_url() + '/@participations/invitations/{}'.format(iid),
            method='PATCH',
            data=data,
            headers=http_headers(),
            )

        browser.open(
            self.workspace.absolute_url() + '/@participations',
            method='GET',
            headers=http_headers(),
        )

        self.assertEquals(
            'WorkspaceAdmin',
            get_entry_by_token(browser.json.get('items'), iid).get('role'))
Exemplo n.º 43
0
 def __call__(self):
     return {
         'content-type':
         json_compatible(self.field.getContentType(self.context)),
         'data':
         super(TextFieldSerializer, self).__call__()
     }
Exemplo n.º 44
0
    def __call__(self):
        image = self.field.get(self.context)
        if not image:
            return None

        width, height = image.getImageSize()

        url = get_original_image_url(
            self.context,
            self.field.__name__,
            width,
            height,
        )

        scales = get_scales(self.context, self.field, width, height)
        result = {
            'filename': image.filename,
            'content-type': image.contentType,
            'size': image.getSize(),
            'download': url,
            'width': width,
            'height': height,
            'scales': scales
        }
        return json_compatible(result)
Exemplo n.º 45
0
 def __call__(self):
     absolute_url = self.context.absolute_url()
     urls = {name: '{0}/@@images/image/{1}'.format(absolute_url, name)
             for name in self.get_scale_names()}
     urls['original'] = '/'.join((self.context.absolute_url(),
                                  '@@images',
                                  self.field.__name__))
     return json_compatible(urls)
 def test_richtext(self):
     value = RichTextValue(u'<p>Hallöchen</p>',
                           mimeType='text/html',
                           outputMimeType='text/html')
     self.assertEquals({
         u'content-type': u'text/html',
         u'data': u'<p>Hallöchen</p>',
         u'encoding': u'utf-8'}, json_compatible(value))
Exemplo n.º 47
0
 def __call__(self):
     summary = json_compatible({
         '@id': self.context.absolute_url(),
         '@type': self.context.portal_type,
         'title': self.context.title,
         'description': self.context.description
     })
     return summary
Exemplo n.º 48
0
 def __call__(self):
     obj = IContentListingObject(self.context)
     summary = json_compatible({
         '@id': obj.getURL(),
         '@type': obj.PortalType(),
         'title': obj.Title(),
         'description': obj.Description()
     })
     return summary
Exemplo n.º 49
0
    def __call__(self, *args, **kwargs):
        result = {
            'date': json_compatible(self.context.date),
            'creator': json_compatible(self.context.creator),
            'added_object': json_compatible(self.context.added_object),
            'changes': json_compatible(self.context.changes),
        }

        # Add attributes from the response schema
        for name, field in getFields(ITaskTransitionResponseFormSchema).items():
            if name in self.SKIPPED_FIELDS:
                continue

            serializer = queryMultiAdapter(
                (field, self.context, self.request), IFieldSerializer)
            value = serializer()
            result[json_compatible(name)] = value

        return result
Exemplo n.º 50
0
 def __call__(self):
     obj = self.context
     parent = obj.aq_parent
     summary = getMultiAdapter((parent, self.request), ISerializeToJson)()
     summary['@type'] = obj.portal_type
     summary['@id'] = obj.absolute_url(),
     summary['start'] = obj.start
     summary['end'] = obj.end
     summary['recurrence'] = ''
     return json_compatible(summary)
Exemplo n.º 51
0
 def __call__(self):
     url = '/'.join((self.context.absolute_url(),
                     '@@download',
                     self.field.getName()))
     result = {
         'filename': self.field.getFilename(self.context),
         'content-type': self.field.getContentType(self.context),
         'size': self.field.get_size(self.context),
         'download': url
     }
     return json_compatible(result)
Exemplo n.º 52
0
def serialize_webaction(action):
    """Serialize a webaction.

    `action` can be a PersistentMapping or a dict.
    """
    site = getSite()
    result = dict(action).copy()
    result = json_compatible(result)
    url = '/'.join((site.absolute_url(), '@webactions/%s' % action['action_id']))
    result.update({'@id': url})
    return result
Exemplo n.º 53
0
 def serialize(self, portal_url):
     return {
         '@id': self._api_url(portal_url),
         'notification_id': self.notification_id,
         'created': json_compatible(self.activity.created),
         'read': self.is_read,
         'title': self.activity.title,
         'label': self.activity.label,
         'link': self._resolve_notification_link(portal_url),
         'summary': self.activity.summary,
     }
Exemplo n.º 54
0
    def _create_items(self, batch):
        items = []
        for entry in batch:
            action = entry.get('action')
            item = {}
            item['title'] = translate(action.get('title'), context=self.request)
            item['time'] = json_compatible(entry.get('time'))
            item['actor_id'] = entry.get('actor')
            item['actor_fullname'] = display_name(entry.get('actor'))
            item['comments'] = entry.get('comments')
            items.append(item)

        return items
Exemplo n.º 55
0
    def __call__(self):
        namedfile = self.field.get(self.context)
        if namedfile is None:
            return None

        url = "/".join((self.context.absolute_url(), "@@download", self.field.__name__))
        result = {
            "filename": namedfile.filename,
            "content-type": namedfile.contentType,
            "size": namedfile.getSize(),
            "download": url,
        }
        return json_compatible(result)
 def test_relation_value(self):
     portal = self.layer['portal']
     doc1 = portal[portal.invokeFactory(
         'DXTestDocument', id='doc1',
         title='Document 1',
         description='Description',
     )]
     intids = getUtility(IIntIds)
     self.assertEquals(
         {'@id': 'http://nohost/plone/doc1',
          '@type': 'DXTestDocument',
          'title': 'Document 1',
          'description': 'Description'},
         json_compatible(RelationValue(intids.getId(doc1))))
Exemplo n.º 57
0
    def reply(self):
        if self.transition not in self.CUSTOMIZED_TRANSITIONS:
            # Delegate to default implementation
            return super(GEVERDossierWorkflowTransition, self).reply()

        try:
            self.perform_custom_transition()

        except WorkflowException as e:
            self.request.response.setStatus(400)
            msg = self.translate(str(e))
            return dict(error=dict(
                type='WorkflowException',
                message=msg))

        except PreconditionsViolated as e:
            self.request.response.setStatus(400)
            return dict(error=dict(
                type='PreconditionsViolated',
                errors=map(self.translate, e.errors),
                message=self.translate(str(e))))

        except InvalidDates as e:
            # From the REST API's point of view, invalid dates are just
            # another violated precondition.
            self.request.response.setStatus(400)
            msg = self.translate(str(e))
            errors = ['The dossier %s has a invalid end_date' % title
                      for title in e.invalid_dossier_titles]
            return dict(error=dict(
                type='PreconditionsViolated',
                errors=errors,
                message=msg))

        except AlreadyBeingResolved as e:
            self.request.response.setStatus(400)
            msg = self.translate(MSG_ALREADY_BEING_RESOLVED)
            return dict(error=dict(
                type='AlreadyBeingResolved',
                message=msg))

        except BadRequest as e:
            self.request.response.setStatus(400)
            return dict(error=dict(
                type='Bad Request',
                message=str(e)))

        action = self.get_latest_wf_action()
        return json_compatible(action)
Exemplo n.º 58
0
def create_list_item(item, fields):
    obj = IContentListingObject(item)
    data = {'@id': obj.getURL()}
    for field in fields:
        if field not in FIELDS:
            continue
        accessor = FIELDS[field][1]
        if isinstance(accessor, str):
            value = getattr(obj, accessor, None)
            if callable(value):
                value = value()
        else:
            value = accessor(obj)
        data[field] = json_compatible(value)
    return data
Exemplo n.º 59
0
def SerializeToJson(context):
    result = {
        '@context': 'http://www.w3.org/ns/hydra/context.jsonld',
        '@id': context.absolute_url(),
        '@type': context.portal_type,
        'parent': {
            '@id': aq_parent(aq_inner(context)).absolute_url(),
            'title': aq_parent(aq_inner(context)).title,
            'description': aq_parent(aq_inner(context)).description
        }
    }
    if IFolderish.providedBy(context):
        result['member'] = [
            {
                '@id': member.absolute_url(),
                'title': member.title,
                'description': member.description
            }
            for member in context.objectValues()
        ]

    if HAS_PLONE_APP_CONTENTTYPES:
        # Conditional import in order to avoid a hard dependency on p.a.ct
        from plone.app.contenttypes.interfaces import ICollection

        if ICollection.providedBy(context):
            portal = getSite()
            result['member'] = [
                {
                    '@id': '{0}/{1}'.format(
                        portal.absolute_url(),
                        '/'.join(member.getPhysicalPath())
                    ),
                    'title': member.title,
                    'description': member.description
                }
                for member in context.results()
            ]

    for schema in iterSchemata(context):
        for field_name, field in getFields(schema).items():
            value = lookup_field_serializer(context, field)()
            result[json_compatible(field_name)] = value

    return result
Exemplo n.º 60
0
    def __call__(self):
        image = self.field.get(self.context)
        if not image:
            return None

        url = "/".join((self.context.absolute_url(), "@@images", self.field.__name__))

        width, height = image.getImageSize()
        scales = get_scales(self.context, self.field, width, height)
        result = {
            "filename": image.filename,
            "content-type": image.contentType,
            "size": image.getSize(),
            "download": url,
            "width": width,
            "height": height,
            "scales": scales,
        }
        return json_compatible(result)