Esempio n. 1
0
class ModelLookup(object):
    """Looks up a model using consumers.
    """

    def __init__(self):
        self._reg = AdapterRegistry()

    def register(self, class_or_interface, consumer):
        """Registers a new consumer.
        """
        source = (_get_interface(class_or_interface),)
        self._reg.subscribe(source, IConsumer, consumer)

    def lookup(self, obj):
        """Get all consumers.
        """
        provided = (providedBy(obj),)
        return self._reg.subscriptions(provided, IConsumer)

    def __call__(self, request, obj, stack):
        """Traverses following stack components and starting from obj.
        """
        unconsumed = stack[:]
        while unconsumed:
            for consumer in self.lookup(obj):
                any_consumed, obj, unconsumed = consumer(request, obj, unconsumed)
                if any_consumed:
                    break
            else:
                # nothing could be consumed
                return obj, unconsumed
        return obj, unconsumed
Esempio n. 2
0
class ComponentMap(dict): 
	def __init__(self, *args): 
		self.registry = AdapterRegistry()
		self.all_components = set() 
		dict.__init__(self, *args)

	def __setitem__(self, k, v):
		raise "Unsupported"
	
	def register(self, cls, *args, **kwargs):
		if cls in self:
			raise AlreadyRegistered, cls
	
		instance = cls(*args, **kwargs)	
		instance.set_enabled(True)
		instance.set_component_map(self)
		dict.__setitem__(self, cls, instance)

	def __delitem__(self, k): 
		v = self[k]
		v.set_component_map(None)
		v.set_enabled(False) 
		super(ComponentMap, self).__delitem__(cls)

	def subscribe(self, listener, listenerinterface, notifier):
		self.registry.subscribe([listenerinterface], notifier, self[listener])
	
	def subscriptions(self, notifier, listenerinterface):		
		return self.registry.subscriptions([listenerinterface], notifier)
Esempio n. 3
0
    def register(self, interface, name, factory):
        r = self._registry.get(name)
        if r is None:
            r = AdapterRegistry()
            self._registry[name] = r

        r.register([interface], Interface, '', factory)
Esempio n. 4
0
class Registry(object):
    def __init__(self):
        self.registry = AdapterRegistry()

    def register(self, sources, target, name, component):
        iface_sources = []
        for source in sources:
            if ISpecification.providedBy(source):
                iface_sources.append(source)
                continue
            if isinstance(source, CLASS_TYPES):
                iface_sources.append(implementedBy(source))
            else:
                raise TypeError("Sources must either be "
                                "an interface or a class.")
        self.registry.register(iface_sources, target, name, component)

    def lookup(self, obs, target, name):
        return self.registry.lookup(map(providedBy, obs), target, name)

    def adapt(self, obs, target, name):
        # self-adaptation
        if len(obs) == 1 and target.providedBy(obs[0]):
            return obs[0]
        adapter = self.lookup(obs, target, name)
        if adapter is None:
            return None
        try:
            return adapter(*obs)
        except TypeError, e:
            raise TypeError(str(e) + " (%s)" % adapter)
Esempio n. 5
0
class ModelLookup(object):
    """Looks up a model using consumers.
    """
    def __init__(self):
        self._reg = AdapterRegistry()

    def register(self, class_or_interface, consumer):
        """Registers a new consumer.
        """
        source = (_get_interface(class_or_interface), )
        self._reg.subscribe(source, IConsumer, consumer)

    def lookup(self, obj):
        """Get all consumers.
        """
        provided = (providedBy(obj), )
        return self._reg.subscriptions(provided, IConsumer)

    def __call__(self, request, obj, stack):
        """Traverses following stack components and starting from obj.
        """
        unconsumed = copy(stack)  # using copy. py3.5+ can use stack.copy()
        while unconsumed:
            for consumer in self.lookup(obj):
                any_consumed, obj, unconsumed = consumer(
                    request, obj, unconsumed)
                if any_consumed:
                    break
            else:
                # nothing could be consumed
                return obj, unconsumed
        return obj, unconsumed
Esempio n. 6
0
class Registry(object):
    """
    Proxy class for managing Utility and Adapter registries
    """
    utilities = AdapterRegistry()
    adapters = AdapterRegistry()

    @classmethod
    def add_adapter(cls, *args, **kwargs):
        """
        Wrapper for zope.interface.AdapterRegistry.register
        """
        cls.adapters.register(*args, **kwargs)

    @classmethod
    def subscribe(cls, interface, obj):
        """
        Register a subscription of an object for a given interface

        :param interface: Target interface
        :param obj: object
        """
        cls.utilities.subscribe([], interface, obj)

    @classmethod
    def add_utility(cls, interface, obj, name=''):
        """
        Register an object as a utility for a given interface

        :param interface:
        :param obj: utility
        :param name: optional name for utility
        """
        cls.utilities.register([], interface, name, obj)

    @classmethod
    def get_utility(cls, interface, name=''):
        """
        Fetch the utility which provides a given interface

        :param interface:
        :param name: optional name for utility
        :return: utility
        """
        return cls.utilities.lookup([], interface, name)

    @classmethod
    def get_subscribers(cls, interface):
        """
        Fetch all subscribers for a given interface

        :param interface:
        :return: list of subscribers
        """
        return cls.utilities.subscriptions([], interface)
Esempio n. 7
0
class Registry(object):

    def __init__(self):
        self.behaviors = AdapterRegistry()
        self.behaviornames = {}
        self.schemas = AdapterRegistry()
        self.schemanames = {}

    def querySchema(self, schema, default=None):
        if isinstance(schema, basestring):
            return self.schemanames.get(schema, default)

        return self.schemas.lookup((ISchema,), schema, default=default)

    def queryBehavior(self, provided, spec, default=None):
        if isinstance(provided, basestring):
            return self.behaviornames.get(provided, default)

        if isinstance(provided, InterfaceClass):
            provided = (provided,)

        return self.behaviors.lookup(provided, spec, default=default)

    def registerSchema(self, schema):
        self.schemas.register((ISchema,), schema.spec, '', schema)
        self.schemanames[schema.name] = schema

    def registerBehavior(self, behavior):
        self.behaviors.register((behavior.spec,), IBehavior, '', behavior)
        self.behaviors.register((behavior.spec,), behavior.spec, '', behavior)
        self.behaviornames[behavior.name] = behavior
Esempio n. 8
0
def test_deregister(monkeypatch):
    monkeypatch.setattr(adapterutil, "registry", AdapterRegistry())

    class IFrom(Interface):
        pass

    @implementer(IFrom)
    class From(object):
        pass

    class ITo(Interface):
        pass

    class To(object):
        def __init__(self, from_obj):
            self.from_obj = from_obj

    adapterutil.register(To, From, ITo)

    from_obj = From()
    assert isinstance(ITo(from_obj), To)

    adapterutil.deregister(To, From, ITo)

    with pytest.raises(TypeError):
        ITo(from_obj)
Esempio n. 9
0
def stackConfigurationContext(context=None, name='not named'):
    """Return a new ``ConfigurationMachine`` configuration context that
    is a clone of the passed-in context. If no context is passed in, a fresh
    configuration context is returned.
    """

    from copy import deepcopy

    from zope.interface import Interface
    from zope.interface.adapter import AdapterRegistry

    from zope.configuration.xmlconfig import registerCommonDirectives

    clone = NamedConfigurationMachine(name)

    # Prime this so that the <meta:redefinePermission /> directive won't lose
    # track of it across our stacked configuration machines
    clone.permission_mapping = {}

    if context is None:
        registerCommonDirectives(clone)
        logger.debug('New configuration context %s', clone)
        return clone

    # Copy over simple attributes
    clone.info = deepcopy(context.info)
    clone.i18n_strings = deepcopy(context.i18n_strings)
    clone.package = deepcopy(context.package)
    clone.basepath = deepcopy(context.basepath)
    clone.includepath = deepcopy(context.includepath)

    clone._seen_files = deepcopy(context._seen_files)
    clone._features = deepcopy(context._features)

    try:
        clone.permission_mapping = deepcopy(context.permission_mapping)
    except AttributeError:
        pass

    # Note: We don't copy ``stack`` or ``actions`` since these are used during
    # ZCML file processing only

    # Copy over documentation registry
    clone._docRegistry = [tuple(list(entry))for entry in context._docRegistry]

    # Copy over the directive registry
    for key, registry in context._registry.items():
        newRegistry = clone._registry.setdefault(key, AdapterRegistry())
        for adapterRegistration in registry._adapters:
            if adapterRegistration not in newRegistry._adapters:
                for interface, info in adapterRegistration.items():
                    if Interface in info:
                        factory = info[Interface][u'']
                        newRegistry.register([interface], Interface, '',
                                             factory)

    logger.debug('Configuration context %s cloned from %s', clone, context)
    return clone
Esempio n. 10
0
class Handlers:
    """Action Handlers for a Button-based form."""

    def __init__(self):
        self._registry = AdapterRegistry()
        self._handlers = ()

    def add_handler(self, button, handler):  # pylint: disable=redefined-outer-name
        """See interfaces.button.IButtonHandlers"""
        # Create a specification for the button
        button_spec = get_specification(button)
        if isinstance(button_spec, class_types):
            button_spec = implementedBy(button_spec)
        # Register the handler
        self._registry.register(
            (button_spec,), IButtonHandler, '', handler)
        self._handlers += ((button, handler),)

    def get_handler(self, button):
        """See interfaces.button.IButtonHandlers"""
        button_provided = providedBy(button)
        # pylint: disable=no-member
        return self._registry.lookup1(button_provided, IButtonHandler)

    def copy(self):
        """See interfaces.button.IButtonHandlers"""
        handlers = Handlers()
        for button, handler in self._handlers:  # pylint: disable=redefined-outer-name
            handlers.add_handler(button, handler)
        return handlers

    def __add__(self, other):
        """See interfaces.button.IButtonHandlers"""
        if not isinstance(other, Handlers):
            raise NotImplementedError
        handlers = self.copy()
        for button, handler in other._handlers:  # pylint: disable=redefined-outer-name
            handlers.add_handler(button, handler)
        return handlers

    def __repr__(self):
        # pylint: disable=redefined-outer-name
        return '<Handlers %r>' % [handler for button, handler in self._handlers]
Esempio n. 11
0
def includeme(config):
    config.add_request_method(find_model)
    config.add_request_method(
        lambda _: AdapterRegistry(),
        'service_cache',
        reify=True,
    )

    config.add_directive('register_model', register_model)
    config.add_directive('register_model_factory', register_model_factory)
Esempio n. 12
0
    def _makeOneRequest(self):
        from pyramid_services import find_service
        from zope.interface.adapter import AdapterRegistry
        import types

        request = DummyRequest()
        request.find_service = types.MethodType(find_service, request)
        request.registry = self.config.registry
        request.service_cache = AdapterRegistry()

        return request
Esempio n. 13
0
def _registryAdapting(*fromToAdapterTuples):
    """
    Construct a Zope Interface adapter registry.

    For example, if you want to construct an adapter registry that can convert
    C{IFoo} to C{IBar} with C{fooToBar}.

    @param fromToAdapterTuples: A sequence of tuples of C{(fromInterface,
        toInterface, adapterCallable)}, where C{fromInterface} and
        C{toInterface} are L{Interface}s, and C{adapterCallable} is a callable
        that takes one argument which provides C{fromInterface} and returns an
        object providing C{toInterface}.
    @type fromToAdapterTuples: C{tuple} of 3-C{tuple}s of C{(Interface,
        Interface, callable)}

    @rtype: L{AdapterRegistry}
    """
    result = AdapterRegistry()
    for From, to, adapter in fromToAdapterTuples:
        result.register([From], to, '', adapter)
    return result
Esempio n. 14
0
    def __get__(self, inst, cls=None):
        if inst is None:
            return getObjectSpecification(cls)

        tp = inst.__type__
        cached = getattr(tp, '_v__providedBy', _marker)
        if cached is not _marker:
            return cached

        provided = [implementedBy(inst.__class__)]
        bhreg = AdapterRegistry()
        for behavior in tp.behaviors:
            behavior = queryBehavior(behavior)
            if behavior is not None:
                bhreg.register((), behavior.spec, '', behavior)
                provided.append(behavior.spec)

        schreg = AdapterRegistry()
        for schId in tp.schemas:
            sch = querySchema(schId)
            if sch is not None and sch.spec not in provided:
                schreg.register((), sch.spec, '', sch)
                provided.append(sch.spec)

        spec = Implements(*provided)

        tp._v__providedBy = spec
        tp._v__bhCache = bhreg
        tp._v__schCache = schreg

        return spec
Esempio n. 15
0
def _registryAdapting(*fromToAdapterTuples):
    """
    Construct a Zope Interface adapter registry.

    For example, if you want to construct an adapter registry that can convert
    C{IFoo} to C{IBar} with C{fooToBar}.

    @param fromToAdapterTuples: A sequence of tuples of C{(fromInterface,
        toInterface, adapterCallable)}, where C{fromInterface} and
        C{toInterface} are L{IInterface}s, and C{adapterCallable} is a callable
        that takes one argument which provides C{fromInterface} and returns an
        object providing C{toInterface}.
    @type fromToAdapterTuples: C{tuple} of 3-C{tuple}s of C{(Interface,
        Interface, callable)}

    @return: an adapter registry adapting the given tuples.
    @rtype: L{AdapterRegistry}
    """
    result = AdapterRegistry()
    for _from, to, adapter in fromToAdapterTuples:
        result.register([_from], to, '', adapter)
    return result
Esempio n. 16
0
def test_fakeimplementor(monkeypatch):
    monkeypatch.setattr(adapterutil, "registry", AdapterRegistry())

    class ITo(Interface):
        pass

    @implementer(ITo)
    def convert(obj):
        return str(obj)

    adapterutil.register(convert, int)

    assert ITo(5) == "5"
Esempio n. 17
0
 def setUp(self):
     """
     Configure L{twisted.python.components.registerAdapter} to mutate an
     alternate registry to improve test isolation.
     """
     # Create a brand new, empty registry and put it onto the components
     # module where registerAdapter will use it.  Also ensure that it goes
     # away at the end of the test.
     scratchRegistry = AdapterRegistry()
     self.patch(components, 'globalRegistry', scratchRegistry)
     # Hook the new registry up to the adapter lookup system and ensure that
     # association is also discarded after the test.
     hook = _addHook(scratchRegistry)
     self.addCleanup(_removeHook, hook)
Esempio n. 18
0
class Registry(object):
    """A base component registry.
    """

    def __init__(self):
        self.registry = AdapterRegistry()

    def register(self, sources, target, name, component):
        required = interfaces(sources)
        self.registry.register(required, target, name, component)

    def subscribe(self, sources, target, component):
        required = interfaces(sources)
        self.registry.subscribe(required, target, component)

    def lookup(self, obs, target, name):
        return self.registry.lookup(map(providedBy, obs), target, name)

    def cls_lookup(self, classes, target, name):
        return self.registry.lookup(map(implementedBy, classes), target, name)

    def lookup_all(self, obs, target):
        return iter(self.registry.lookupAll(list(map(providedBy, obs)), target))

    def subscriptions(self, obs, target):
        return self.registry.subscriptions(map(providedBy, obs), target)

    def predicates(self, classes, target):
        return self.registry.subscriptions(map(implementedBy, classes), target)

    def adapt(self, obs, target, name):
        # self-adaptation
        if len(obs) == 1 and target.providedBy(obs[0]):
            return obs[0]
        adapter = self.lookup(obs, target, name)
        if adapter is None:
            return None
        try:
            return adapter(*obs)
        except TypeError as e:
            raise TypeError(str(e) + " (%s)" % adapter)
def dummy_request(extra_environ):  # type (dict) -> Request
    from pyramid import testing
    from pyramid_services import find_service
    from zope.interface.adapter import AdapterRegistry

    locale_name = 'en'
    req = testing.DummyRequest(subdomain='',
                               environ=extra_environ,
                               _LOCALE_=locale_name,
                               locale_name=locale_name,
                               matched_route=None)

    # for service objects
    req.service_cache = AdapterRegistry()
    req.find_service = (
        lambda *args, **kwargs: find_service(req, *args, **kwargs))
    return req
Esempio n. 20
0
def _register_adapters(config):
    settings = config.registry.settings
    adapter_registry = AdapterRegistry()

    # TODO (Guilherme Pereira): abstract this block of code to avoid its pattern repetition
    list_of_identity_adapters = aslist(settings["keyloop.identity_sources"])
    for adapter_description in list_of_identity_adapters:
        realm, identity_source_name = adapter_description.split(":")

        adapter_registry.register([identity.IIdentity],
                                  identity.IIdentitySource, realm,
                                  config.maybe_dotted(identity_source_name))
        logger.debug("Registered IIdentitySource adapter for realm '%s'",
                     realm)

    list_of_auth_session_adapters = aslist(
        settings["keyloop.auth_session_sources"])
    for adapter_description in list_of_auth_session_adapters:
        realm, auth_session_source_name = adapter_description.split(":")

        adapter_registry.register(
            [auth_session.IAuthSession], auth_session.IAuthSessionSource,
            realm, config.maybe_dotted(auth_session_source_name))
        logger.debug("Registered IAuthSessionSource adapter for realm '%s'",
                     realm)

    list_of_permission_adapters = aslist(
        settings["keyloop.permission_sources"])
    for adapter_description in list_of_permission_adapters:
        realm, permission_source_name = adapter_description.split(":")

        adapter_registry.register([permission.IPermission],
                                  permission.IPermissionSource, realm,
                                  config.maybe_dotted(permission_source_name))
        logger.debug("Registered IPermissionSource adapter for realm '%s'",
                     realm)

    config.registry.settings["keyloop_adapters"] = adapter_registry
Esempio n. 21
0
class TestRunner(object):
    def __init__(self):
        self.registry = AdapterRegistry()

    def scan(self, module):
        module = maybe_dotted(module)
        scanner = venusian.Scanner(runner=self)
        scanner.scan(module)

    def add_test(self, test, values=(), target=None, description=None):
        name = test.__name__
        description = description or test.__doc__
        case = TestCase(name, test, description, values=values, target=target)
        self.registry.register([], ITestCase, name, case)

    def get_tests(self):
        for test in self.registry.lookupAll([], ITestCase):
            yield test

    def run_tests(self):
        result = TextTestResult()
        for name, test in self.get_tests():
            test.run(result)
Esempio n. 22
0
def test_simple(monkeypatch):
    monkeypatch.setattr(adapterutil, "registry", AdapterRegistry())

    class IFrom(Interface):
        pass

    @implementer(IFrom)
    class From(object):
        pass

    class ITo(Interface):
        pass

    class To(object):
        def __init__(self, from_obj):
            self.from_obj = from_obj

    adapterutil.register(To, From, ITo)

    from_obj = From()
    result = ITo(from_obj)
    assert isinstance(result, To)
    assert result.from_obj is from_obj
Esempio n. 23
0
class Components(object):

    _v_utility_registrations_cache = None

    def __init__(self, name='', bases=()):
        # __init__ is used for test cleanup as well as initialization.
        # XXX add a separate API for test cleanup.
        assert isinstance(name, STRING_TYPES)
        self.__name__ = name
        self._init_registries()
        self._init_registrations()
        self.__bases__ = tuple(bases)
        self._v_utility_registrations_cache = None

    def __repr__(self):
        return "<%s %s>" % (self.__class__.__name__, self.__name__)

    def __reduce__(self):
        # Mimic what a persistent.Persistent object does and elide
        # _v_ attributes so that they don't get saved in ZODB.
        # This allows us to store things that cannot be pickled in such
        # attributes.
        reduction = super(Components, self).__reduce__()
        # (callable, args, state, listiter, dictiter)
        # We assume the state is always a dict; the last three items
        # are technically optional and can be missing or None.
        filtered_state = {
            k: v
            for k, v in reduction[2].items() if not k.startswith('_v_')
        }
        reduction = list(reduction)
        reduction[2] = filtered_state
        return tuple(reduction)

    def _init_registries(self):
        # Subclasses have never been required to call this method
        # if they override it, merely to fill in these two attributes.
        self.adapters = AdapterRegistry()
        self.utilities = AdapterRegistry()

    def _init_registrations(self):
        self._utility_registrations = {}
        self._adapter_registrations = {}
        self._subscription_registrations = []
        self._handler_registrations = []

    @property
    def _utility_registrations_cache(self):
        # We use a _v_ attribute internally so that data aren't saved in ZODB,
        # because this object cannot be pickled.
        cache = self._v_utility_registrations_cache
        if (cache is None or cache._utilities is not self.utilities
                or cache._utility_registrations
                is not self._utility_registrations):
            cache = self._v_utility_registrations_cache = _UtilityRegistrations(
                self.utilities, self._utility_registrations)
        return cache

    def _getBases(self):
        # Subclasses might override
        return self.__dict__.get('__bases__', ())

    def _setBases(self, bases):
        # Subclasses might override
        self.adapters.__bases__ = tuple([base.adapters for base in bases])
        self.utilities.__bases__ = tuple([base.utilities for base in bases])
        self.__dict__['__bases__'] = tuple(bases)

    __bases__ = property(
        lambda self: self._getBases(),
        lambda self, bases: self._setBases(bases),
    )

    def registerUtility(self,
                        component=None,
                        provided=None,
                        name=u'',
                        info=u'',
                        event=True,
                        factory=None):
        if factory:
            if component:
                raise TypeError("Can't specify factory and component.")
            component = factory()

        if provided is None:
            provided = _getUtilityProvided(component)

        if name == u'':
            name = _getName(component)

        reg = self._utility_registrations.get((provided, name))
        if reg is not None:
            if reg[:2] == (component, info):
                # already registered
                return
            self.unregisterUtility(reg[0], provided, name)

        self._utility_registrations_cache.registerUtility(
            provided, name, component, info, factory)

        if event:
            notify(
                Registered(
                    UtilityRegistration(self, provided, name, component, info,
                                        factory)))

    def unregisterUtility(self,
                          component=None,
                          provided=None,
                          name=u'',
                          factory=None):
        if factory:
            if component:
                raise TypeError("Can't specify factory and component.")
            component = factory()

        if provided is None:
            if component is None:
                raise TypeError("Must specify one of component, factory and "
                                "provided")
            provided = _getUtilityProvided(component)

        old = self._utility_registrations.get((provided, name))
        if (old is None) or ((component is not None) and
                             (component != old[0])):
            return False

        if component is None:
            component = old[0]

        # Note that component is now the old thing registered
        self._utility_registrations_cache.unregisterUtility(
            provided, name, component)

        notify(
            Unregistered(
                UtilityRegistration(self, provided, name, component,
                                    *old[1:])))

        return True

    def registeredUtilities(self):
        for ((provided, name),
             data) in iter(self._utility_registrations.items()):
            yield UtilityRegistration(self, provided, name, *data)

    def queryUtility(self, provided, name=u'', default=None):
        return self.utilities.lookup((), provided, name, default)

    def getUtility(self, provided, name=u''):
        utility = self.utilities.lookup((), provided, name)
        if utility is None:
            raise ComponentLookupError(provided, name)
        return utility

    def getUtilitiesFor(self, interface):
        for name, utility in self.utilities.lookupAll((), interface):
            yield name, utility

    def getAllUtilitiesRegisteredFor(self, interface):
        return self.utilities.subscriptions((), interface)

    def registerAdapter(self,
                        factory,
                        required=None,
                        provided=None,
                        name=u'',
                        info=u'',
                        event=True):
        if provided is None:
            provided = _getAdapterProvided(factory)
        required = _getAdapterRequired(factory, required)
        if name == u'':
            name = _getName(factory)
        self._adapter_registrations[(required, provided, name)] = factory, info
        self.adapters.register(required, provided, name, factory)

        if event:
            notify(
                Registered(
                    AdapterRegistration(self, required, provided, name,
                                        factory, info)))

    def unregisterAdapter(
        self,
        factory=None,
        required=None,
        provided=None,
        name=u'',
    ):
        if provided is None:
            if factory is None:
                raise TypeError("Must specify one of factory and provided")
            provided = _getAdapterProvided(factory)

        if (required is None) and (factory is None):
            raise TypeError("Must specify one of factory and required")

        required = _getAdapterRequired(factory, required)
        old = self._adapter_registrations.get((required, provided, name))
        if (old is None) or ((factory is not None) and (factory != old[0])):
            return False

        del self._adapter_registrations[(required, provided, name)]
        self.adapters.unregister(required, provided, name)

        notify(
            Unregistered(
                AdapterRegistration(self, required, provided, name, *old)))

        return True

    def registeredAdapters(self):
        for ((required, provided, name),
             (component, info)) in iter(self._adapter_registrations.items()):
            yield AdapterRegistration(self, required, provided, name,
                                      component, info)

    def queryAdapter(self, object, interface, name=u'', default=None):
        return self.adapters.queryAdapter(object, interface, name, default)

    def getAdapter(self, object, interface, name=u''):
        adapter = self.adapters.queryAdapter(object, interface, name)
        if adapter is None:
            raise ComponentLookupError(object, interface, name)
        return adapter

    def queryMultiAdapter(self, objects, interface, name=u'', default=None):
        return self.adapters.queryMultiAdapter(objects, interface, name,
                                               default)

    def getMultiAdapter(self, objects, interface, name=u''):
        adapter = self.adapters.queryMultiAdapter(objects, interface, name)
        if adapter is None:
            raise ComponentLookupError(objects, interface, name)
        return adapter

    def getAdapters(self, objects, provided):
        for name, factory in self.adapters.lookupAll(
                list(map(providedBy, objects)), provided):
            adapter = factory(*objects)
            if adapter is not None:
                yield name, adapter

    def registerSubscriptionAdapter(self,
                                    factory,
                                    required=None,
                                    provided=None,
                                    name=u'',
                                    info=u'',
                                    event=True):
        if name:
            raise TypeError("Named subscribers are not yet supported")
        if provided is None:
            provided = _getAdapterProvided(factory)
        required = _getAdapterRequired(factory, required)
        self._subscription_registrations.append(
            (required, provided, name, factory, info))
        self.adapters.subscribe(required, provided, factory)

        if event:
            notify(
                Registered(
                    SubscriptionRegistration(self, required, provided, name,
                                             factory, info)))

    def registeredSubscriptionAdapters(self):
        for data in self._subscription_registrations:
            yield SubscriptionRegistration(self, *data)

    def unregisterSubscriptionAdapter(
        self,
        factory=None,
        required=None,
        provided=None,
        name=u'',
    ):
        if name:
            raise TypeError("Named subscribers are not yet supported")
        if provided is None:
            if factory is None:
                raise TypeError("Must specify one of factory and provided")
            provided = _getAdapterProvided(factory)

        if (required is None) and (factory is None):
            raise TypeError("Must specify one of factory and required")

        required = _getAdapterRequired(factory, required)

        if factory is None:
            new = [(r, p, n, f, i)
                   for (r, p, n, f, i) in self._subscription_registrations
                   if not (r == required and p == provided)]
        else:
            new = [(r, p, n, f, i)
                   for (r, p, n, f, i) in self._subscription_registrations
                   if not (r == required and p == provided and f == factory)]

        if len(new) == len(self._subscription_registrations):
            return False

        self._subscription_registrations[:] = new
        self.adapters.unsubscribe(required, provided, factory)

        notify(
            Unregistered(
                SubscriptionRegistration(self, required, provided, name,
                                         factory, '')))

        return True

    def subscribers(self, objects, provided):
        return self.adapters.subscribers(objects, provided)

    def registerHandler(self,
                        factory,
                        required=None,
                        name=u'',
                        info=u'',
                        event=True):
        if name:
            raise TypeError("Named handlers are not yet supported")
        required = _getAdapterRequired(factory, required)
        self._handler_registrations.append((required, name, factory, info))
        self.adapters.subscribe(required, None, factory)

        if event:
            notify(
                Registered(
                    HandlerRegistration(self, required, name, factory, info)))

    def registeredHandlers(self):
        for data in self._handler_registrations:
            yield HandlerRegistration(self, *data)

    def unregisterHandler(self, factory=None, required=None, name=u''):
        if name:
            raise TypeError("Named subscribers are not yet supported")

        if (required is None) and (factory is None):
            raise TypeError("Must specify one of factory and required")

        required = _getAdapterRequired(factory, required)

        if factory is None:
            new = [(r, n, f, i) for (r, n, f, i) in self._handler_registrations
                   if r != required]
        else:
            new = [(r, n, f, i) for (r, n, f, i) in self._handler_registrations
                   if not (r == required and f == factory)]

        if len(new) == len(self._handler_registrations):
            return False

        self._handler_registrations[:] = new
        self.adapters.unsubscribe(required, None, factory)

        notify(
            Unregistered(HandlerRegistration(self, required, name, factory,
                                             '')))

        return True

    def handle(self, *objects):
        self.adapters.subscribers(objects, None)

    def rebuildUtilityRegistryFromLocalCache(self, rebuild=False):
        """
        Emergency maintenance method to rebuild the ``.utilities``
        registry from the local copy maintained in this object, or
        detect the need to do so.

        Most users will never need to call this, but it can be helpful
        in the event of suspected corruption.

        By default, this method only checks for corruption. To make it
        actually rebuild the registry, pass `True` for *rebuild*.

        :param bool rebuild: If set to `True` (not the default),
           this method will actually register and subscribe utilities
           in the registry as needed to synchronize with the local cache.

        :return: A dictionary that's meant as diagnostic data. The keys
           and values may change over time. When called with a false *rebuild*,
           the keys ``"needed_registered"`` and ``"needed_subscribed"`` will be
           non-zero if any corruption was detected, but that will not be corrected.

        .. versionadded:: 5.3.0
        """
        regs = dict(self._utility_registrations)
        utils = self.utilities
        needed_registered = 0
        did_not_register = 0
        needed_subscribed = 0
        did_not_subscribe = 0

        # Avoid the expensive change process during this; we'll call
        # it once at the end if needed.
        assert 'changed' not in utils.__dict__
        utils.changed = lambda _: None

        if rebuild:
            register = utils.register
            subscribe = utils.subscribe
        else:
            register = subscribe = lambda *args: None

        try:
            for (provided, name), (value, _info, _factory) in regs.items():
                if utils.registered((), provided, name) != value:
                    register((), provided, name, value)
                    needed_registered += 1
                else:
                    did_not_register += 1

                if utils.subscribed((), provided, value) is None:
                    needed_subscribed += 1
                    subscribe((), provided, value)
                else:
                    did_not_subscribe += 1
        finally:
            del utils.changed
            if rebuild and (needed_subscribed or needed_registered):
                utils.changed(utils)

        return {
            'needed_registered': needed_registered,
            'did_not_register': did_not_register,
            'needed_subscribed': needed_subscribed,
            'did_not_subscribe': did_not_subscribe
        }
Esempio n. 24
0
class Components(object):

    _v_utility_registrations_cache = None

    def __init__(self, name='', bases=()):
        # __init__ is used for test cleanup as well as initialization.
        # XXX add a separate API for test cleanup.
        assert isinstance(name, STRING_TYPES)
        self.__name__ = name
        self._init_registries()
        self._init_registrations()
        self.__bases__ = tuple(bases)
        self._v_utility_registrations_cache = None

    def __repr__(self):
        return "<%s %s>" % (self.__class__.__name__, self.__name__)

    def __reduce__(self):
        # Mimic what a persistent.Persistent object does and elide
        # _v_ attributes so that they don't get saved in ZODB.
        # This allows us to store things that cannot be pickled in such
        # attributes.
        reduction = super(Components, self).__reduce__()
        # (callable, args, state, listiter, dictiter)
        # We assume the state is always a dict; the last three items
        # are technically optional and can be missing or None.
        filtered_state = {k: v for k, v in reduction[2].items()
                          if not k.startswith('_v_')}
        reduction = list(reduction)
        reduction[2] = filtered_state
        return tuple(reduction)

    def _init_registries(self):
        # Subclasses have never been required to call this method
        # if they override it, merely to fill in these two attributes.
        self.adapters = AdapterRegistry()
        self.utilities = AdapterRegistry()

    def _init_registrations(self):
        self._utility_registrations = {}
        self._adapter_registrations = {}
        self._subscription_registrations = []
        self._handler_registrations = []

    @property
    def _utility_registrations_cache(self):
        # We use a _v_ attribute internally so that data aren't saved in ZODB,
        # because this object cannot be pickled.
        cache = self._v_utility_registrations_cache
        if (cache is None
            or cache._utilities is not self.utilities
            or cache._utility_registrations is not self._utility_registrations):
            cache = self._v_utility_registrations_cache = _UtilityRegistrations(
                self.utilities,
                self._utility_registrations)
        return cache

    def _getBases(self):
        # Subclasses might override
        return self.__dict__.get('__bases__', ())

    def _setBases(self, bases):
        # Subclasses might override
        self.adapters.__bases__ = tuple([
            base.adapters for base in bases])
        self.utilities.__bases__ = tuple([
            base.utilities for base in bases])
        self.__dict__['__bases__'] = tuple(bases)

    __bases__ = property(
        lambda self: self._getBases(),
        lambda self, bases: self._setBases(bases),
        )

    def registerUtility(self, component=None, provided=None, name=u'',
                        info=u'', event=True, factory=None):
        if factory:
            if component:
                raise TypeError("Can't specify factory and component.")
            component = factory()

        if provided is None:
            provided = _getUtilityProvided(component)

        if name == u'':
            name = _getName(component)

        reg = self._utility_registrations.get((provided, name))
        if reg is not None:
            if reg[:2] == (component, info):
                # already registered
                return
            self.unregisterUtility(reg[0], provided, name)

        self._utility_registrations_cache.registerUtility(
            provided, name, component, info, factory)

        if event:
            notify(Registered(
                UtilityRegistration(self, provided, name, component, info,
                                    factory)
                ))

    def unregisterUtility(self, component=None, provided=None, name=u'',
                          factory=None):
        if factory:
            if component:
                raise TypeError("Can't specify factory and component.")
            component = factory()

        if provided is None:
            if component is None:
                raise TypeError("Must specify one of component, factory and "
                                "provided")
            provided = _getUtilityProvided(component)

        old = self._utility_registrations.get((provided, name))
        if (old is None) or ((component is not None) and
                             (component != old[0])):
            return False

        if component is None:
            component = old[0]

        # Note that component is now the old thing registered
        self._utility_registrations_cache.unregisterUtility(
            provided, name, component)

        notify(Unregistered(
            UtilityRegistration(self, provided, name, component, *old[1:])
            ))

        return True

    def registeredUtilities(self):
        for ((provided, name), data
             ) in iter(self._utility_registrations.items()):
            yield UtilityRegistration(self, provided, name, *data)

    def queryUtility(self, provided, name=u'', default=None):
        return self.utilities.lookup((), provided, name, default)

    def getUtility(self, provided, name=u''):
        utility = self.utilities.lookup((), provided, name)
        if utility is None:
            raise ComponentLookupError(provided, name)
        return utility

    def getUtilitiesFor(self, interface):
        for name, utility in self.utilities.lookupAll((), interface):
            yield name, utility

    def getAllUtilitiesRegisteredFor(self, interface):
        return self.utilities.subscriptions((), interface)

    def registerAdapter(self, factory, required=None, provided=None,
                        name=u'', info=u'', event=True):
        if provided is None:
            provided = _getAdapterProvided(factory)
        required = _getAdapterRequired(factory, required)
        if name == u'':
            name = _getName(factory)
        self._adapter_registrations[(required, provided, name)
                                    ] = factory, info
        self.adapters.register(required, provided, name, factory)

        if event:
            notify(Registered(
                AdapterRegistration(self, required, provided, name,
                                    factory, info)
                ))


    def unregisterAdapter(self, factory=None,
                          required=None, provided=None, name=u'',
                          ):
        if provided is None:
            if factory is None:
                raise TypeError("Must specify one of factory and provided")
            provided = _getAdapterProvided(factory)

        if (required is None) and (factory is None):
            raise TypeError("Must specify one of factory and required")

        required = _getAdapterRequired(factory, required)
        old = self._adapter_registrations.get((required, provided, name))
        if (old is None) or ((factory is not None) and
                             (factory != old[0])):
            return False

        del self._adapter_registrations[(required, provided, name)]
        self.adapters.unregister(required, provided, name)

        notify(Unregistered(
            AdapterRegistration(self, required, provided, name,
                                *old)
            ))

        return True

    def registeredAdapters(self):
        for ((required, provided, name), (component, info)
             ) in iter(self._adapter_registrations.items()):
            yield AdapterRegistration(self, required, provided, name,
                                      component, info)

    def queryAdapter(self, object, interface, name=u'', default=None):
        return self.adapters.queryAdapter(object, interface, name, default)

    def getAdapter(self, object, interface, name=u''):
        adapter = self.adapters.queryAdapter(object, interface, name)
        if adapter is None:
            raise ComponentLookupError(object, interface, name)
        return adapter

    def queryMultiAdapter(self, objects, interface, name=u'',
                          default=None):
        return self.adapters.queryMultiAdapter(
            objects, interface, name, default)

    def getMultiAdapter(self, objects, interface, name=u''):
        adapter = self.adapters.queryMultiAdapter(objects, interface, name)
        if adapter is None:
            raise ComponentLookupError(objects, interface, name)
        return adapter

    def getAdapters(self, objects, provided):
        for name, factory in self.adapters.lookupAll(
            list(map(providedBy, objects)),
            provided):
            adapter = factory(*objects)
            if adapter is not None:
                yield name, adapter

    def registerSubscriptionAdapter(self,
                                    factory, required=None, provided=None,
                                    name=u'', info=u'',
                                    event=True):
        if name:
            raise TypeError("Named subscribers are not yet supported")
        if provided is None:
            provided = _getAdapterProvided(factory)
        required = _getAdapterRequired(factory, required)
        self._subscription_registrations.append(
            (required, provided, name, factory, info)
            )
        self.adapters.subscribe(required, provided, factory)

        if event:
            notify(Registered(
                SubscriptionRegistration(self, required, provided, name,
                                         factory, info)
                ))

    def registeredSubscriptionAdapters(self):
        for data in self._subscription_registrations:
            yield SubscriptionRegistration(self, *data)

    def unregisterSubscriptionAdapter(self, factory=None,
                          required=None, provided=None, name=u'',
                          ):
        if name:
            raise TypeError("Named subscribers are not yet supported")
        if provided is None:
            if factory is None:
                raise TypeError("Must specify one of factory and provided")
            provided = _getAdapterProvided(factory)

        if (required is None) and (factory is None):
            raise TypeError("Must specify one of factory and required")

        required = _getAdapterRequired(factory, required)

        if factory is None:
            new = [(r, p, n, f, i)
                   for (r, p, n, f, i)
                   in self._subscription_registrations
                   if not (r == required and p == provided)
                   ]
        else:
            new = [(r, p, n, f, i)
                   for (r, p, n, f, i)
                   in self._subscription_registrations
                   if not (r == required and p == provided and f == factory)
                   ]

        if len(new) == len(self._subscription_registrations):
            return False


        self._subscription_registrations[:] = new
        self.adapters.unsubscribe(required, provided, factory)

        notify(Unregistered(
            SubscriptionRegistration(self, required, provided, name,
                                     factory, '')
            ))

        return True

    def subscribers(self, objects, provided):
        return self.adapters.subscribers(objects, provided)

    def registerHandler(self,
                        factory, required=None,
                        name=u'', info=u'',
                        event=True):
        if name:
            raise TypeError("Named handlers are not yet supported")
        required = _getAdapterRequired(factory, required)
        self._handler_registrations.append(
            (required, name, factory, info)
            )
        self.adapters.subscribe(required, None, factory)

        if event:
            notify(Registered(
                HandlerRegistration(self, required, name, factory, info)
                ))

    def registeredHandlers(self):
        for data in self._handler_registrations:
            yield HandlerRegistration(self, *data)

    def unregisterHandler(self, factory=None, required=None, name=u''):
        if name:
            raise TypeError("Named subscribers are not yet supported")

        if (required is None) and (factory is None):
            raise TypeError("Must specify one of factory and required")

        required = _getAdapterRequired(factory, required)

        if factory is None:
            new = [(r, n, f, i)
                   for (r, n, f, i)
                   in self._handler_registrations
                   if r != required
                   ]
        else:
            new = [(r, n, f, i)
                   for (r, n, f, i)
                   in self._handler_registrations
                   if not (r == required and f == factory)
                   ]

        if len(new) == len(self._handler_registrations):
            return False

        self._handler_registrations[:] = new
        self.adapters.unsubscribe(required, None, factory)

        notify(Unregistered(
            HandlerRegistration(self, required, name, factory, '')
            ))

        return True

    def handle(self, *objects):
        self.adapters.subscribers(objects, None)
Esempio n. 25
0
class CustomizationRegistry(object):
    """Register and execute customization handlers.
    """

    def __init__(self):
        self._scheduled = False
        self._events = []
        self._origin = AdapterRegistry()
        self._field = AdapterRegistry()
        subscribers.append(self.watch)

    def watch(self, *events):
        if len(events) > 0 and IFieldCreatedEvent.providedBy(events[0]):
            self._events.append(events[0])

    def register(self, handler, options):
        if 'origin' in options:
            self._origin.register(
                (options['origin'], options.get('schema')),
                Interface,
                options.get('name', u''),
                handler)
        elif 'field' in options:
            self._field.register(
                (options['field'], options.get('schema')),
                Interface,
                options.get('name', u''),
                handler)
        elif 'schema' in options:
            self._origin.register(
                (Interface, options['schema']),
                Interface,
                options.get('name', u''),
                handler)
        else:
            raise AssertionError('Invalid customization')

    def execute(self, clear=True):
        for event in self._events:
            handler = None
            if event.origin is not None:
                # 1. Lookup customization with the original field
                required = (providedBy(event.origin), event.interface)
                # 1.a Original field and name
                handler = self._origin.lookup(
                    required, Interface, event.field.identifier)
                if handler is None:
                    # 1.b Original field without name
                    handler = self._origin.lookup(required, Interface)
                if handler is not None:
                    handler(event.field)
            if handler is None:
                # 2. No customization found, lookup with the zeam.form field
                required = (providedBy(event.field), event.interface)
                # 2.a zeam.form field and name
                handler = self._field.lookup(
                    required, Interface, event.field.identifier)
                if handler is None:
                    # 2.b zeam.form field without name
                    handler = self._field.lookup(required, Interface)
                if handler is not None:
                    handler(event.field)
        if clear:
            del self._events[:]
        self._scheduled = False

    def schedule(self, config):
        if not self._scheduled:
            config.action(
                discriminator=('customize fields',),
                callable=self.execute,
                args=tuple(),
                order=sys.maxint-1)
            self._scheduled = True
Esempio n. 26
0
class Components(object):

    def __init__(self, name='', bases=()):
        assert isinstance(name, STRING_TYPES)
        self.__name__ = name
        self._init_registries()
        self._init_registrations()
        self.__bases__ = tuple(bases)

    def __repr__(self):
        return "<%s %s>" % (self.__class__.__name__, self.__name__)

    def _init_registries(self):
        self.adapters = AdapterRegistry()
        self.utilities = AdapterRegistry()

    def _init_registrations(self):
        self._utility_registrations = {}
        self._adapter_registrations = {}
        self._subscription_registrations = []
        self._handler_registrations = []

    def _getBases(self):
        # Subclasses might override
        return self.__dict__.get('__bases__', ())

    def _setBases(self, bases):
        # Subclasses might override
        self.adapters.__bases__ = tuple([
            base.adapters for base in bases])
        self.utilities.__bases__ = tuple([
            base.utilities for base in bases])
        self.__dict__['__bases__'] = tuple(bases)

    __bases__ = property(
        lambda self: self._getBases(),
        lambda self, bases: self._setBases(bases),
        )

    def registerUtility(self, component=None, provided=None, name=_u(''), 
                        info=_u(''), event=True, factory=None):
        if factory:
            if component:
                raise TypeError("Can't specify factory and component.")
            component = factory()

        if provided is None:
            provided = _getUtilityProvided(component)

        reg = self._utility_registrations.get((provided, name))
        if reg is not None:
            if reg[:2] == (component, info):
                # already registered
                return
            self.unregisterUtility(reg[0], provided, name)

        subscribed = False
        for ((p, _), data) in iter(self._utility_registrations.items()):
            if p == provided and data[0] == component:
                subscribed = True
                break

        self._utility_registrations[(provided, name)] = component, info, factory
        self.utilities.register((), provided, name, component)

        if not subscribed:
            self.utilities.subscribe((), provided, component)

        if event:
            notify(Registered(
                UtilityRegistration(self, provided, name, component, info,
                                    factory)
                ))

    def unregisterUtility(self, component=None, provided=None, name=_u(''),
                          factory=None):
        if factory:
            if component:
                raise TypeError("Can't specify factory and component.")
            component = factory()

        if provided is None:
            if component is None:
                raise TypeError("Must specify one of component, factory and "
                                "provided")
            provided = _getUtilityProvided(component)

        old = self._utility_registrations.get((provided, name))
        if (old is None) or ((component is not None) and
                             (component != old[0])):
            return False

        if component is None:
            component = old[0]

        # Note that component is now the old thing registered

        del self._utility_registrations[(provided, name)]
        self.utilities.unregister((), provided, name)

        subscribed = False
        for ((p, _), data) in iter(self._utility_registrations.items()):
            if p == provided and data[0] == component:
                subscribed = True
                break

        if not subscribed:
            self.utilities.unsubscribe((), provided, component)

        notify(Unregistered(
            UtilityRegistration(self, provided, name, component, *old[1:])
            ))

        return True

    def registeredUtilities(self):
        for ((provided, name), data
             ) in iter(self._utility_registrations.items()):
            yield UtilityRegistration(self, provided, name, *data)

    def queryUtility(self, provided, name=_u(''), default=None):
        return self.utilities.lookup((), provided, name, default)

    def getUtility(self, provided, name=_u('')):
        utility = self.utilities.lookup((), provided, name)
        if utility is None:
            raise ComponentLookupError(provided, name)
        return utility

    def getUtilitiesFor(self, interface):
        for name, utility in self.utilities.lookupAll((), interface):
            yield name, utility

    def getAllUtilitiesRegisteredFor(self, interface):
        return self.utilities.subscriptions((), interface)

    def registerAdapter(self, factory, required=None, provided=None, 
                        name=_u(''), info=_u(''), event=True):
        if provided is None:
            provided = _getAdapterProvided(factory)
        required = _getAdapterRequired(factory, required)
        self._adapter_registrations[(required, provided, name)
                                    ] = factory, info
        self.adapters.register(required, provided, name, factory)

        if event:
            notify(Registered(
                AdapterRegistration(self, required, provided, name,
                                    factory, info)
                ))


    def unregisterAdapter(self, factory=None,
                          required=None, provided=None, name=_u(''),
                          ):
        if provided is None:
            if factory is None:
                raise TypeError("Must specify one of factory and provided")
            provided = _getAdapterProvided(factory)

        if (required is None) and (factory is None):
            raise TypeError("Must specify one of factory and required")

        required = _getAdapterRequired(factory, required)
        old = self._adapter_registrations.get((required, provided, name))
        if (old is None) or ((factory is not None) and
                             (factory != old[0])):
            return False

        del self._adapter_registrations[(required, provided, name)]
        self.adapters.unregister(required, provided, name)

        notify(Unregistered(
            AdapterRegistration(self, required, provided, name,
                                *old)
            ))

        return True

    def registeredAdapters(self):
        for ((required, provided, name), (component, info)
             ) in iter(self._adapter_registrations.items()):
            yield AdapterRegistration(self, required, provided, name,
                                      component, info)

    def queryAdapter(self, object, interface, name=_u(''), default=None):
        return self.adapters.queryAdapter(object, interface, name, default)

    def getAdapter(self, object, interface, name=_u('')):
        adapter = self.adapters.queryAdapter(object, interface, name)
        if adapter is None:
            raise ComponentLookupError(object, interface, name)
        return adapter

    def queryMultiAdapter(self, objects, interface, name=_u(''), 
                          default=None):
        return self.adapters.queryMultiAdapter(
            objects, interface, name, default)

    def getMultiAdapter(self, objects, interface, name=_u('')):
        adapter = self.adapters.queryMultiAdapter(objects, interface, name)
        if adapter is None:
            raise ComponentLookupError(objects, interface, name)
        return adapter

    def getAdapters(self, objects, provided):
        for name, factory in self.adapters.lookupAll(
            list(map(providedBy, objects)),
            provided):
            adapter = factory(*objects)
            if adapter is not None:
                yield name, adapter

    def registerSubscriptionAdapter(self,
                                    factory, required=None, provided=None,
                                    name=_u(''), info=_u(''),
                                    event=True):
        if name:
            raise TypeError("Named subscribers are not yet supported")
        if provided is None:
            provided = _getAdapterProvided(factory)
        required = _getAdapterRequired(factory, required)
        self._subscription_registrations.append(
            (required, provided, name, factory, info)
            )
        self.adapters.subscribe(required, provided, factory)

        if event:
            notify(Registered(
                SubscriptionRegistration(self, required, provided, name,
                                         factory, info)
                ))

    def registeredSubscriptionAdapters(self):
        for data in self._subscription_registrations:
            yield SubscriptionRegistration(self, *data)

    def unregisterSubscriptionAdapter(self, factory=None,
                          required=None, provided=None, name=_u(''),
                          ):
        if name:
            raise TypeError("Named subscribers are not yet supported")
        if provided is None:
            if factory is None:
                raise TypeError("Must specify one of factory and provided")
            provided = _getAdapterProvided(factory)

        if (required is None) and (factory is None):
            raise TypeError("Must specify one of factory and required")

        required = _getAdapterRequired(factory, required)

        if factory is None:
            new = [(r, p, n, f, i)
                   for (r, p, n, f, i)
                   in self._subscription_registrations
                   if not (r == required and p == provided)
                   ]
        else:
            new = [(r, p, n, f, i)
                   for (r, p, n, f, i)
                   in self._subscription_registrations
                   if not (r == required and p == provided and f == factory)
                   ]

        if len(new) == len(self._subscription_registrations):
            return False


        self._subscription_registrations[:] = new
        self.adapters.unsubscribe(required, provided, factory)

        notify(Unregistered(
            SubscriptionRegistration(self, required, provided, name,
                                     factory, '')
            ))

        return True

    def subscribers(self, objects, provided):
        return self.adapters.subscribers(objects, provided)

    def registerHandler(self,
                        factory, required=None,
                        name=_u(''), info=_u(''),
                        event=True):
        if name:
            raise TypeError("Named handlers are not yet supported")
        required = _getAdapterRequired(factory, required)
        self._handler_registrations.append(
            (required, name, factory, info)
            )
        self.adapters.subscribe(required, None, factory)

        if event:
            notify(Registered(
                HandlerRegistration(self, required, name, factory, info)
                ))

    def registeredHandlers(self):
        for data in self._handler_registrations:
            yield HandlerRegistration(self, *data)

    def unregisterHandler(self, factory=None, required=None, name=_u('')):
        if name:
            raise TypeError("Named subscribers are not yet supported")

        if (required is None) and (factory is None):
            raise TypeError("Must specify one of factory and required")

        required = _getAdapterRequired(factory, required)

        if factory is None:
            new = [(r, n, f, i)
                   for (r, n, f, i)
                   in self._handler_registrations
                   if r != required
                   ]
        else:
            new = [(r, n, f, i)
                   for (r, n, f, i)
                   in self._handler_registrations
                   if not (r == required and f == factory)
                   ]

        if len(new) == len(self._handler_registrations):
            return False

        self._handler_registrations[:] = new
        self.adapters.unsubscribe(required, None, factory)

        notify(Unregistered(
            HandlerRegistration(self, required, name, factory, '')
            ))

        return True

    def handle(self, *objects):
        self.adapters.subscribers(objects, None)
Esempio n. 27
0
 def _init_registries(self):
     self.adapters = AdapterRegistry()
     self.utilities = AdapterRegistry()
Esempio n. 28
0
# 8) Special cases aren't special enough to break the rules.
try:
    ISpecialCases('the rules')
except TypeError:
    print "Special cases could not adapt the rules."


# 9) Although practicality beats purity.
practicality = Practicality()
if IPurity(practicality) is practicality:
    print "Practicality implements purity."


# 10) Errors should never pass silently.
# Register an object that depends on IErrors and provides ISilence
registry = AdapterRegistry()  # XXX Logic below is not quite right
registry.register([IErrors], ISilence, 'should not', 'pass')
if (registry.lookup([IErrors], ISilence, 'should not') == 'pass' and
    registry.lookup([Interface], ISilence) is None):
    print ("Errors should never require a specification that doesn’t extend "
        "the specification of silence.")


# 11) Unless explicitly silenced.
errors = Errors()
silence = Silence()
registry.register([IErrors, ISilence], IPass, '', Explicit)
explicit = registry.queryMultiAdapter((errors, silence), IPass)
if (explicit.__class__.__name__ == "Explicit" and
    explicit.errors is errors and explicit.silence is silence):
    print "Unless explicit is a multi-adapter."
Esempio n. 29
0
	def __init__(self, *args): 
		self.registry = AdapterRegistry()
		self.all_components = set() 
		dict.__init__(self, *args)
Esempio n. 30
0
def dummy_request(request, config):
    req = testing.DummyRequest()
    req.find_service = types.MethodType(find_service, req)
    req.service_cache = AdapterRegistry()
    return req
Esempio n. 31
0
# system imports
import warnings

# zope3 imports
from zope.interface import interface, declarations
from zope.interface.adapter import AdapterRegistry


class ComponentsDeprecationWarning(DeprecationWarning):
    """Nothing emits this warning anymore."""
    pass


# Twisted's global adapter registry
globalRegistry = AdapterRegistry()

# Attribute that registerAdapter looks at. Is this supposed to be public?
ALLOW_DUPLICATES = 0

# Define a function to find the registered adapter factory, using either a
# version of Zope Interface which has the `registered' method or an older
# version which does not.
if getattr(AdapterRegistry, 'registered', None) is None:

    def _registered(registry, required, provided):
        """
        Return the adapter factory for the given parameters in the given
        registry, or None if there is not one.
        """
        return registry.get(required).selfImplied.get(provided, {}).get('')
Esempio n. 32
0
 def __init__(self):
     self.registry = AdapterRegistry()
Esempio n. 33
0
 def _init_registries(self):
     # Subclasses have never been required to call this method
     # if they override it, merely to fill in these two attributes.
     self.adapters = AdapterRegistry()
     self.utilities = AdapterRegistry()
Esempio n. 34
0
 def __init__(self):
     self.registry = AdapterRegistry()
     self.calls = ([], [])
Esempio n. 35
0
# -*- coding: utf-8 -*-
"""
gites.ldapimport

Licensed under the GPL license, see LICENCE.txt for more details.
Copyright by Affinitic sprl

$Id$
"""
from zope.interface.adapter import AdapterRegistry
from gites.ldapimport.interfaces import (IProprietaire,
                                         ILDAPProprietaire,
                                         INameChooser)
from gites.ldapimport.ldapProprietaire import LDAPProprietaire
PROPRIO_LOGIN_REGISTRY = []
from gites.ldapimport.namechooser import ProprietaireNameChooser


registry = AdapterRegistry()
registry.register([IProprietaire], ILDAPProprietaire, '', LDAPProprietaire)
registry.register([IProprietaire], INameChooser, '', ProprietaireNameChooser)
Esempio n. 36
0
class Registry(object):
    """A base component registry.
    """
    def __init__(self):
        self.registry = AdapterRegistry()
        self.calls = ([], [])

    def loadCalls(self, calls):
        for item in calls[0]:
            self.registry.register(item[0], item[1], item[2], item[3])

        for item in calls[1]:
            self.registry.subscribe(item[0], item[1], item[2])

    def register(self, sources, target, name, component):
        required = interfaces(sources)
        self.calls[0].append((required, target, name, component))
        self.registry.register(required, target, name, component)

    def subscribe(self, sources, target, component):
        required = interfaces(sources)
        self.calls[1].append((required, target, component))
        self.registry.subscribe(required, target, component)

    def lookup(self, obs, target, name):
        return self.registry.lookup(map(providedBy, obs), target, name)

    def cls_lookup(self, classes, target, name):
        return self.registry.lookup(map(implementedBy, classes), target, name)

    def lookup_all(self, obs, target):
        return iter(self.registry.lookupAll(list(map(providedBy, obs)),
                                            target))

    def subscriptions(self, obs, target):
        return self.registry.subscriptions(map(providedBy, obs), target)

    def predicates(self, classes, target):
        return self.registry.subscriptions(map(implementedBy, classes), target)

    def adapt(self, obs, target, name):
        # self-adaptation
        if len(obs) == 1 and target.providedBy(obs[0]):
            return obs[0]
        adapter = self.lookup(obs, target, name)
        if adapter is None:
            return None
        try:
            return adapter(*obs)
        except TypeError as e:
            raise TypeError(str(e) + " (%s)" % adapter)
Esempio n. 37
0
class Components(object):
    def __init__(self, name='', bases=()):
        assert isinstance(name, STRING_TYPES)
        self.__name__ = name
        self._init_registries()
        self._init_registrations()
        self.__bases__ = tuple(bases)

    def __repr__(self):
        return "<%s %s>" % (self.__class__.__name__, self.__name__)

    def _init_registries(self):
        self.adapters = AdapterRegistry()
        self.utilities = AdapterRegistry()

    def _init_registrations(self):
        self._utility_registrations = {}
        self._adapter_registrations = {}
        self._subscription_registrations = []
        self._handler_registrations = []

    def _getBases(self):
        # Subclasses might override
        return self.__dict__.get('__bases__', ())

    def _setBases(self, bases):
        # Subclasses might override
        self.adapters.__bases__ = tuple([base.adapters for base in bases])
        self.utilities.__bases__ = tuple([base.utilities for base in bases])
        self.__dict__['__bases__'] = tuple(bases)

    __bases__ = property(
        lambda self: self._getBases(),
        lambda self, bases: self._setBases(bases),
    )

    def registerUtility(self,
                        component=None,
                        provided=None,
                        name=_u(''),
                        info=_u(''),
                        event=True,
                        factory=None):
        if factory:
            if component:
                raise TypeError("Can't specify factory and component.")
            component = factory()

        if provided is None:
            provided = _getUtilityProvided(component)

        reg = self._utility_registrations.get((provided, name))
        if reg is not None:
            if reg[:2] == (component, info):
                # already registered
                return
            self.unregisterUtility(reg[0], provided, name)

        subscribed = False
        for ((p, _), data) in iter(self._utility_registrations.items()):
            if p == provided and data[0] == component:
                subscribed = True
                break

        self._utility_registrations[(provided,
                                     name)] = component, info, factory
        self.utilities.register((), provided, name, component)

        if not subscribed:
            self.utilities.subscribe((), provided, component)

        if event:
            notify(
                Registered(
                    UtilityRegistration(self, provided, name, component, info,
                                        factory)))

    def unregisterUtility(self,
                          component=None,
                          provided=None,
                          name=_u(''),
                          factory=None):
        if factory:
            if component:
                raise TypeError("Can't specify factory and component.")
            component = factory()

        if provided is None:
            if component is None:
                raise TypeError("Must specify one of component, factory and "
                                "provided")
            provided = _getUtilityProvided(component)

        old = self._utility_registrations.get((provided, name))
        if (old is None) or ((component is not None) and
                             (component != old[0])):
            return False

        if component is None:
            component = old[0]

        # Note that component is now the old thing registered

        del self._utility_registrations[(provided, name)]
        self.utilities.unregister((), provided, name)

        subscribed = False
        for ((p, _), data) in iter(self._utility_registrations.items()):
            if p == provided and data[0] == component:
                subscribed = True
                break

        if not subscribed:
            self.utilities.unsubscribe((), provided, component)

        notify(
            Unregistered(
                UtilityRegistration(self, provided, name, component,
                                    *old[1:])))

        return True

    def registeredUtilities(self):
        for ((provided, name),
             data) in iter(self._utility_registrations.items()):
            yield UtilityRegistration(self, provided, name, *data)

    def queryUtility(self, provided, name=_u(''), default=None):
        return self.utilities.lookup((), provided, name, default)

    def getUtility(self, provided, name=_u('')):
        utility = self.utilities.lookup((), provided, name)
        if utility is None:
            raise ComponentLookupError(provided, name)
        return utility

    def getUtilitiesFor(self, interface):
        for name, utility in self.utilities.lookupAll((), interface):
            yield name, utility

    def getAllUtilitiesRegisteredFor(self, interface):
        return self.utilities.subscriptions((), interface)

    def registerAdapter(self,
                        factory,
                        required=None,
                        provided=None,
                        name=_u(''),
                        info=_u(''),
                        event=True):
        if provided is None:
            provided = _getAdapterProvided(factory)
        required = _getAdapterRequired(factory, required)
        self._adapter_registrations[(required, provided, name)] = factory, info
        self.adapters.register(required, provided, name, factory)

        if event:
            notify(
                Registered(
                    AdapterRegistration(self, required, provided, name,
                                        factory, info)))

    def unregisterAdapter(
            self,
            factory=None,
            required=None,
            provided=None,
            name=_u(''),
    ):
        if provided is None:
            if factory is None:
                raise TypeError("Must specify one of factory and provided")
            provided = _getAdapterProvided(factory)

        if (required is None) and (factory is None):
            raise TypeError("Must specify one of factory and required")

        required = _getAdapterRequired(factory, required)
        old = self._adapter_registrations.get((required, provided, name))
        if (old is None) or ((factory is not None) and (factory != old[0])):
            return False

        del self._adapter_registrations[(required, provided, name)]
        self.adapters.unregister(required, provided, name)

        notify(
            Unregistered(
                AdapterRegistration(self, required, provided, name, *old)))

        return True

    def registeredAdapters(self):
        for ((required, provided, name),
             (component, info)) in iter(self._adapter_registrations.items()):
            yield AdapterRegistration(self, required, provided, name,
                                      component, info)

    def queryAdapter(self, object, interface, name=_u(''), default=None):
        return self.adapters.queryAdapter(object, interface, name, default)

    def getAdapter(self, object, interface, name=_u('')):
        adapter = self.adapters.queryAdapter(object, interface, name)
        if adapter is None:
            raise ComponentLookupError(object, interface, name)
        return adapter

    def queryMultiAdapter(self, objects, interface, name=_u(''), default=None):
        return self.adapters.queryMultiAdapter(objects, interface, name,
                                               default)

    def getMultiAdapter(self, objects, interface, name=_u('')):
        adapter = self.adapters.queryMultiAdapter(objects, interface, name)
        if adapter is None:
            raise ComponentLookupError(objects, interface, name)
        return adapter

    def getAdapters(self, objects, provided):
        for name, factory in self.adapters.lookupAll(
                list(map(providedBy, objects)), provided):
            adapter = factory(*objects)
            if adapter is not None:
                yield name, adapter

    def registerSubscriptionAdapter(self,
                                    factory,
                                    required=None,
                                    provided=None,
                                    name=_u(''),
                                    info=_u(''),
                                    event=True):
        if name:
            raise TypeError("Named subscribers are not yet supported")
        if provided is None:
            provided = _getAdapterProvided(factory)
        required = _getAdapterRequired(factory, required)
        self._subscription_registrations.append(
            (required, provided, name, factory, info))
        self.adapters.subscribe(required, provided, factory)

        if event:
            notify(
                Registered(
                    SubscriptionRegistration(self, required, provided, name,
                                             factory, info)))

    def registeredSubscriptionAdapters(self):
        for data in self._subscription_registrations:
            yield SubscriptionRegistration(self, *data)

    def unregisterSubscriptionAdapter(
            self,
            factory=None,
            required=None,
            provided=None,
            name=_u(''),
    ):
        if name:
            raise TypeError("Named subscribers are not yet supported")
        if provided is None:
            if factory is None:
                raise TypeError("Must specify one of factory and provided")
            provided = _getAdapterProvided(factory)

        if (required is None) and (factory is None):
            raise TypeError("Must specify one of factory and required")

        required = _getAdapterRequired(factory, required)

        if factory is None:
            new = [(r, p, n, f, i)
                   for (r, p, n, f, i) in self._subscription_registrations
                   if not (r == required and p == provided)]
        else:
            new = [(r, p, n, f, i)
                   for (r, p, n, f, i) in self._subscription_registrations
                   if not (r == required and p == provided and f == factory)]

        if len(new) == len(self._subscription_registrations):
            return False

        self._subscription_registrations[:] = new
        self.adapters.unsubscribe(required, provided, factory)

        notify(
            Unregistered(
                SubscriptionRegistration(self, required, provided, name,
                                         factory, '')))

        return True

    def subscribers(self, objects, provided):
        return self.adapters.subscribers(objects, provided)

    def registerHandler(self,
                        factory,
                        required=None,
                        name=_u(''),
                        info=_u(''),
                        event=True):
        if name:
            raise TypeError("Named handlers are not yet supported")
        required = _getAdapterRequired(factory, required)
        self._handler_registrations.append((required, name, factory, info))
        self.adapters.subscribe(required, None, factory)

        if event:
            notify(
                Registered(
                    HandlerRegistration(self, required, name, factory, info)))

    def registeredHandlers(self):
        for data in self._handler_registrations:
            yield HandlerRegistration(self, *data)

    def unregisterHandler(self, factory=None, required=None, name=_u('')):
        if name:
            raise TypeError("Named subscribers are not yet supported")

        if (required is None) and (factory is None):
            raise TypeError("Must specify one of factory and required")

        required = _getAdapterRequired(factory, required)

        if factory is None:
            new = [(r, n, f, i) for (r, n, f, i) in self._handler_registrations
                   if r != required]
        else:
            new = [(r, n, f, i) for (r, n, f, i) in self._handler_registrations
                   if not (r == required and f == factory)]

        if len(new) == len(self._handler_registrations):
            return False

        self._handler_registrations[:] = new
        self.adapters.unsubscribe(required, None, factory)

        notify(
            Unregistered(HandlerRegistration(self, required, name, factory,
                                             '')))

        return True

    def handle(self, *objects):
        self.adapters.subscribers(objects, None)
Esempio n. 38
0
 def __init__(self):
     self.behaviors = AdapterRegistry()
     self.behaviornames = {}
     self.schemas = AdapterRegistry()
     self.schemanames = {}
     self.relations = {}
Esempio n. 39
0
from zope.interface.adapter import AdapterRegistry
from zope.interface.interface import adapter_hooks
import zope.interface


registry = AdapterRegistry()


def hook(provided, object):
    adapter = registry.lookup1(zope.interface.providedBy(object), provided, '')
    if not adapter:
        return
    return adapter(object)
adapter_hooks.append(hook)


def configure_registry():
    from jukebox import interfaces
    from jukebox import storage

    registry.register(
        [interfaces.ISearchableStorage],
        interfaces.IStorage,
        '',
        storage.NoOpStorageAdaptor
    )
    registry.register(
        [interfaces.IStorage],
        interfaces.ISearchableStorage,
        '',
        storage.NoOpSearchableStorage
Esempio n. 40
0
 def _init_registries(self):
     # Subclasses have never been required to call this method
     # if they override it, merely to fill in these two attributes.
     self.adapters = AdapterRegistry()
     self.utilities = AdapterRegistry()
Esempio n. 41
0
 def _init_registries(self):
     self.adapters = AdapterRegistry()
     self.utilities = AdapterRegistry()
Esempio n. 42
0
 def __init__(self):
     self.registry = AdapterRegistry()
Esempio n. 43
0
 def __init__(self):
     self._scheduled = False
     self._events = []
     self._origin = AdapterRegistry()
     self._field = AdapterRegistry()
     subscribers.append(self.watch)
Esempio n. 44
0
def run_tests(module):
    module = maybe_dotted(module)
    registry = AdapterRegistry()
    scanner = venusian.Scanner(registry=registry)
    scanner.scan(module)
Esempio n. 45
0
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

from zope.interface import interface, declarations
from zope.interface.adapter import AdapterRegistry

# The following is taken almots as-is from twisted.python.components
_vcoRegistry = AdapterRegistry()


def _registered(registry, required, provided):
    """
    Return the adapter factory for the given parameters in the given
    registry, or None if there is not one.
    """
    return registry.get(required).selfImplied.get(provided, {}).get('')


def registerAdapter(adapterFactory, origInterface, *interfaceClasses):
    """Register an adapter class.

    An adapter class is expected to implement the given interface, by
    adapting instances implementing 'origInterface'. An adapter class's
Esempio n. 46
0
class Components(object):
    def __init__(self, name='', bases=()):
        assert isinstance(name, STRING_TYPES)
        self.__name__ = name
        self._init_registries()
        self._init_registrations()
        self.__bases__ = tuple(bases)

        # __init__ is used for test cleanup as well as initialization.
        # XXX add a separate API for test cleanup.
        # See _utility_registrations below.
        if hasattr(self, '_v_utility_registrations_cache'):
            del self._v_utility_registrations_cache

    def __repr__(self):
        return "<%s %s>" % (self.__class__.__name__, self.__name__)

    def _init_registries(self):
        self.adapters = AdapterRegistry()
        self.utilities = AdapterRegistry()

    def _init_registrations(self):
        self._utility_registrations = {}
        self._adapter_registrations = {}
        self._subscription_registrations = []
        self._handler_registrations = []

    @property
    def _utility_registrations_cache(self):
        # We use a _v_ attribute internally so that data aren't saved in ZODB.
        # If data are pickled in other contexts, the data will be carried along.
        # There's no harm in pickling the extra data othr than that it would
        # be somewhat wasteful. It's doubtful that that's an issue anyway.
        try:
            return self._v_utility_registrations_cache
        except AttributeError:
            self._v_utility_registrations_cache = _UtilityRegistrations(
                self.utilities, self._utility_registrations)
            return self._v_utility_registrations_cache

    def _getBases(self):
        # Subclasses might override
        return self.__dict__.get('__bases__', ())

    def _setBases(self, bases):
        # Subclasses might override
        self.adapters.__bases__ = tuple([base.adapters for base in bases])
        self.utilities.__bases__ = tuple([base.utilities for base in bases])
        self.__dict__['__bases__'] = tuple(bases)

    __bases__ = property(
        lambda self: self._getBases(),
        lambda self, bases: self._setBases(bases),
    )

    def registerUtility(self,
                        component=None,
                        provided=None,
                        name=u'',
                        info=u'',
                        event=True,
                        factory=None):
        if factory:
            if component:
                raise TypeError("Can't specify factory and component.")
            component = factory()

        if provided is None:
            provided = _getUtilityProvided(component)

        if name == u'':
            name = _getName(component)

        reg = self._utility_registrations.get((provided, name))
        if reg is not None:
            if reg[:2] == (component, info):
                # already registered
                return
            self.unregisterUtility(reg[0], provided, name)

        self._utility_registrations_cache.registerUtility(
            provided, name, component, info, factory)

        if event:
            notify(
                Registered(
                    UtilityRegistration(self, provided, name, component, info,
                                        factory)))

    def unregisterUtility(self,
                          component=None,
                          provided=None,
                          name=u'',
                          factory=None):
        if factory:
            if component:
                raise TypeError("Can't specify factory and component.")
            component = factory()

        if provided is None:
            if component is None:
                raise TypeError("Must specify one of component, factory and "
                                "provided")
            provided = _getUtilityProvided(component)

        old = self._utility_registrations.get((provided, name))
        if (old is None) or ((component is not None) and
                             (component != old[0])):
            return False

        if component is None:
            component = old[0]

        # Note that component is now the old thing registered
        self._utility_registrations_cache.unregisterUtility(
            provided, name, component)

        notify(
            Unregistered(
                UtilityRegistration(self, provided, name, component,
                                    *old[1:])))

        return True

    def registeredUtilities(self):
        for ((provided, name),
             data) in iter(self._utility_registrations.items()):
            yield UtilityRegistration(self, provided, name, *data)

    def queryUtility(self, provided, name=u'', default=None):
        return self.utilities.lookup((), provided, name, default)

    def getUtility(self, provided, name=u''):
        utility = self.utilities.lookup((), provided, name)
        if utility is None:
            raise ComponentLookupError(provided, name)
        return utility

    def getUtilitiesFor(self, interface):
        for name, utility in self.utilities.lookupAll((), interface):
            yield name, utility

    def getAllUtilitiesRegisteredFor(self, interface):
        return self.utilities.subscriptions((), interface)

    def registerAdapter(self,
                        factory,
                        required=None,
                        provided=None,
                        name=u'',
                        info=u'',
                        event=True):
        if provided is None:
            provided = _getAdapterProvided(factory)
        required = _getAdapterRequired(factory, required)
        if name == u'':
            name = _getName(factory)
        self._adapter_registrations[(required, provided, name)] = factory, info
        self.adapters.register(required, provided, name, factory)

        if event:
            notify(
                Registered(
                    AdapterRegistration(self, required, provided, name,
                                        factory, info)))

    def unregisterAdapter(
        self,
        factory=None,
        required=None,
        provided=None,
        name=u'',
    ):
        if provided is None:
            if factory is None:
                raise TypeError("Must specify one of factory and provided")
            provided = _getAdapterProvided(factory)

        if (required is None) and (factory is None):
            raise TypeError("Must specify one of factory and required")

        required = _getAdapterRequired(factory, required)
        old = self._adapter_registrations.get((required, provided, name))
        if (old is None) or ((factory is not None) and (factory != old[0])):
            return False

        del self._adapter_registrations[(required, provided, name)]
        self.adapters.unregister(required, provided, name)

        notify(
            Unregistered(
                AdapterRegistration(self, required, provided, name, *old)))

        return True

    def registeredAdapters(self):
        for ((required, provided, name),
             (component, info)) in iter(self._adapter_registrations.items()):
            yield AdapterRegistration(self, required, provided, name,
                                      component, info)

    def queryAdapter(self, object, interface, name=u'', default=None):
        return self.adapters.queryAdapter(object, interface, name, default)

    def getAdapter(self, object, interface, name=u''):
        adapter = self.adapters.queryAdapter(object, interface, name)
        if adapter is None:
            raise ComponentLookupError(object, interface, name)
        return adapter

    def queryMultiAdapter(self, objects, interface, name=u'', default=None):
        return self.adapters.queryMultiAdapter(objects, interface, name,
                                               default)

    def getMultiAdapter(self, objects, interface, name=u''):
        adapter = self.adapters.queryMultiAdapter(objects, interface, name)
        if adapter is None:
            raise ComponentLookupError(objects, interface, name)
        return adapter

    def getAdapters(self, objects, provided):
        for name, factory in self.adapters.lookupAll(
                list(map(providedBy, objects)), provided):
            adapter = factory(*objects)
            if adapter is not None:
                yield name, adapter

    def registerSubscriptionAdapter(self,
                                    factory,
                                    required=None,
                                    provided=None,
                                    name=u'',
                                    info=u'',
                                    event=True):
        if name:
            raise TypeError("Named subscribers are not yet supported")
        if provided is None:
            provided = _getAdapterProvided(factory)
        required = _getAdapterRequired(factory, required)
        self._subscription_registrations.append(
            (required, provided, name, factory, info))
        self.adapters.subscribe(required, provided, factory)

        if event:
            notify(
                Registered(
                    SubscriptionRegistration(self, required, provided, name,
                                             factory, info)))

    def registeredSubscriptionAdapters(self):
        for data in self._subscription_registrations:
            yield SubscriptionRegistration(self, *data)

    def unregisterSubscriptionAdapter(
        self,
        factory=None,
        required=None,
        provided=None,
        name=u'',
    ):
        if name:
            raise TypeError("Named subscribers are not yet supported")
        if provided is None:
            if factory is None:
                raise TypeError("Must specify one of factory and provided")
            provided = _getAdapterProvided(factory)

        if (required is None) and (factory is None):
            raise TypeError("Must specify one of factory and required")

        required = _getAdapterRequired(factory, required)

        if factory is None:
            new = [(r, p, n, f, i)
                   for (r, p, n, f, i) in self._subscription_registrations
                   if not (r == required and p == provided)]
        else:
            new = [(r, p, n, f, i)
                   for (r, p, n, f, i) in self._subscription_registrations
                   if not (r == required and p == provided and f == factory)]

        if len(new) == len(self._subscription_registrations):
            return False

        self._subscription_registrations[:] = new
        self.adapters.unsubscribe(required, provided, factory)

        notify(
            Unregistered(
                SubscriptionRegistration(self, required, provided, name,
                                         factory, '')))

        return True

    def subscribers(self, objects, provided):
        return self.adapters.subscribers(objects, provided)

    def registerHandler(self,
                        factory,
                        required=None,
                        name=u'',
                        info=u'',
                        event=True):
        if name:
            raise TypeError("Named handlers are not yet supported")
        required = _getAdapterRequired(factory, required)
        self._handler_registrations.append((required, name, factory, info))
        self.adapters.subscribe(required, None, factory)

        if event:
            notify(
                Registered(
                    HandlerRegistration(self, required, name, factory, info)))

    def registeredHandlers(self):
        for data in self._handler_registrations:
            yield HandlerRegistration(self, *data)

    def unregisterHandler(self, factory=None, required=None, name=u''):
        if name:
            raise TypeError("Named subscribers are not yet supported")

        if (required is None) and (factory is None):
            raise TypeError("Must specify one of factory and required")

        required = _getAdapterRequired(factory, required)

        if factory is None:
            new = [(r, n, f, i) for (r, n, f, i) in self._handler_registrations
                   if r != required]
        else:
            new = [(r, n, f, i) for (r, n, f, i) in self._handler_registrations
                   if not (r == required and f == factory)]

        if len(new) == len(self._handler_registrations):
            return False

        self._handler_registrations[:] = new
        self.adapters.unsubscribe(required, None, factory)

        notify(
            Unregistered(HandlerRegistration(self, required, name, factory,
                                             '')))

        return True

    def handle(self, *objects):
        self.adapters.subscribers(objects, None)