Ejemplo n.º 1
0
 def manage_FTPget(self, REQUEST=None, RESPONSE=None):
     """Return the body of the content item in an FTP or WebDAV response.
     
     This adapts self to IRawReadFile(), which is then returned as an
     iterator. The adapter should provide IStreamIterator.
     """
     reader = IRawReadFile(self, None)
     if reader is None:
         return ''
     
     request = REQUEST is not None and REQUEST or self.REQUEST
     response = RESPONSE is not None and RESPONSE or request.response
     
     mimeType = reader.mimeType
     encoding = reader.encoding
     
     if mimeType is not None:
         if encoding is not None:
             response.setHeader('Content-Type', '%s; charset="%s"' % (mimeType, encoding,))
         else:
             response.setHeader('Content-Type', mimeType)
     
     size = reader.size()
     if size is not None:
         response.setHeader('Content-Length', str(size))
     
     # if the reader is an iterator that the publisher can handle, return
     # it as-is. Otherwise, read the full contents
     
     if ((IInterface.providedBy(IStreamIterator) and IStreamIterator.providedBy(reader))
      or (not IInterface.providedBy(IStreamIterator) and IStreamIterator.isImplementedBy(reader))
     ):
         return reader
     else:
         return reader.read()
Ejemplo n.º 2
0
 def _get_post_metric_name(self, iresource: IInterface) -> str:
     name = 'process.post'
     if iresource.isOrExtends(IProposalVersion):
         name = 'process.post.proposalversion'
     elif iresource.isOrExtends(IRateVersion):
         name = 'process.post.rateversion'
     return name
Ejemplo n.º 3
0
def referential_integrity(event):
    if event.moving:
        return
    obj = event.object
    obj_oid = oid_of(obj, None)
    objectmap = find_objectmap(obj)
    if objectmap is None:
        return
    for reftype in objectmap.get_reftypes():

        is_iface = IInterface.providedBy(reftype)

        if is_iface and reftype.queryTaggedValue('source_integrity', False):
            targetids = objectmap.targetids(obj, reftype)
            if obj_oid in targetids:
                targetids.remove(obj_oid) # self-referential
            if targetids:
                # object is a source
                raise SourceIntegrityError(obj, reftype, targetids)

        if is_iface and reftype.queryTaggedValue('target_integrity', False):
            sourceids = objectmap.sourceids(obj, reftype)
            if obj_oid in sourceids:
                sourceids.remove(obj_oid) # self-referential
            if sourceids:
                # object is a target
                raise TargetIntegrityError(obj, reftype, sourceids)
Ejemplo n.º 4
0
 def __init__(self, context, schema):
     if not IComposedQuery.providedBy(context):
         raise ValueError('context must provide IComposedQuery')
     if not IInterface.providedBy(schema):
         raise ValueError('schema provided must be interface')
     self.context = context
     self.schema = schema
Ejemplo n.º 5
0
def find_parents(context, findone=False, start_depth=2, **kwargs):
    typename = kwargs.get("typename", None)
    iface = kwargs.get("iface", None)
    if IInterface.providedBy(iface):
        iface = iface.__identifier__
    if findone and typename is None and iface is None:
        parent = getattr(context, "__parent__", None)
        if parent:
            return parent  # immediate parent of context
    result = []
    catalog = getToolByName(context, "portal_catalog")
    path = context.getPhysicalPath()
    subpaths = reversed([path[0:i] for i in range(len(path) + 1)][start_depth:])
    for subpath in subpaths:
        query = {"path": {"query": "/".join(subpath), "depth": 0}}
        if typename is not None:
            query["portal_type"] = typename
        if iface is not None:
            query["object_provides"] = iface
        brains = catalog.unrestrictedSearchResults(query)
        if not brains:
            continue
        else:
            item = brains[0]._unrestrictedGetObject()
            if aq_base(item) is aq_base(context):
                continue  # don't return or append the context itself!
            if findone:
                return item
            result.append(item)
    if findone:
        return None  # never found one
    return result
Ejemplo n.º 6
0
def referential_integrity(event):
    if event.moving is not None: # being moved
        return

    objectmap = find_objectmap(event.object)

    if objectmap is None:
        return

    reftypes = list(objectmap.get_reftypes())

    for oid in event.removed_oids:

        for reftype in reftypes:

            is_iface = IInterface.providedBy(reftype)

            if is_iface and reftype.queryTaggedValue('source_integrity', False):
                targetids = objectmap.targetids(oid, reftype)
                if oid in targetids:
                    targetids.remove(oid) # self-referential
                if targetids:
                    # object is a source
                    obj = objectmap.object_for(oid)
                    raise SourceIntegrityError(obj, reftype, targetids)

            if is_iface and reftype.queryTaggedValue('target_integrity', False):
                sourceids = objectmap.sourceids(oid, reftype)
                if oid in sourceids:
                    sourceids.remove(oid) # self-referential
                if sourceids:
                    # object is a target
                    obj = objectmap.object_for(oid)
                    raise TargetIntegrityError(obj, reftype, sourceids)
Ejemplo n.º 7
0
    def register(template=template):
        if isinstance(template, basestring):
            helper = renderers.RendererHelper(name=template, package=config.package, registry=config.registry)
            template = helper.renderer.implementation()

        layout_intr.update(dict(name=name, filename=template.filename, context=context, callable=layout))
        introspectables.append(layout_intr)

        def derived_layout(context, request):
            wrapped = layout(context, request)
            wrapped.__layout__ = name
            wrapped.__template__ = template
            return wrapped

        r_context = context
        if r_context is None:
            r_context = Interface
        if not IInterface.providedBy(r_context):
            r_context = implementedBy(r_context)

        reg_layout = config.registry.adapters.lookup((r_context,), ILayout, name=name)
        if isinstance(reg_layout, _MultiLayout):
            reg_layout[containment] = derived_layout
            return
        elif containment:
            reg_layout = _MultiLayout(reg_layout)
            reg_layout[containment] = derived_layout
        else:
            reg_layout = derived_layout

        config.registry.registerAdapter(reg_layout, (context,), ILayout, name=name)
Ejemplo n.º 8
0
def resolve(name):
    """Resolve the name.
    """
    obj = pythonResolve(name)
    if not IInterface.providedBy(obj):
        return obj.__provides__._implements
    return obj
Ejemplo n.º 9
0
 def factory(self, schema):
     if not IInterface.providedBy(schema):
         raise GrokImportError(
             "You can only pass an interface to the "
             "provides argument of %s." % self.name)
     return schema
     
Ejemplo n.º 10
0
 def available(self):
     # We are available if we have sublevel menu or a screen.
     return (
         (len(self.submenu) != 0)
         or IUIScreen.implementedBy(self.screen)
         or (IInterface.providedBy(self.interface) and self.interface.extends(IUIScreen))
     )
Ejemplo n.º 11
0
 def __get__(self, inst, cls=None):
     global generated
     if inst is None:
         return getObjectSpecification(cls)
     spec = getattr(inst, '__provides__', None)
     if spec is None:
         spec = implementedBy(cls)
     signature = getattr(inst, 'signature', None)
     if signature is None:
         return spec
     if not ismd5hex(signature):
         if not isdottedname(signature):
             return spec
         # not an md5 signature, so perhaps we have a dotted name
         try:
             iface = resolve(signature)
             if not IInterface.providedBy(iface):
                 raise ValueError('Not interface: %s' % signature)
             return Implements(iface, spec)
         except ImportError:
             logger.warning('SignatureAwareDescriptor: '
                            'unabled to resolve interface '
                            '%s by dotted name.')
             return spec
     iface_name = 'I%s' % signature
     dynamic = [getattr(generated, iface_name)]
     dynamic.append(spec)
     spec = Implements(*dynamic)
     return spec
Ejemplo n.º 12
0
 def __init__(self, context, schema):
     if not IFilterGroup.providedBy(context):
         raise ValueError('context must provide IFilterGroup')
     if not IInterface.providedBy(schema):
         raise ValueError('schema provided must be interface')
     self.context = context
     self.schema = schema
Ejemplo n.º 13
0
def identifier(obj):
    """Gives the Python identifier for the given object, so after we
    can do resolve on it to get it back.
    """
    if IInterface.providedBy(obj):
        return obj.__identifier__
    return obj.__name__
Ejemplo n.º 14
0
 def forget(self, schema):
     name = str(schema)
     if IInterface.providedBy(schema):
         name = identify_interface(schema)
     if name not in self._names:
         return
     self._names.remove(name)
Ejemplo n.º 15
0
    def __init__(self, schema=_NotGiven, **kw):
        """
        Object(schema=<Not Given>, *, validate_invariants=True, **kwargs)

        Create an `~.IObject` field. The keyword arguments are as for `~.Field`.

        .. versionchanged:: 4.6.0
           Add the keyword argument *validate_invariants*. When true (the default),
           the schema's ``validateInvariants`` method will be invoked to check
           the ``@invariant`` properties of the schema.
        .. versionchanged:: 4.6.0
           The *schema* argument can be ommitted in a subclass
           that specifies a ``schema`` attribute.
        """
        if schema is _NotGiven:
            schema = self.schema

        if not IInterface.providedBy(schema):
            # Note that we don't provide 'self' as the 'field'
            # by calling with_field_and_value(): We're not fully constructed,
            # we don't want this instance to escape.
            raise NotAnInterface(schema, self.__name__)

        self.schema = schema
        self.validate_invariants = kw.pop('validate_invariants', True)
        super(Object, self).__init__(**kw)
Ejemplo n.º 16
0
 def bind(self, schema):
     if not IInterface.providedBy(schema):
         raise TypeError("Cannot bind non-interface object %s" % schema)
     name = identify_interface(schema)
     if name in self._names:
         raise KeyError("duplicate schema: Interface %s already managed." % (name,))
     self._names.append(name)
Ejemplo n.º 17
0
 def __init__(self, context, request):
     super(ModuleDetails, self).__init__(context, request)
     items = list(self.context.items())
     items.sort()
     self.text_files = []
     self.zcml_files = []
     self.modules = []
     self.interfaces = []
     self.classes = []
     self.functions = []
     for name, obj in items:
         entry = {'name': name, 'url': absoluteURL(obj, self.request)}
         if IFunctionDocumentation.providedBy(obj):
             entry['doc'] = formatDocString(
                 obj.getDocString(), self.context.getPath())
             entry['signature'] = obj.getSignature()
             self.functions.append(entry)
         elif IModuleDocumentation.providedBy(obj):
             entry['doc'] = formatDocString(
                 obj.getDocString(), obj.getPath(), True)
             self.modules.append(entry)
         elif IInterface.providedBy(obj):
             entry['path'] = getPythonPath(removeAllProxies(obj))
             entry['doc'] = formatDocString(
                 obj.__doc__, obj.__module__, True)
             self.interfaces.append(entry)
         elif IClassDocumentation.providedBy(obj):
             entry['doc'] = formatDocString(
                 obj.getDocString(), self.context.getPath(), True)
             self.classes.append(entry)
         elif IZCMLFile.providedBy(obj):
             self.zcml_files.append(entry)
         elif ITextFile.providedBy(obj):
             self.text_files.append(entry)
Ejemplo n.º 18
0
    def resolve_isheet_field_from_dotted_string(self, dotted: str) -> tuple:
        """Resolve `dotted` string to isheet and field name and schema node.

        :dotted: isheet.__identifier__ and field_name separated by ':'
        :return: tuple with isheet (ISheet), field_name (str), field schema
                 node (colander.SchemaNode).
        :raise ValueError: If the string is not dotted or it cannot be
            resolved to isheet and field name.
        """
        if ':' not in dotted:
            raise ValueError(
                'Not a colon-separated dotted string: {}'.format(dotted))
        name = ''.join(dotted.split(':')[:-1])
        field = dotted.split(':')[-1]
        try:
            isheet = resolver.resolve(name)
        except ImportError:
            raise ValueError('No such sheet: {}'.format(name))
        if not (IInterface.providedBy(isheet) and isheet.isOrExtends(ISheet)):
            raise ValueError('Not a sheet: {}'.format(name))
        schema = self.sheets_meta[isheet].schema_class()
        node = schema.get(field, None)
        if not node:
            raise ValueError('No such field: {}'.format(dotted))
        return isheet, field, node
Ejemplo n.º 19
0
def MultiChecker(specs):
    """Create a checker from a sequence of specifications

    A specification is:

    - A two-tuple with:

      o a sequence of names or an interface

      o a permission id

      All the names in the sequence of names or the interface are
      protected by the permission.

    - A dictionoid (having an items method), with items that are
      name/permission-id pairs.
    """
    data = {}

    for spec in specs:
        if type(spec) is tuple:
            names, permission_id = spec
            if IInterface.providedBy(names):
                names = names.names(all=True)
            for name in names:
                if data.get(name, permission_id) is not permission_id:
                    raise DuplicationError(name)
                data[name] = permission_id
        else:
            for name, permission_id in spec.items():
                if data.get(name, permission_id) is not permission_id:
                    raise DuplicationError(name)
                data[name] = permission_id

    return Checker(data)
Ejemplo n.º 20
0
    def setup(self, catalog, name, context, module_info):
        # If the user supplied attribute= when instantiating us, we
        # allow that value to override the attribute name under which we
        # are actually stored inside of the `grokcore.catalog.Indexes`
        # instance.
        if self._attribute is not None:
            field_name = self._attribute
        else:
            field_name = name

        if IInterface.providedBy(context):
            try:
                method = context[field_name]
            except KeyError:
                raise GrokError(
                    "grokcore.catalog.Indexes in %r refers to an attribute or "
                    "method %r on interface %r, but this does not "
                    "exist." % (module_info.getModule(),
                                field_name, context), None)
            call = IMethod.providedBy(method)
        else:
            call = callable(getattr(context, field_name, None))
            context = None  # no interface lookup
        catalog[name] = self.index_class(
            field_name=field_name,
            interface=context,
            field_callable=call,
            *self._args, **self._kw)
Ejemplo n.º 21
0
 def _validate(self, value):
     super(InterfaceField, self)._validate(value)
     if not IInterface.providedBy(value):
         raise NotAnInterface(
             value,
             self.__name__
         ).with_field_and_value(self, value)
Ejemplo n.º 22
0
    def provideAdapter(self, required, provided, name, factory, info=''):
        """Register an adapter

        >>> from zope.interface import Interface
        >>> registry = GlobalSiteManager()
        >>> class R1(Interface):
        ...     pass
        >>> class R2(R1):
        ...     pass
        >>> class P1(Interface):
        ...     pass
        >>> class P2(P1):
        ...     pass

        >>> registry.provideAdapter((R1, ), P2, 'bob', 'c1', 'd1')
        >>> registry.provideAdapter((R1, ), P2,    '', 'c2', 'd2')
        >>> registry.adapters.lookup((R2, ), P1, '')
        'c2'

        >>> registrations = map(repr, registry.registrations())
        >>> registrations.sort()
        >>> for registration in registrations:
        ...    print registration
        AdapterRegistration(('R1',), 'P2', '', 'c2', 'd2')
        AdapterRegistration(('R1',), 'P2', 'bob', 'c1', 'd1')

        Let's make sure that we can also register regular classes for
        adaptation.

        >>> class O1(object):
        ...     pass
        >>> class O2(object):
        ...     pass
        >>> class O3(object):
        ...     def __init__(self, obj1, obj2=None):
        ...         pass

        >>> registry.provideAdapter((O1, ), R1, '', O3)
        >>> registry.queryAdapter(O1(), R1, '').__class__
        <class 'zope.component.site.O3'>

        >>> registry.provideAdapter((O1, O2), R1, '', O3)
        >>> registry.queryMultiAdapter((O1(), O2()), R1, '').__class__
        <class 'zope.component.site.O3'>
        """
        ifaces = []
        for iface in required:
            if not IInterface.providedBy(iface) and iface is not None:
                if not isinstance(iface, (type, types.ClassType)):
                    raise TypeError(iface, IInterface)
                iface = implementedBy(iface)

            ifaces.append(iface)
        required = tuple(ifaces)

        self._registrations[(required, provided, name)] = AdapterRegistration(
            required, provided, name, factory, info)

        self.adapters.register(required, provided, name, factory)
Ejemplo n.º 23
0
 def __init__(self, schema, **kwargs):
     if IInterface.providedBy(schema):
         self.identifier = schema.__identifier__
     else:
         self.identifier = str(schema)
     for name in getFieldNamesInOrder(interfaces.IFlavor):
         if name in kwargs:
             setattr(self, name, kwargs.get(name))
Ejemplo n.º 24
0
    def execute(self, factory, config, context, **kw):

        if getattr(factory, 'schema', None) is None and \
                IInterface.providedBy(context):
            factory.schema = context
            return True
        else:
            return False
Ejemplo n.º 25
0
 def acquire(self, interface):
     node = self.parent
     while node:
         if (IInterface.providedBy(interface) and
                 interface.providedBy(node)) or \
                 isinstance(node, interface):
             return node
         node = node.parent
Ejemplo n.º 26
0
 def factory(self, *args):
     if not args:
         raise TypeError("The omitted directive expects at least one argument.")
     form_interface = Interface
     if IInterface.providedBy(args[0]):
         form_interface = args[0]
         args = args[1:]
     return [(form_interface, field, self.value) for field in args]
Ejemplo n.º 27
0
def list_base_interfaces(interface):
    """List all interfaces regrouped by this one.
    """
    if IInterface.providedBy(interface):
        yield interface
        for base in interface.__bases__:
            for base_base in list_base_interfaces(base):
                yield base_base
Ejemplo n.º 28
0
 def add_content_provider(self, provider, name, context=None):
     """ Add content provider."""
     if context is None:
         context = Interface
     if not IInterface.providedBy(context):
         context = implementedBy(context)
     self.registry.registerAdapter(
         provider, (context,), IContentProvider, name=name)
def setBody(self, body, *args, **kw):
    if IInterface.providedBy(IStreamIterator):  # is this zope 2.12?
        stream = IStreamIterator.providedBy(body)
    else:
        stream = IStreamIterator.isImplementedBy(body)
    if stream:
        body = ''.join(body)    # read from iterator
    return original_setBody(self, body, *args, **kw)
Ejemplo n.º 30
0
 def testFileBlobInterfaces(self):
     foo = self.folder[self.folder.invokeFactory('File', 'foo')]
     self.assertTrue(atfile.IATFile.providedBy(foo), 'no IATFile?')
     self.assertTrue(atfile.IFileContent.providedBy(foo), 'no IFileContent?')
     self.assertTrue(IATBlobFile.providedBy(foo), 'no IATBlobFile?')
     if not IInterface.providedBy(Z2IATFile):    # this is zope < 2.12
         self.assertTrue(Z2IATFile.isImplementedBy(foo), 'no zope2 IATFile?')
         self.assertFalse(Z2IATImage.isImplementedBy(foo), 'zope2 IATImage?')
Ejemplo n.º 31
0
def _get(discriminator):
    """Get the TypeInfo instance for discriminator, that may be any of:
            type_key: str (the lowercase underscore-separated of domain cls name)
            workflow: an instance of Workflow, provides IWorkflow
            interface: provides IInterface
            domain model: provides IBungeniContent
            domain model instance: type provides IBungeniContent
            descriptor: provides IModelDescriptor
    
    Raise KeyError if no entry matched.
    
    Usage: capi.get_type_info(discriminator)
    """
    if discriminator is None:
        m = "type_info._get discriminator is None"
        log.error(m)
        raise ValueError(m)
    discri = removeSecurityProxy(discriminator)
    getter = None

    # !+IALCHEMISTCONTENT normalize trickier discriminator cases to type_key
    if IIModelInterface.providedBy(discri):
        discri = naming.type_key("table_schema_interface_name",
                                 discri.__name__)
    elif IInterface.providedBy(discri):
        discri = naming.type_key("model_interface_name", discri.__name__)
    elif type(discri) is type and issubclass(discri, domain.Entity):
        discri = naming.polymorphic_identity(discri)
    elif isinstance(discri, domain.Entity):
        discri = naming.polymorphic_identity(type(discri))

    if isinstance(discri, basestring):
        getter = _get_by_type_key
    #elif IInterface.providedBy(discri):
    #    getter = _get_by_interface
    #!+elif interfaces.IBungeniContent.implementedBy(discri):
    #elif issubclass(discri, domain.Entity):
    #    getter = _get_by_model
    #!+elif interfaces.IBungeniContent.providedBy(discri):
    #elif isinstance(discri, domain.Entity):
    #    getter = _get_by_instance
    elif IWorkflow.providedBy(discri):
        getter = _get_by_workflow
    elif IModelDescriptor.implementedBy(discri):
        getter = _get_by_descriptor_model

    if getter is not None:
        ti = getter(discri)
        if ti is not None:
            return ti
        else:
            m = "No type registered for discriminator: %r" % (discriminator)
    else:
        m = "Invalid type info lookup discriminator: %r" % (discriminator)
    from bungeni.ui.utils import debug
    log.debug(debug.interfaces(discriminator))
    log.debug(m)
    raise KeyError(m)
Ejemplo n.º 32
0
 def iface_index(item):
     iface = item._for or Interface
     if IInterface.providedBy(iface):
         return ifaces.index(iface)
     if isinstance(removeSecurityProxy(object), item._for):
         # directly specified for class, this goes first.
         return -1
     # no idea. This goes last.
     return max_key  # pragma: no cover
Ejemplo n.º 33
0
 def factory(self, *args):
     if not args:
         raise TypeError(
             'The omitted directive expects at least one argument.')
     form_interface = Interface
     if IInterface.providedBy(args[0]):
         form_interface = args[0]
         args = args[1:]
     return [(form_interface, field, self.value) for field in args]
Ejemplo n.º 34
0
def find_resource_by_type(resource, path, class_or_interface):
    context = find_resource(resource, path)
    if IInterface.providedBy(class_or_interface):
        test = class_or_interface.providedBy
    else:
        test = lambda arg: isinstance(arg, class_or_interface)
    if not test(context):
        raise KeyError('%r type is not %s' % (context, class_or_interface))
    return context
Ejemplo n.º 35
0
def getInterfaceAllDocs(interface):
    iface_id = '%s.%s' % (interface.__module__, interface.__name__)
    docs = [str(iface_id).lower(), str(interface.__doc__).lower()]

    if IInterface.providedBy(interface):
        for name in sorted(interface):
            docs.append(str(interface.getDescriptionFor(name).__doc__).lower())

    return '\n'.join(docs)
Ejemplo n.º 36
0
 def testImageBlobInterfaces(self):
     foo = self.folder[self.folder.invokeFactory('Image', 'foo')]
     self.assertTrue(atimage.IATImage.providedBy(foo), 'no IATImage?')
     self.assertTrue(atimage.IImageContent.providedBy(foo),
                     'no IImageContent?')
     self.assertTrue(IATBlobImage.providedBy(foo), 'no IATBlobImage?')
     if not IInterface.providedBy(Z2IATFile):  # this is zope < 2.12
         self.assertTrue(Z2IATImage.isImplementedBy(foo),
                         'no zope2 IATImage?')
         self.assertFalse(Z2IATFile.isImplementedBy(foo), 'zope2 IATFile?')
Ejemplo n.º 37
0
def applyTransformOnSuccess(event):
    """Apply the transform after a successful request
    """
    transformed = applyTransform(event.request)
    if transformed is not None:
        response = event.request.response

        # horrid check to deal with Plone 3/Zope 2.10, where this is still an old-style interface
        if ((IInterface.providedBy(IStreamIterator)
             and IStreamIterator.providedBy(transformed))
                or (not IInterface.providedBy(IStreamIterator)
                    and IStreamIterator.isImplementedBy(transformed))):
            response.setBody(transformed)
        # setBody() can deal with byte and unicode strings (and will encode as necessary)...
        elif isinstance(transformed, basestring):
            response.setBody(transformed)
        # ... but not with iterables
        else:
            response.setBody(''.join(transformed))
Ejemplo n.º 38
0
def _get_base_ifaces(iface: IInterface, root_iface=Interface) -> [str]:
    bases = []
    current_bases = iface.getBases()
    while current_bases:
        old_bases = deepcopy(current_bases)
        current_bases = ()
        for base in old_bases:
            if base.extends(root_iface):
                bases.append(base.__identifier__)
            current_bases += base.getBases()
    return bases
 def test_w_name_wo_ifact_type(self):
     from zope.interface import Interface
     from zope.interface.interfaces import IInterface
     from zope.component.globalregistry import getGlobalSiteManager
     gsm = getGlobalSiteManager()
     class IFoo(Interface):
         pass
     self._callFUT('foo', IFoo)
     self.assertTrue(IInterface.providedBy(IFoo))
     registered = gsm.getUtility(IInterface, name='foo')
     self.assertIs(registered, IFoo)
Ejemplo n.º 40
0
    def class_or_interface_extends_validator(directive_name, value):

        if IInterface.providedBy(value):
            if not value.isOrExtends(extension_core):
                raise validator.GrokkerValidationError(
                    "%r is not a valid `%s` interface." %
                    (value, extension_core.__name__))
        elif not extension_core.implementedBy(value):
            raise validator.GrokkerValidationError(
                "%r must implement the `%s` interface." %
                (value, extension_core.__name__))
Ejemplo n.º 41
0
def get_dotted_name(ob: ResolvableType) -> str:
    """
    Convert a module/class/function to dotted path string

    :param ob: the object you'd like to convert
    """
    if inspect.isclass(ob) or IInterface.providedBy(ob) or isinstance(ob, types.FunctionType):
        name = ob.__name__
    else:
        name = ob.__class__.__name__
    return ob.__module__ + "." + name
Ejemplo n.º 42
0
def _get_post_pool(context: IPool, iresource_or_service_name) -> IResource:
    if IInterface.providedBy(iresource_or_service_name):
        post_pool = find_interface(context, iresource_or_service_name)
    else:
        post_pool = find_service(context, iresource_or_service_name)
    if post_pool is None:
        context_path = resource_path(context)
        post_pool_type = str(iresource_or_service_name)
        msg = 'Cannot find post_pool with interface or service name {}'\
              ' for context {}.'.format(post_pool_type, context_path)
        raise RuntimeConfigurationError(msg)
    return post_pool
Ejemplo n.º 43
0
def schema_indexes(context):
    if IField.providedBy(context):
        _index_types = schema_index_types(context)
        _name = lambda idx, n: '%s_%s' % (idx, n)
        name = context.__name__
        return tuple(_name(idx, name) for idx in _index_types)
    if IInterface.providedBy(context):
        r = []
        for name, field in getFieldsInOrder(context):
            r += list(schema_indexes(field))
        return tuple(r)
    raise ValueError('context must be interface or field')
Ejemplo n.º 44
0
def get_auto_fields(context):
    """Get the form fields for context.
    """
    # for an interface context, we generate them from that interface
    if IInterface.providedBy(context):
        return zope.formlib.form.Fields(context)
    # if we have a non-interface context, we're autogenerating them
    # from any schemas defined by the context
    fields = zope.formlib.form.Fields(*most_specialized_interfaces(context))
    # we pull in this field by default, but we don't want it in our form
    fields = fields.omit('__name__')
    return fields
Ejemplo n.º 45
0
 def __init__(self, interface, *interfaces):
     """
     :param interface: interface or class of resource
     :param interfaces: addition interfaces or classes of resource
     """
     self.interfaces = set(interfaces)
     self.interfaces.add(interface)
     self._validators = []
     for class_or_interface in self.interfaces:
         if IInterface.providedBy(class_or_interface):
             self._validators.append(class_or_interface.providedBy)
         else:
             self._validators.append(lambda arg: isinstance(arg, class_or_interface))
Ejemplo n.º 46
0
    def get_sheet(self, context: object, isheet: IInterface) -> ISheet:
        """Get sheet for `context` and set the 'context' attribute.

        :raise adhocracy_core.exceptions.RuntimeConfigurationError:
           if there is no `isheet` sheet registered for context.
        """
        if not isheet.providedBy(context):
            msg = 'Sheet {0} is not provided by resource {1}'\
                .format(isheet.__identifier__, resource_path(context))
            raise RuntimeConfigurationError(msg)
        meta = self.sheets_meta[isheet]
        sheet = meta.sheet_class(meta, context, self.registry)
        return sheet
Ejemplo n.º 47
0
    def factory(self, factory, adapts=None, provides=None, name=None):
        if provides is not None and not IInterface.providedBy(provides):
            raise GrokImportError(
                "You can only pass an interface to the "
                "provides argument of %s." % self.name)
        if adapts is None:
            adapts = getattr(factory, '__component_adapts__', None)
        elif not isinstance(adapts, (list, tuple,)):
            adapts = (adapts,)
        elif isinstance(adapts, list):
            adapts = tuple(adapts)

        return (factory, adapts, provides, name)
Ejemplo n.º 48
0
def flatten_interfaces(args):
    result = []
    for a in args:
        if isinstance(a, (list, tuple)):
            result.extend(flatten_interfaces(a))
        elif IInterface.providedBy(a):
            result.append(a)
        else:
            log.warning('  replacing %s with a placeholder', repr(a))
            result.append(
                InterfaceClass(a.__name__,
                               __module__='broken ' + a.__module__))
    return result
Ejemplo n.º 49
0
    def factory(self, *args):
        """The searchable directive accepts as arguments one or more
        fieldnames (string) of fields which should be searchable.
        """
        if not args:
            raise TypeError('The searchable directive expects at '
                            'least one argument.')

        form_interface = Interface
        if IInterface.providedBy(args[0]):
            form_interface = args[0]
            args = args[1:]
        return [(form_interface, field, self.value) for field in args]
Ejemplo n.º 50
0
    def manage_FTPget(self, REQUEST=None, RESPONSE=None):
        """Return the body of the content item in an FTP or WebDAV response.
        
        This adapts self to IRawReadFile(), which is then returned as an
        iterator. The adapter should provide IStreamIterator.
        """
        reader = IRawReadFile(self, None)
        if reader is None:
            return ''

        request = REQUEST is not None and REQUEST or self.REQUEST
        response = RESPONSE is not None and RESPONSE or request.response

        mimeType = reader.mimeType
        encoding = reader.encoding

        if mimeType is not None:
            if encoding is not None:
                response.setHeader('Content-Type', '%s; charset="%s"' % (
                    mimeType,
                    encoding,
                ))
            else:
                response.setHeader('Content-Type', mimeType)

        size = reader.size()
        if size is not None:
            response.setHeader('Content-Length', str(size))

        # if the reader is an iterator that the publisher can handle, return
        # it as-is. Otherwise, read the full contents

        if ((IInterface.providedBy(IStreamIterator)
             and IStreamIterator.providedBy(reader))
                or (not IInterface.providedBy(IStreamIterator)
                    and IStreamIterator.isImplementedBy(reader))):
            return reader
        else:
            return reader.read()
Ejemplo n.º 51
0
def set_registry_record(name=None, value=None, interface=None):
    """Set a record value in the ``plone.app.registry``

    :param name: [required] Name of the record
    :type name: string
    :param value: [required] Value to set
    :type value: python primitive
    :param interface: interface whose attributes are plone.app.registry
        settings
    :type interface: zope.interface.Interface
    :Example: :ref:`portal_set_registry_record_example`
    """
    if not isinstance(name, str):
        raise InvalidParameterError(u"The parameter 'name' has to be a string")

    if interface is not None and not IInterface.providedBy(interface):
        raise InvalidParameterError(
            u'The interface parameter has to derive from '
            u'zope.interface.Interface',
        )

    registry = getUtility(IRegistry)

    if interface is not None:
        # confirm that the name exists on the interface
        get_registry_record(name=name, interface=interface)

        from zope.schema._bootstrapinterfaces import WrongType
        try:
            registry[interface.__identifier__ + '.' + name] = value
        except WrongType:
            field_type = [
                field[1]
                for field in interface.namesAndDescriptions()
                if field[0] == 'field_one'
            ][0]
            raise InvalidParameterError(
                u'The value parameter for the field {name} needs to be '
                u'{of_class} instead of {of_type}'.format(
                    name=name,
                    of_class=str(field_type.__class__),
                    of_type=type(value),
                ),
            )

    elif isinstance(name, str):

        # confirm that the record exists before setting the value
        get_registry_record(name)

        registry[name] = value
Ejemplo n.º 52
0
 def get_all_addables(self, require=None):
     if require is not None:
         if IInterface.providedBy(require):
             requires = [
                 require,
             ]
         else:
             requires = require
     else:
         requires = list(self.REQUIRES)
     return map(
         operator.itemgetter('name'),
         filter(self._is_installed,
                extensionRegistry.get_addables(requires=requires)))
Ejemplo n.º 53
0
 def _getDirectMarkersOf(self, base):
     """Get empty interfaces directly inheriting from the given one.
     """
     results = []
     interfaces = searchInterface(None, base=base)
     for interface in interfaces:
         # There are things registered with the interface service
         # that are not interfaces. Yay!
         if not IInterface.providedBy(interface):
             continue
         if base in interface.__bases__ and not interface.names():
             results.append(interface)
     results.sort()
     return tuple(results)
Ejemplo n.º 54
0
def get_registry_record(name=None, interface=None):
    """Get a record value from ``plone.app.registry``

    :param name: [required] Name
    :type name: string
    :param interface: interface whose attributes are plone.app.registry
        settings
    :type interface: zope.interface.Interface
    :returns: Registry record value
    :rtype: plone.app.registry registry record
    :Example: :ref:`portal_get_registry_record_example`
    """
    if not isinstance(name, str):
        raise InvalidParameterError(u"The 'name' parameter has to be a string")

    if interface is not None and not IInterface.providedBy(interface):
        raise InvalidParameterError(
            u"The interface parameter has to derive from "
            u"zope.interface.Interface")

    registry = getUtility(IRegistry)

    if interface is not None:
        records = registry.forInterface(interface)
        _marker = object()
        if getattr(records, name, _marker) == _marker:
            # Show all records on the interface.
            records = [key for key in interface.names()]
            raise InvalidParameterError(
                "Cannot find a record with name '{0}' on interface {1}.\n"
                'Did you mean?'
                '{2}'.format(name, interface.__identifier__,
                             '\n'.join(records)))
        return registry['{0}.{1}'.format(interface.__identifier__, name)]

    if name not in registry:
        # Show all records that 'look like' name.
        # We don't dump the whole list, because it 1500+ items.
        records = [key for key in registry.records.keys() if name in key]
        if records:
            raise InvalidParameterError(
                "Cannot find a record with name '{0}'.\n"
                'Did you mean?:\n'
                '{1}'.format(name, '\n'.join(records)))
        else:
            raise InvalidParameterError(
                "Cannot find a record with name '{0}'".format(name))

    return registry[name]
Ejemplo n.º 55
0
    def factory(self,
                factory,
                provides=None,
                name=u'',
                setup=None,
                public=False,
                name_in_container=None):
        if provides is not None and not IInterface.providedBy(provides):
            raise GrokImportError("You can only pass an interface to the "
                                  "provides argument of %s." % self.name)

        if provides is None:
            # We cannot bind the provides directive and get information
            # from the factory, so we do it "manually" as we know how
            # to get to the information.
            dotted = grokcore.component.provides.dotted_name()
            provides = getattr(factory, dotted, None)

        if provides is None:
            if util.check_subclass(factory, LocalUtility):
                baseInterfaces = interface.implementedBy(LocalUtility)
                utilityInterfaces = interface.implementedBy(factory)
                provides = list(utilityInterfaces - baseInterfaces)

                if len(provides) == 0 and len(list(utilityInterfaces)) > 0:
                    raise GrokImportError(
                        "Cannot determine which interface to use "
                        "for utility registration of %r. "
                        "It implements an interface that is a specialization "
                        "of an interface implemented by grok.LocalUtility. "
                        "Specify the interface by either using grok.provides "
                        "on the utility or passing 'provides' to "
                        "grok.local_utility." % factory, factory)
            else:
                provides = list(interface.implementedBy(factory))

            util.check_implements_one_from_list(provides, factory)
            provides = provides[0]

        if (provides, name) in self.frame.f_locals.get(self.dotted_name(), {}):
            raise GrokImportError(
                "Conflicting local utility registration %r. "
                "Local utilities are registered multiple "
                "times for interface %r and name %r." %
                (factory, provides, name), factory)

        info = LocalUtilityInfo(factory, provides, name, setup, public,
                                name_in_container)
        return (provides, name), info
Ejemplo n.º 56
0
def _all_the_things(context, portal_type=None, iface=None):
    if not (iface or portal_type):
        raise ValueError('must provide either portal_type or iface')
    if IInterface.providedBy(iface):
        iface = iface.__identifier__
    site = getSite()
    query = {}
    if portal_type:
        query['portal_type'] = portal_type
    if iface:
        query['object_provides'] = iface
    if context is not site:
        query.update({'path': '/'.join(context.getPhysicalPath())})
    r = site.portal_catalog.unrestrictedSearchResults(query)
    _all_but_context = lambda o: aq_base(o) is not aq_base(context)
    return filter(_all_but_context, [b._unrestrictedGetObject() for b in r])
Ejemplo n.º 57
0
class MockField:
    if IInterface.providedBy(IField):
        implements(IField)
    else:
        __implements__ = IField
    type = "mock"

    def __init__(self, name="MockField", schemata="default"):
        self.name = name
        self.schemata = schemata

    def toString(self):
        return "MockField"

    def getName(self):
        return self.name
Ejemplo n.º 58
0
 def __init__(self, *args):
     buttons = []
     for arg in args:
         if IInterface.providedBy(arg):
             for name, button in getFieldsInOrder(arg):
                 if IButton.providedBy(button):
                     buttons.append((name, button))
         elif self.manager_interface.providedBy(arg):
             buttons += arg.items()
         elif IButton.providedBy(arg):
             if not arg.__name__:
                 arg.__name__ = create_id(arg.title)
             buttons.append((arg.__name__, arg))
         else:
             raise TypeError("Unrecognized argument type", arg)
     super().__init__(buttons)
Ejemplo n.º 59
0
class BlobStreamIterator(object):
    """ a streamiterator for blobs enabling to directly serve them
        in an extra ZServer thread """
    if IInterface.providedBy(IStreamIterator):  # is this zope 2.12?
        implements(IStreamIterator)
    else:
        __implements__ = (IStreamIterator, )

    def __init__(self, blob, mode='r', streamsize=1 << 16, start=0, end=None):
        self.blob = openBlob(blob, mode)
        self.streamsize = streamsize
        self.start = start
        self.end = end
        self.seek(start, 0)

    def next(self):
        """ return next chunk of data from the blob, taking the optionally
            given range into consideration """
        if self.end is None:
            bytes = self.streamsize
        else:
            bytes = max(min(self.end - self.tell(), self.streamsize), 0)
        data = self.blob.read(bytes)
        if not data:
            raise StopIteration
        return data

    def __len__(self):
        return fstat(self.blob.fileno()).st_size

    def __iter__(self):
        return self

    # bbb methods to pretend we're a file-like object

    def close(self):
        return self.blob.close()

    def read(self, *args, **kw):
        return self.blob.read(*args, **kw)

    def seek(self, *args, **kw):
        return self.blob.seek(*args, **kw)

    def tell(self):
        return self.blob.tell()
Ejemplo n.º 60
0
def find_interface(resource, class_or_interface):
    """
    Return the first resource found in the :term:`lineage` of ``resource``
    which, a) if ``class_or_interface`` is a Python class object, is an
    instance of the class or any subclass of that class or b) if
    ``class_or_interface`` is a :term:`interface`, provides the specified
    interface.  Return ``None`` if no resource providing ``interface_or_class``
    can be found in the lineage.  The ``resource`` passed in *must* be
    :term:`location`-aware.
    """
    if IInterface.providedBy(class_or_interface):
        test = class_or_interface.providedBy
    else:
        test = lambda arg: isinstance(arg, class_or_interface)
    for location in lineage(resource):
        if test(location):
            return location