[Zope3-checkins] SVN: Zope3/trunk/ Implemented:
http://dev.zope.org/Zope3/SimplifyEventSystem
Jim Fulton
jim at zope.com
Thu May 27 09:00:50 EDT 2004
Log message for revision 25041:
Implemented: http://dev.zope.org/Zope3/SimplifyEventSystem
Merged the jim-simplifyevents branch:
svn merge -r24988:HEAD \
svn+ssh://svn.zope.org/repos/main/Zope3/branches/jim-simplifyevents
Revisions:
25027, 25024, 25017, 25016, 25015, 25014, 25011, 25001, 25000, 24999,
24998, 24997, 24996
Summary of changes:
- We had an object hub service. The object hub service was responsible
for:
- Managing short ids for objects, useful for indexing
- Keeping track of object locations. This was important when the
object hub was created, because it wasn't practical to use direct
object references. No it is, so hub ids are no-longer useful for
implementing location-independent object references.
The object hub service is dead.
In the future, there will be a utility for use by indexes, that
maintains short ids for objects. Perhaps this will be an indexing id
service.
The index and catalog machinery depend heavily on a facility for
assigning shot ids to objects, currently the hub. Rather than trying
to remove this dependency now, and ad it back later when we have an
index-id utility, it makes more sense to just remove the index and
catalog facilities for now.
Later, when we create an index-id utility, we'll port the code, which
will still be in the repository, back.
- Converted event subscribers to simple handlers implemented as
simple Python functions.
- Now all handlers are registered as subscription adapters using the
subscriber directive (rather than event:subscribe).
- No longer have IEvent. There's no need for a common base
interface.
- No longer have event publication or subscription services.
-=-
Deleted: Zope3/trunk/package-includes/catalog-configure.zcml
===================================================================
--- Zope3/trunk/package-includes/catalog-configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/package-includes/catalog-configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1 +0,0 @@
-<include package="zope.app.catalog" />
Deleted: Zope3/trunk/package-includes/index-configure.zcml
===================================================================
--- Zope3/trunk/package-includes/index-configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/package-includes/index-configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1 +0,0 @@
-<include package="zope.app.index"/>
Deleted: Zope3/trunk/package-includes/zope.app.catalog-configure.zcml
===================================================================
--- Zope3/trunk/package-includes/zope.app.catalog-configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/package-includes/zope.app.catalog-configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1 +0,0 @@
-<include package="zope.app.catalog"/>
Deleted: Zope3/trunk/package-includes/zope.app.zptpage.textindex-configure.zcml
===================================================================
--- Zope3/trunk/package-includes/zope.app.zptpage.textindex-configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/package-includes/zope.app.zptpage.textindex-configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1 +0,0 @@
-<include package="zope.app.zptpage.textindex" />
Modified: Zope3/trunk/src/zope/app/adapter/browser/__init__.py
===================================================================
--- Zope3/trunk/src/zope/app/adapter/browser/__init__.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/adapter/browser/__init__.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -34,7 +34,7 @@
from zope.app.registration.interfaces import IRegistration
from zope.app.form.interfaces import IInputWidget
from zope.app.form.utility import applyWidgetsChanges
-from zope.app.event import publish
+from zope.event import notify
from zope.app.event.objectevent import ObjectCreatedEvent
from zope.app.adapter.adapter import AdapterRegistration
@@ -48,7 +48,7 @@
if "FINISH" in self.request:
data = getWidgetsData(self, IAdapterRegistration)
registration = AdapterRegistration(**data)
- publish(self.context.context, ObjectCreatedEvent(registration))
+ notify(ObjectCreatedEvent(registration))
registration = self.context.add(registration)
applyWidgetsChanges(view, IRegistration, target=registration)
self.request.response.redirect(self.context.nextURL())
Modified: Zope3/trunk/src/zope/app/apidoc/ifacemodule/browser.py
===================================================================
--- Zope3/trunk/src/zope/app/apidoc/ifacemodule/browser.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/apidoc/ifacemodule/browser.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -332,8 +332,14 @@
>>> details = getInterfaceDetails()
>>> adapters = details.getRequiredAdapters()
+ >>> adapters.sort()
>>> pprint(adapters)
- [[('factory',
+ [[('factory', 'None.append'),
+ ('factory_url', 'None/append'),
+ ('name', None),
+ ('provided', None),
+ ('required', [])],
+ [('factory',
'zope.app.location.traversing.LocationPhysicallyLocatable'),
('factory_url',
'zope/app/location/traversing/LocationPhysicallyLocatable'),
@@ -360,7 +366,7 @@
'required': [getPythonPath(iface)
for iface in reg.required
if iface is not None],
- 'name': reg.name,
+ 'name': getattr(reg, 'name', None),
'factory': path,
'factory_url': url
})
Modified: Zope3/trunk/src/zope/app/apidoc/servicemodule/__init__.py
===================================================================
--- Zope3/trunk/src/zope/app/apidoc/servicemodule/__init__.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/apidoc/servicemodule/__init__.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -60,9 +60,9 @@
>>> print '\n'.join([id for id, iface in module.items()][:4])
Adapters
- EventPublication
Presentation
Services
+ Utilities
>>> setup.tearDown()
"""
Modified: Zope3/trunk/src/zope/app/appsetup/appsetup.py
===================================================================
--- Zope3/trunk/src/zope/app/appsetup/appsetup.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/appsetup/appsetup.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -18,9 +18,8 @@
import zope.interface
from zope.security.interfaces import IParticipation
from zope.security.management import system_user
-from zope.app.event.interfaces import IEvent
-class IDatabaseOpenedEvent(IEvent):
+class IDatabaseOpenedEvent(zope.interface.Interface):
"""The main database has been opened."""
database = zope.interface.Attribute("The main database.")
@@ -31,7 +30,7 @@
def __init__(self, database):
self.database = database
-class IProcessStartingEvent(IEvent):
+class IProcessStartingEvent(zope.interface.Interface):
"""The application server process is starting."""
class ProcessStarting:
@@ -89,7 +88,7 @@
db = DB(storage, cache_size=4000)
# The following will fail unless the application has been configured.
- from zope.app.event import publish
- publish(None, DatabaseOpened(db))
+ from zope.event import notify
+ notify(DatabaseOpened(db))
return db
Modified: Zope3/trunk/src/zope/app/appsetup/bootstrap.py
===================================================================
--- Zope3/trunk/src/zope/app/appsetup/bootstrap.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/appsetup/bootstrap.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -26,28 +26,21 @@
from zope.component.exceptions import ComponentLookupError
from zope.app import zapi
-from zope.app.event.interfaces import ISubscriber
from zope.app.traversing.api import traverse, traverseName
from zope.app.publication.zopepublication import ZopePublication
from zope.app.folder import rootFolder
-from zope.app.servicenames import HubIds, PrincipalAnnotation
-from zope.app.servicenames import EventPublication, EventSubscription
+from zope.app.servicenames import PrincipalAnnotation
from zope.app.servicenames import ErrorLogging, Utilities
from zope.app.site.service import ServiceManager, ServiceRegistration
-from zope.app.event.localservice import EventService
from zope.app.errorservice import RootErrorReportingService
-from zope.app.event import function
from zope.app.container.interfaces import INameChooser
from zope.app.utility import UtilityRegistration, LocalUtilityService
# XXX It should be possible to remove each of these from the basic
-# bootstrap, at which point we can remove the zope.app.hub,
+# bootstrap, at which point we can remove the
# zope.app.principalannotation, and zope.app.session packages from
# zope.app.
-from zope.app.hub import ObjectHub, Registration
-from zope.app.hub.interfaces import ISubscriptionControl
-
from zope.app.principalannotation import PrincipalAnnotationService
from zope.app.session.interfaces import \
@@ -63,8 +56,6 @@
method.
"""
- implements(ISubscriber)
-
def doSetup(self):
"""Instantiate some service.
@@ -72,7 +63,7 @@
"""
pass
- def notify(self, event):
+ def __call__(self, event):
db = event.database
connection = db.open()
@@ -167,30 +158,7 @@
XXX This ought to be configurable. For now, hardcode some
services we know we all need.
"""
- # The EventService class implements two services
- name = self.ensureService(EventPublication, EventService)
- if name:
- configureService(self.root_folder, EventSubscription, name)
- elif not self.service_manager.queryLocalService(EventSubscription):
- pub = self.service_manager.queryLocalService(EventPublication)
- name = zapi.getName(pub)
- configureService(self.root_folder, EventSubscription, name)
- # Add the HubIds service, which subscribes itself to the event service
- name = self.ensureService(HubIds, ObjectHub)
- # Add a Registration object so that the Hub has something to do.
- name = self.ensureObject('Registration',
- ISubscriptionControl, Registration)
-
- if name:
- package = getServiceManagerDefault(self.root_folder)
- reg = package[name]
- # It's possible that we would want to reindex all objects when
- # this is added - this seems like a very site-specific decision,
- # though.
- reg.subscribe()
-
-
# Sundry other services
self.ensureService(ErrorLogging,
RootErrorReportingService, copy_to_zlog=True)
Modified: Zope3/trunk/src/zope/app/appsetup/configure.zcml
===================================================================
--- Zope3/trunk/src/zope/app/appsetup/configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/appsetup/configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,11 +1,8 @@
-<configure
- xmlns="http://namespaces.zope.org/zope"
- xmlns:event="http://namespaces.zope.org/event"
- >
+<configure xmlns="http://namespaces.zope.org/zope">
- <event:subscribe
- subscriber=".bootstrap.bootstrapInstance"
- event_types="zope.app.appsetup.IDatabaseOpenedEvent"
+ <subscriber
+ factory=".bootstrap.bootstrapInstance"
+ for="zope.app.appsetup.IDatabaseOpenedEvent"
/>
</configure>
Modified: Zope3/trunk/src/zope/app/appsetup/tests.py
===================================================================
--- Zope3/trunk/src/zope/app/appsetup/tests.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/appsetup/tests.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -24,8 +24,6 @@
from zope.app.folder.interfaces import IRootFolder
from zope.app.errorservice.interfaces import IErrorReportingService
from zope.app.principalannotation.interfaces import IPrincipalAnnotationService
-from zope.app.event.interfaces import IEventService
-from zope.app.hub.interfaces import IObjectHub
from zope.app.publication.zopepublication import ZopePublication
from zope.app.site.tests.placefulsetup import PlacefulSetup
from zope.app.errorservice import ErrorReportingService
@@ -75,7 +73,7 @@
setup()
- BootstrapSubscriberBase().notify(EventStub(self.db))
+ BootstrapSubscriberBase()(EventStub(self.db))
cx = self.db.open()
root = cx.root()
@@ -92,7 +90,7 @@
self.createRFAndSM()
bs = BootstrapSubscriberBase()
- bs.notify(EventStub(self.db))
+ bs(EventStub(self.db))
for i in range(2):
cx = self.db.open()
name = bs.ensureService(ErrorLogging, ErrorReportingService)
@@ -118,7 +116,7 @@
def test_bootstrapInstance(self):
from zope.app.appsetup.bootstrap import bootstrapInstance
- bootstrapInstance.notify(EventStub(self.db))
+ bootstrapInstance(EventStub(self.db))
cx = self.db.open()
root = cx.root()
@@ -127,12 +125,6 @@
package_name = '/++etc++site/default'
package = traverse(root_folder, package_name)
- self.assert_(IEventService.providedBy(
- traverse(package, 'EventPublication')))
-
- self.assert_(IObjectHub.providedBy(
- traverse(package, 'HubIds')))
-
self.assert_(IErrorReportingService.providedBy(
traverse(package, 'ErrorLogging')))
@@ -151,7 +143,7 @@
ErrorReportingService, copy_to_zlog=True)
configureService(self.root_folder, ErrorLogging, name)
- bootstrapInstance.notify(EventStub(self.db))
+ bootstrapInstance(EventStub(self.db))
cx = self.db.open()
root = cx.root()
@@ -160,21 +152,12 @@
package_name = '/++etc++site/default'
package = traverse(root_folder, package_name)
- self.assert_(IEventService.providedBy(
- traverse(package, 'EventPublication')))
-
- self.assert_(IObjectHub.providedBy(
- traverse(package, 'HubIds')))
-
self.assertRaises(NotFoundError, traverse, root_folder,
'/++etc++site/default/ErrorLogging')
self.assert_(IErrorReportingService.providedBy(
traverse(package, 'Errors')))
- self.assert_(IEventService.providedBy(
- traverse(package, 'EventPublication')))
-
self.assert_(IPrincipalAnnotationService.providedBy(
traverse(package, 'PrincipalAnnotation')))
Modified: Zope3/trunk/src/zope/app/broken/broken.py
===================================================================
--- Zope3/trunk/src/zope/app/broken/broken.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/broken/broken.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -20,7 +20,6 @@
import ZODB.broken
import zope.interface
import zope.app.location.interfaces
-import zope.app.event.function
import zope.security.checker
@@ -127,5 +126,3 @@
return find_global(modulename, globalname, Broken_, type_)
event.database.classFactory = classFactory
-
-installBrokenSubscriber = zope.app.event.function.Subscriber(installBroken)
Modified: Zope3/trunk/src/zope/app/broken/configure.zcml
===================================================================
--- Zope3/trunk/src/zope/app/broken/configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/broken/configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,15 +1,12 @@
-<configure
- xmlns="http://namespaces.zope.org/zope"
- xmlns:event="http://namespaces.zope.org/event"
- >
+<configure xmlns="http://namespaces.zope.org/zope">
<content class=".broken.Broken">
<allow interface="zope.app.annotation.interfaces.IAnnotations" />
</content>
- <event:subscribe
- subscriber=".broken.installBrokenSubscriber"
- event_types="zope.app.appsetup.IDatabaseOpenedEvent"
+ <subscriber
+ factory=".broken.installBroken"
+ for="zope.app.appsetup.IDatabaseOpenedEvent"
/>
<include file="browser.zcml" />
Modified: Zope3/trunk/src/zope/app/browser.zcml
===================================================================
--- Zope3/trunk/src/zope/app/browser.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/browser.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -8,7 +8,6 @@
<include package="zope.app.traversing.browser" />
<include package="zope.app.container.browser" />
- <include package="zope.app.event.browser" />
<include package="zope.app.registration.browser" />
<include package="zope.app.form.browser" />
<include package="zope.app.utility.browser" />
Modified: Zope3/trunk/src/zope/app/component/configure.zcml
===================================================================
--- Zope3/trunk/src/zope/app/component/configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/component/configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,7 +1,4 @@
-<configure
- xmlns="http://namespaces.zope.org/zope"
- xmlns:event="http://namespaces.zope.org/event"
- >
+<configure xmlns="http://namespaces.zope.org/zope">
<serviceType
id="Utilities"
@@ -52,14 +49,14 @@
provides="zope.component.IServiceService"
for="zope.interface.Interface" />
- <event:subscribe
- subscriber=".localservice.threadSiteSubscriber"
- event_types="zope.app.publication.interfaces.IBeforeTraverseEvent"
+ <subscriber
+ factory=".localservice.threadSiteSubscriber"
+ for="zope.app.publication.interfaces.IBeforeTraverseEvent"
/>
- <event:subscribe
- subscriber=".localservice.clearThreadSiteSubscriber"
- event_types="zope.app.publication.interfaces.IEndRequestEvent"
+ <subscriber
+ factory=".localservice.clearThreadSiteSubscriber"
+ for="zope.app.publication.interfaces.IEndRequestEvent"
/>
</configure>
Modified: Zope3/trunk/src/zope/app/component/localservice.py
===================================================================
--- Zope3/trunk/src/zope/app/component/localservice.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/component/localservice.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -22,7 +22,6 @@
from zope.component.interfaces import IServiceService
from zope.proxy import removeAllProxies
from zope.app.site.interfaces import ISite, ISiteManager
-from zope.app.event.interfaces import ISubscriber
from zope.testing.cleanup import addCleanUp
from zope.app.component.hooks import setSite
from zope.component.service import IGlobalServiceManager
@@ -135,34 +134,22 @@
" IServiceService" % (ob, ))
-class ThreadSiteSubscriber:
+def threadSiteSubscriber(event):
"""A subscriber to BeforeTraverseEvent
Sets the 'site' thread global if the object traversed is a site.
"""
+ if ISite.providedBy(event.object):
+ setSite(event.object)
- implements(ISubscriber)
- def notify(self, event):
- if ISite.providedBy(event.object):
- setSite(event.object)
-
-threadSiteSubscriber = ThreadSiteSubscriber()
-
-
-class ClearThreadSiteSubscriber:
+def clearThreadSiteSubscriber(event):
"""A subscriber to EndRequestEvent
Cleans up the site thread global after the request is processed.
"""
+ clearSite()
- implements(ISubscriber)
- def notify(self, event):
- clearSite()
-
-clearThreadSiteSubscriber = ClearThreadSiteSubscriber()
-
-
# Clear the site thread global
clearSite = setSite
Modified: Zope3/trunk/src/zope/app/component/tests/adapter.py
===================================================================
--- Zope3/trunk/src/zope/app/component/tests/adapter.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/component/tests/adapter.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -27,6 +27,10 @@
class I3(zope.interface.Interface):
pass
+class IS(zope.interface.Interface):
+ pass
+
+
class Adapter:
def __init__(self, *args):
self.context = args
@@ -40,6 +44,7 @@
class A3(Adapter):
zope.interface.implements(I3)
+
def Handler(content, *args):
# uninteresting handler
content.args = getattr(content, 'args', ()) + (args, )
Modified: Zope3/trunk/src/zope/app/component/tests/test_directives.py
===================================================================
--- Zope3/trunk/src/zope/app/component/tests/test_directives.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/component/tests/test_directives.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -24,7 +24,6 @@
from zope.testing.doctestunit import DocTestSuite
from zope.app.component.metaconfigure import interface
from zope.app.content.interfaces import IContentType
-from zope.app.event.interfaces import ISubscriber
from zope.configuration.xmlconfig import xmlconfig, XMLConfig
from zope.configuration.exceptions import ConfigurationError
@@ -103,12 +102,13 @@
def testSubscriber(self):
from zope.app.component.tests.adapter import A1, A2, A3, I3
+ from zope.app.component.tests.adapter import IS
from zope.component.tests.components import Content
xmlconfig(StringIO(template % (
"""
<subscriber
- provides="zope.app.event.interfaces.ISubscriber"
+ provides="zope.app.component.tests.adapter.IS"
factory="zope.app.component.tests.adapter.A3"
for="zope.component.tests.components.IContent
zope.app.component.tests.adapter.I1"
@@ -118,7 +118,7 @@
content = Content()
a1 = A1()
- subscribers = zapi.subscribers((content, a1), ISubscriber)
+ subscribers = zapi.subscribers((content, a1), IS)
a3 = subscribers[0]
@@ -147,18 +147,19 @@
def testMultiSubscriber(self):
from zope.app.component.tests.adapter import A1, A2, A3, I3
+ from zope.app.component.tests.adapter import IS
from zope.component.tests.components import Content
xmlconfig(StringIO(template % (
"""
<subscriber
- provides="zope.app.event.interfaces.ISubscriber"
+ provides="zope.app.component.tests.adapter.IS"
factory="zope.app.component.tests.adapter.A3"
for="zope.component.tests.components.IContent
zope.app.component.tests.adapter.I1"
/>
<subscriber
- provides="zope.app.event.interfaces.ISubscriber"
+ provides="zope.app.component.tests.adapter.IS"
factory="zope.app.component.tests.adapter.A2"
for="zope.component.tests.components.IContent
zope.app.component.tests.adapter.I1"
@@ -168,7 +169,7 @@
content = Content()
a1 = A1()
- subscribers = zapi.subscribers((content, a1), ISubscriber)
+ subscribers = zapi.subscribers((content, a1), IS)
expectedLength = 2
self.assertEqual(len(subscribers), expectedLength)
Modified: Zope3/trunk/src/zope/app/component/tests/test_localservice.py
===================================================================
--- Zope3/trunk/src/zope/app/component/tests/test_localservice.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/component/tests/test_localservice.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -26,7 +26,6 @@
from zope.component.service import serviceManager
from zope.interface import implements, directlyProvides, directlyProvidedBy
from zope.interface.verify import verifyObject
-from zope.app.event.interfaces import ISubscriber
from zope.app.tests.setup import placelessSetUp, placelessTearDown
from zope.app.tests import ztapi
from zope.app.component.hooks import setSite, getSite
@@ -240,15 +239,13 @@
from zope.app.component.localservice import clearSite
from zope.app.publication.zopepublication import BeforeTraverseEvent
- verifyObject(ISubscriber, threadSiteSubscriber)
-
self.assertEqual(getSite(), None)
# A non-site is traversed
ob = object()
request = object()
ev = BeforeTraverseEvent(ob, request)
- threadSiteSubscriber.notify(ev)
+ threadSiteSubscriber(ev)
self.assertEqual(getSite(), None)
@@ -258,7 +255,7 @@
site.setSiteManager(ss)
ev = BeforeTraverseEvent(site, request)
- threadSiteSubscriber.notify(ev)
+ threadSiteSubscriber(ev)
self.assertEqual(getSite(), site)
Modified: Zope3/trunk/src/zope/app/configure.zcml
===================================================================
--- Zope3/trunk/src/zope/app/configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -10,10 +10,11 @@
<!-- Note that we need to do this early, as later startup
subscribers may break without fixups -->
+ <include package="zope.app.component" />
+
<include package=".generations" file="subscriber.zcml" />
<!-- Ordinary Application (non-view) configuration) -->
- <include package="zope.app.component" />
<include package="zope.app.interface" />
<include package="zope.app.security" />
<include package="zope.app.event" />
@@ -48,7 +49,6 @@
<!-- Services -->
<include package="zope.app.errorservice" />
- <include package="zope.app.hub" />
<include package="zope.app.pluggableauth" />
<include package="zope.app.site" />
<include package="zope.app.adapter" />
Modified: Zope3/trunk/src/zope/app/container/browser/adding.py
===================================================================
--- Zope3/trunk/src/zope/app/container/browser/adding.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/container/browser/adding.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -33,7 +33,7 @@
from zope.app import zapi
from zope.app.event.objectevent import ObjectCreatedEvent
from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile
-from zope.app.event import publish
+from zope.event import notify
from zope.app.publisher.browser import BrowserView
from zope.app.i18n import ZopeMessageIDFactory as _
@@ -150,7 +150,7 @@
# into unproxying an existing object,
content = removeAllProxies(content)
- publish(self.context, ObjectCreatedEvent(content))
+ notify(ObjectCreatedEvent(content))
self.add(content)
self.request.response.redirect(self.nextURL())
Modified: Zope3/trunk/src/zope/app/container/configure.zcml
===================================================================
--- Zope3/trunk/src/zope/app/container/configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/container/configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -2,7 +2,6 @@
xmlns="http://namespaces.zope.org/zope"
xmlns:browser="http://namespaces.zope.org/browser"
xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc"
- xmlns:event="http://namespaces.zope.org/event"
i18n_domain="zope"
>
@@ -44,9 +43,9 @@
factory=".contained.NameChooser"
/>
- <event:subscribe
- subscriber=".dependency.CheckDependency"
- event_types="zope.app.container.interfaces.IObjectRemovedEvent"
+ <subscriber
+ factory=".dependency.CheckDependency"
+ for="zope.app.container.interfaces.IObjectRemovedEvent"
/>
<content class=".constraints.ItemTypePrecondition">
Modified: Zope3/trunk/src/zope/app/container/contained.py
===================================================================
--- Zope3/trunk/src/zope/app/container/contained.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/container/contained.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -27,7 +27,7 @@
from zope.app.exception.interfaces import UserError
from zope.app.event.objectevent import ObjectEvent, modified
-from zope.app.event import publish
+from zope.event import notify
from zope.app.i18n import ZopeMessageIDFactory as _
from zope.app.container.interfaces import IContained
from zope.app.container.interfaces import INameChooser
@@ -232,20 +232,16 @@
... def setMoved(self, event):
... self.moved = event
- >>> from zope.app.event.objectevent import objectEventCallbackHelper
>>> from zope.app.container.interfaces import IObjectAddedEvent
>>> from zope.app.container.interfaces import IObjectMovedEvent
- >>> from zope.component import getService
- >>> from zope.app.servicenames import Adapters
- >>> from zope.app.event.interfaces import ISubscriber
- >>> factory = objectEventCallbackHelper(
- ... lambda event: event.object.setAdded(event))
- >>> getService(None, Adapters).subscribe(
- ... [IItem,IObjectAddedEvent], ISubscriber, factory)
- >>> factory = objectEventCallbackHelper(
- ... lambda event: event.object.setMoved(event))
- >>> getService(None, Adapters).subscribe(
- ... [IItem, IObjectMovedEvent], ISubscriber, factory)
+ >>> from zope.app.tests import ztapi
+
+ >>> ztapi.handle([IItem, IObjectAddedEvent],
+ ... lambda obj, event: obj.setAdded(event))
+
+ >>> ztapi.handle([IItem, IObjectMovedEvent],
+ ... lambda obj, event: obj.setMoved(event))
+
>>> item = Item()
>>> container = {}
@@ -445,7 +441,7 @@
object, event = containedEvent(object, container, name)
setitemf(name, object)
if event:
- publish(container, event)
+ notify(event)
modified(container)
fixing_up = False
@@ -546,7 +542,7 @@
return
event = ObjectRemovedEvent(object, oldparent, oldname)
- publish(container, event)
+ notify(event)
object.__parent__ = None
object.__name__ = None
Modified: Zope3/trunk/src/zope/app/container/dependency.py
===================================================================
--- Zope3/trunk/src/zope/app/container/dependency.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/container/dependency.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -15,31 +15,19 @@
$Id$
"""
-from zope.proxy import removeAllProxies
-from zope.interface import implements
from zope.app import zapi
from zope.app.dependable.interfaces import IDependable, DependencyError
-from zope.app.event.interfaces import ISubscriber
+from zope.proxy import removeAllProxies
-class DependencyChecker:
- """Checking dependency while deleting object
- """
- implements(ISubscriber)
-
- def __init__(self):
- pass
-
- def notify(self, event):
- object = removeAllProxies(event.object)
- dependency = IDependable(object, None)
- if dependency is not None:
- dependents = dependency.dependents()
- if dependents:
- objectpath = zapi.getPath(event.object)
- raise DependencyError("Removal of object (%s)"
- " which has dependents (%s)"
- % (objectpath,
- ", ".join(dependents)))
-
-CheckDependency = DependencyChecker()
+def CheckDependency(event):
+ object = removeAllProxies(event.object)
+ dependency = IDependable(object, None)
+ if dependency is not None:
+ dependents = dependency.dependents()
+ if dependents:
+ objectpath = zapi.getPath(event.object)
+ raise DependencyError("Removal of object (%s)"
+ " which has dependents (%s)"
+ % (objectpath,
+ ", ".join(dependents)))
Modified: Zope3/trunk/src/zope/app/copypastemove/__init__.py
===================================================================
--- Zope3/trunk/src/zope/app/copypastemove/__init__.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/copypastemove/__init__.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -20,7 +20,7 @@
from zope.app import zapi
from zope.app.container.sample import SampleContainer
-from zope.app.event import publish
+from zope.event import notify
from zope.app.event.objectevent import ObjectCopiedEvent
from zope.app.copypastemove.interfaces import IObjectMover
from zope.app.copypastemove.interfaces import IObjectCopier
@@ -374,7 +374,7 @@
copy = removeAllProxies(obj)
copy = locationCopy(copy)
copy.__parent__ = copy.__name__ = None
- publish(target, ObjectCopiedEvent(copy))
+ notify(ObjectCopiedEvent(copy))
target[new_name] = copy
Modified: Zope3/trunk/src/zope/app/dav/mkcol.py
===================================================================
--- Zope3/trunk/src/zope/app/dav/mkcol.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/dav/mkcol.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -16,7 +16,7 @@
from zope.app import zapi
from zope.app.filerepresentation.interfaces import IWriteDirectory
from zope.app.filerepresentation.interfaces import IDirectoryFactory
-from zope.app.event import publish
+from zope.event import notify
from zope.app.event.objectevent import ObjectCreatedEvent
class NullResource(object):
@@ -46,7 +46,7 @@
factory = IDirectoryFactory(container)
newdir = factory(name)
- publish(self.context, ObjectCreatedEvent(newdir))
+ notify(ObjectCreatedEvent(newdir))
dir[name] = newdir
request.response.setStatus(201)
Modified: Zope3/trunk/src/zope/app/demo/jobboard/browser.py
===================================================================
--- Zope3/trunk/src/zope/app/demo/jobboard/browser.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/demo/jobboard/browser.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,6 +1,6 @@
from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile
from zope.app.publisher.browser import BrowserView
-from zope.app.event import publish
+from zope.event import notify
from zope.app.event.objectevent import ObjectCreatedEvent, ObjectModifiedEvent
@@ -38,7 +38,7 @@
# Validation code should go here
job = Job(submitter, summary, description, contact)
self.context.add(job)
- publish(self.context,ObjectModifiedEvent(self.context))
+ notify(ObjectModifiedEvent(self.context))
return self.thanks()
@@ -100,5 +100,5 @@
response.redirect('review.html')
else:
response.redirect('.')
- publish(self.context,ObjectModifiedEvent(self.context))
+ notify(ObjectModifiedEvent(self.context))
Modified: Zope3/trunk/src/zope/app/demo/jobboard/job.py
===================================================================
--- Zope3/trunk/src/zope/app/demo/jobboard/job.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/demo/jobboard/job.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -47,7 +47,7 @@
from persistent.dict import PersistentDict
-from zope.app.event import publish
+from zope.event import notify
from zope.app.event.objectevent import ObjectCreatedEvent
class JobList(Persistent):
Modified: Zope3/trunk/src/zope/app/dublincore/browser/metadataedit.py
===================================================================
--- Zope3/trunk/src/zope/app/dublincore/browser/metadataedit.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/dublincore/browser/metadataedit.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -16,7 +16,7 @@
$Id$
"""
from datetime import datetime
-from zope.app.event import publish
+from zope.event import notify
from zope.app.event.objectevent import ObjectAnnotationsModifiedEvent
from zope.app.i18n import ZopeMessageIDFactory as _
from zope.app.dublincore.interfaces import IZopeDublinCore
@@ -35,7 +35,7 @@
if 'dctitle' in request:
dc.title = request['dctitle']
dc.description = request['dcdescription']
- publish(self.context, ObjectAnnotationsModifiedEvent(self.context))
+ notify(ObjectAnnotationsModifiedEvent(self.context))
message = _("Changed data ${datetime}")
message.mapping = {'datetime': formatter.format(datetime.utcnow())}
Modified: Zope3/trunk/src/zope/app/dublincore/configure.zcml
===================================================================
--- Zope3/trunk/src/zope/app/dublincore/configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/dublincore/configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,6 +1,4 @@
-<configure
- xmlns="http://namespaces.zope.org/zope"
- xmlns:event="http://namespaces.zope.org/event">
+<configure xmlns="http://namespaces.zope.org/zope">
<permission
id="zope.app.dublincore.view"
@@ -42,23 +40,27 @@
/>
</content>
- <event:subscribe
- subscriber=".timeannotators.ModifiedAnnotator"
- event_types="zope.app.event.interfaces.IObjectModifiedEvent"
+ <subscriber
+ factory=".timeannotators.ModifiedAnnotator"
+ for="zope.app.event.interfaces.IObjectModifiedEvent"
/>
- <event:subscribe
- subscriber=".timeannotators.CreatedAnnotator"
- event_types="zope.app.event.interfaces.IObjectCreatedEvent"
+ <subscriber
+ factory=".timeannotators.CreatedAnnotator"
+ for="zope.app.event.interfaces.IObjectCreatedEvent"
/>
- <event:subscribe
- subscriber=".creatorannotator.CreatorAnnotator"
- event_types="zope.app.event.interfaces.IObjectModifiedEvent
- zope.app.event.interfaces.IObjectCreatedEvent"
- />
+ <subscriber
+ factory=".creatorannotator.CreatorAnnotator"
+ for="zope.app.event.interfaces.IObjectModifiedEvent"
+ />
+ <subscriber
+ factory=".creatorannotator.CreatorAnnotator"
+ for="zope.app.event.interfaces.IObjectCreatedEvent"
+ />
+
<!-- Include browser package -->
<include package=".browser" />
Modified: Zope3/trunk/src/zope/app/dublincore/creatorannotator.py
===================================================================
--- Zope3/trunk/src/zope/app/dublincore/creatorannotator.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/dublincore/creatorannotator.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -16,27 +16,21 @@
$Id$
"""
from zope.app.dublincore.interfaces import IZopeDublinCore
-from zope.app.event.interfaces import ISubscriber
from zope.security.management import queryInteraction
-from zope.interface import implements
-class CreatorAnnotatorClass(object):
+def CreatorAnnotator(event):
"""Update Dublin-Core creator property"""
- implements(ISubscriber)
+ dc = IZopeDublinCore(event.object, None)
+ if dc is None:
+ return
- def notify(self, event):
- dc = IZopeDublinCore(event.object, None)
- if dc is None:
- return
+ # Try to find a principal for that one. If there
+ # is no principal then we don't touch the list
+ # of creators.
+ interaction = queryInteraction()
+ if interaction is not None:
+ for participation in interaction.participations:
+ principalid = participation.principal.id
+ if not principalid in dc.creators:
+ dc.creators = dc.creators + (unicode(principalid), )
- # Try to find a principal for that one. If there
- # is no principal then we don't touch the list
- # of creators.
- interaction = queryInteraction()
- if interaction is not None:
- for participation in interaction.participations:
- principalid = participation.principal.id
- if not principalid in dc.creators:
- dc.creators = dc.creators + (unicode(principalid), )
-
-CreatorAnnotator = CreatorAnnotatorClass()
Modified: Zope3/trunk/src/zope/app/dublincore/tests/test_creatorannotator.py
===================================================================
--- Zope3/trunk/src/zope/app/dublincore/tests/test_creatorannotator.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/dublincore/tests/test_creatorannotator.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -25,14 +25,13 @@
from zope.app.dublincore.creatorannotator import CreatorAnnotator
from zope.app.dublincore.interfaces import IZopeDublinCore
from zope.app.security.interfaces import IPrincipal
-from zope.app.event.interfaces import IEvent
from zope.security.management import newInteraction, endInteraction
class IDummyContent(Interface):
pass
class DummyEvent:
- implements(IEvent)
+ pass
class DummyDCAdapter(object):
@@ -96,13 +95,13 @@
# Check what happens if no user is there
newInteraction(None)
- CreatorAnnotator.notify(event)
+ CreatorAnnotator(event)
self.assertEqual(data.creators,())
endInteraction()
# Let the bad edit it first
newInteraction(DummyRequest(bad_author))
- CreatorAnnotator.notify(event)
+ CreatorAnnotator(event)
self.failIf(len(data.creators) != 1)
self.failUnless(bad_author.id in data.creators)
@@ -110,7 +109,7 @@
# Now let the good edit it
newInteraction(DummyRequest(good_author))
- CreatorAnnotator.notify(event)
+ CreatorAnnotator(event)
self.failIf(len(data.creators) != 2)
self.failUnless(good_author.id in data.creators)
@@ -119,7 +118,7 @@
# Let the bad edit it again
newInteraction(DummyRequest(bad_author))
- CreatorAnnotator.notify(event)
+ CreatorAnnotator(event)
# Check that the bad author hasn't been added twice.
self.failIf(len(data.creators) != 2)
Modified: Zope3/trunk/src/zope/app/dublincore/timeannotators.py
===================================================================
--- Zope3/trunk/src/zope/app/dublincore/timeannotators.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/dublincore/timeannotators.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -15,42 +15,18 @@
$Id$
"""
-__metaclass__ = type
from datetime import datetime
from zope.app.dublincore.interfaces import IZopeDublinCore
-from zope.app.event.interfaces import ISubscriber
-from zope.interface import implements
-class DCTimeAnnotatorBase:
- """Update Dublin-Core time property
- """
- implements(ISubscriber)
-
- def notify(self, event):
- dc = IZopeDublinCore(event.object, None)
- if dc is not None:
- self.annotate(dc)
-
- def annotate(self, dc):
- raise RuntimeError, 'annotate not implemented'
-
-
-class ModifiedAnnotatorClass(DCTimeAnnotatorBase):
- """Updates DC modified when an object is modified."""
-
- def annotate(self, dc):
+def ModifiedAnnotator(event):
+ dc = IZopeDublinCore(event.object, None)
+ if dc is not None:
dc.modified = datetime.utcnow()
-
-class CreatedAnnotatorClass(DCTimeAnnotatorBase):
- """Sets DC created and modified when an object is created."""
-
- def annotate(self, dc):
+def CreatedAnnotator(event):
+ dc = IZopeDublinCore(event.object, None)
+ if dc is not None:
now = datetime.utcnow()
dc.created = now
dc.modified = now
-
-
-ModifiedAnnotator = ModifiedAnnotatorClass()
-CreatedAnnotator = CreatedAnnotatorClass()
Modified: Zope3/trunk/src/zope/app/event/__init__.py
===================================================================
--- Zope3/trunk/src/zope/app/event/__init__.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/__init__.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,42 +1,19 @@
##############################################################################
#
-# Copyright (c) 2002 Zope Corporation and Contributors.
+# Copyright (c) 2004 Zope Corporation and Contributors.
# All Rights Reserved.
-#
+#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
-#
+#
##############################################################################
"""
+
$Id$
"""
-from zope.component import getService
-from zope.app.servicenames import EventPublication
-from zope.app.event.interfaces import IEvent
-from zope.app.event.globalservice import eventPublisher
-# XXX convert these as well
-def getEventService(context): # the "publish" service
- return getService(EventPublication, context=context)
-
-def publish(context, event):
- return getEventService(context).publish(event)
-
-def globalSubscribe(subscriber, event_type=IEvent, filter=None):
- return eventPublisher.globalSubscribe(subscriber, event_type, filter)
-
-def globalSubscribeMany(subscriber, event_types=(IEvent,), filter=None):
- subscribe_func = eventPublisher.globalSubscribe
- for event_type in event_types:
- subscribe_func(subscriber, event_type, filter)
-
-def globalUnsubscribe(subscriber, event_type=None, filter=None):
- return eventPublisher.unsubscribe(subscriber, event_type, filter)
-
-def globalListSubscriptions(subscriber, event_type=None):
- return eventPublisher.listSubscriptions(subscriber, event_type)
-
+from dispatching import publish
Modified: Zope3/trunk/src/zope/app/event/configure.zcml
===================================================================
--- Zope3/trunk/src/zope/app/event/configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -3,37 +3,9 @@
xmlns:event="http://namespaces.zope.org/event"
>
-<serviceType
- id="EventPublication"
- interface="zope.app.event.interfaces.IPublisher" />
-
-<service
- serviceType="EventPublication"
- component="zope.app.event.globalservice.eventPublisher" />
-
-<event:subscribe
- subscriber=".objectevent.objectEventNotifierInstance"
- event_types="zope.app.event.interfaces.IObjectEvent" />
-
-<!-- Local Event Service -->
-<content class=".localservice.EventService">
- <factory
- id="Events"
- />
- <require
- permission="zope.View"
- attributes="publish notify"
- />
- <require
- permission="zope.ManageServices"
- attributes="bound unbound subscribe unsubscribe subscribeOnBind
- unsubscribedFrom subscribedTo"
- />
-</content>
-
-<serviceType
- id="Subscription"
- interface=".interfaces.ISubscriptionService"
+<subscriber
+ for="zope.app.event.interfaces.IObjectEvent"
+ factory=".objectevent.objectEventNotify"
/>
</configure>
Copied: Zope3/trunk/src/zope/app/event/dispatching.py (from rev 25030, Zope3/branches/jim-simplifyevents/src/zope/app/event/dispatching.py)
Property changes on: Zope3/trunk/src/zope/app/event/dispatching.py
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Deleted: Zope3/trunk/src/zope/app/event/function.py
===================================================================
--- Zope3/trunk/src/zope/app/event/function.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/function.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,47 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2003 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""Class to create an event subscriber from a simple function.
-
-$Id$
-"""
-
-from zope.interface import implements
-from zope.app.event.interfaces import ISubscriber
-
-
-class Subscriber:
- """Event subscriber that calls a function when an event is received.
-
- This is especially useful for creating subscribers from global
- functions that can be registered from ZCML:
-
- from zope.app.event import function
-
- def startupEventHandler(event):
- # do something useful with event:
- pass
-
- startupEventHandler = function.Subscriber(startupEventHandler)
-
- And then use this ZCML:
-
- <event:subscribe
- subscriber='.module.startupEventHandler'
- event_types='zope.app.appsetup.IProcessStartingEvent'
- />
- """
- implements(ISubscriber)
-
- def __init__(self, function):
- self.notify = function
Deleted: Zope3/trunk/src/zope/app/event/globalservice.py
===================================================================
--- Zope3/trunk/src/zope/app/event/globalservice.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/globalservice.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,237 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""
-$Id$
-"""
-
-__metaclass__ = type
-
-from zope.interface.type import TypeRegistry
-from zope.interface import implements
-from zope.exceptions import NotFoundError
-from zope.proxy import removeAllProxies
-
-from zope.app.event.interfaces import IEvent, ISubscriber, ISubscribingAware
-from zope.app.event.interfaces import IGlobalSubscribable, IPublisher
-
-import logging
-import pprint
-from StringIO import StringIO
-
-def checkEventType(event_type, allow_none=False):
- if not (
- (allow_none and event_type is None)
- or event_type.extends(IEvent, strict=False)
- ):
- raise TypeError('event_type must extend IEvent: %s' % repr(event_type))
-
-class Logger:
- """Class to log all events sent out by an event service.
-
- This is an event subscriber that you can add via ZCML to log all
- events sent out by Zope.
- """
-
- implements(ISubscriber)
-
- def __init__(self, severity=logging.INFO):
- self.severity = severity
- self.logger = logging.getLogger("Event.Logger")
-
- def notify(self, event):
- c = event.__class__
- detail = StringIO()
- data = event.__dict__.items()
- data.sort()
- # XXX The detail output could be improved. Not sure what is wanted.
- pprint.pprint(data, detail)
- self.logger.log(self.severity, "%s.%s: %s",
- c.__module__, c.__name__, detail.getvalue())
-
-
-class GlobalSubscribable:
- """A global mix-in"""
-
- implements(IGlobalSubscribable)
-
- def __init__(self):
- self._registry = TypeRegistry()
- self._subscribers = [] # use dict?
-
- _clear = __init__
-
- def globalSubscribe(self, subscriber, event_type=IEvent, filter=None):
- checkEventType(event_type)
- clean_subscriber = removeAllProxies(subscriber)
-
- subscribingaware = ISubscribingAware(subscriber, None)
- if subscribingaware is not None:
- subscribingaware.subscribedTo(self, event_type, filter)
-
- if event_type is IEvent:
- event_type = None # optimization
-
- subscribers = self._registry.setdefault(event_type, [])
- subscribers.append((clean_subscriber, filter))
-
- for sub in self._subscribers:
- if sub[0] == clean_subscriber:
- try:
- sub[1][event_type] += 1
- except KeyError:
- sub[1][event_type] = 1
- break
- else:
- self._subscribers.append((clean_subscriber, {event_type: 1}))
-
- # Trigger persistence, if pertinent
- # self._registry = self._registry
-
-
- def unsubscribe(self, subscriber, event_type=None, filter=None):
- checkEventType(event_type, allow_none=True)
- clean_subscriber = removeAllProxies(subscriber)
-
- for subscriber_index in range(len(self._subscribers)):
- sub = self._subscribers[subscriber_index]
- if sub[0] == clean_subscriber:
- ev_set = sub[1] # the dict of type:subscriptionCount
- break
- else:
- if event_type is not None:
- raise NotFoundError(subscriber)
- else:
- # this was a generic unsubscribe all request; work may have
- # been done by a local service
- return
-
- subscribingaware = ISubscribingAware(subscriber, None)
-
- if event_type:
- ev_type = event_type
- if event_type is IEvent:
- ev_type = None # handle optimization
- if ev_type not in ev_set:
- raise NotFoundError(subscriber, event_type, filter)
- subscriptions = self._registry.get(ev_type)
- if not subscriptions:
- raise NotFoundError(subscriber, event_type, filter)
- try:
- subscriptions.remove((clean_subscriber, filter))
- except ValueError:
- raise NotFoundError(subscriber, event_type, filter)
- if subscribingaware is not None:
- subscribingaware.unsubscribedFrom(self, event_type, filter)
- ev_set[ev_type] -= 1
- if ev_set[ev_type] < 1:
- for asubscriber, afilter in subscriptions:
- if asubscriber == clean_subscriber:
- break
- else:
- if len(ev_set) > 1:
- del ev_set[ev_type]
- else: # len(ev_set) == 1, and we just eliminated it
- del self._subscribers[subscriber_index]
- else:
- for ev_type in ev_set:
- subscriptions = self._registry.get(ev_type)
- if ev_type is None:
- ev_type = IEvent
- subs = subscriptions[:]
- subscriptions[:] = []
- for asubscriber, afilter in subs:
- if asubscriber == clean_subscriber:
- # deleted (not added back)
- if subscribingaware is not None:
- subscribingaware.unsubscribedFrom(
- self, ev_type, afilter)
- else:
- # kept (added back)
- subscriptions.append(sub)
- del self._subscribers[subscriber_index]
- # Trigger persistence, if pertinent
- # self._registry = self._registry
-
- def listSubscriptions(self, subscriber, event_type=None):
- checkEventType(event_type, allow_none=True)
- subscriber = removeAllProxies(subscriber)
-
- result = []
- if event_type:
- ev_type = event_type
- if event_type is IEvent:
- ev_type = None # handle optimization
- subscriptions = self._registry.get(ev_type)
- if subscriptions:
- for sub in subscriptions:
- if sub[0] == subscriber:
- result.append((event_type, sub[1]))
- else:
- for subscriber_index in range(len(self._subscribers)):
- sub = self._subscribers[subscriber_index]
- if sub[0] == subscriber:
- ev_set = sub[1]
- break
- else:
- return result
- for ev_type in ev_set:
- subscriptions = self._registry.get(ev_type)
- if subscriptions:
- if ev_type is None:
- ev_type = IEvent
- for sub in subscriptions:
- if sub[0] == subscriber:
- result.append((ev_type, sub[1]))
- return result
-
-
-def globalNotifyOrPublish(self, event):
- assert IEvent.providedBy(event)
- subscriptionsForEvent = self._registry.getAllForObject(event)
- for subscriptions in subscriptionsForEvent:
- for subscriber, filter in subscriptions:
- if filter is not None and not filter(event):
- continue
- ISubscriber(subscriber).notify(event)
-
-class GlobalEventChannel(GlobalSubscribable):
-
- implements(IGlobalSubscribable, ISubscriber)
-
- notify = globalNotifyOrPublish
-
-
-class GlobalEventPublisher(GlobalSubscribable):
-
- implements(IGlobalSubscribable, IPublisher)
-
- publish = globalNotifyOrPublish
-
-
-# Repeated here, and in zope/app/event/__init__.py to avoid circular import.
-def globalSubscribeMany(subscriber, event_types=(IEvent,), filter=None):
- subscribe_func = eventPublisher.globalSubscribe
- for event_type in event_types:
- subscribe_func(subscriber, event_type, filter)
-
-eventPublisher = GlobalEventPublisher()
-eventLogger = Logger()
-
-_clear = eventPublisher._clear
-
-# Register our cleanup with Testing.CleanUp to make writing unit tests simpler.
-from zope.testing.cleanup import addCleanUp
-addCleanUp(_clear)
-del addCleanUp
-
Modified: Zope3/trunk/src/zope/app/event/interfaces.py
===================================================================
--- Zope3/trunk/src/zope/app/event/interfaces.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/interfaces.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -17,303 +17,7 @@
"""
from zope.interface import Interface, Attribute
-class IEvent(Interface):
- """The base interface for Events."""
-
-
-class IFilter(Interface):
- """Interface for predicates used to filter events."""
-
- def __call__(event):
- """Return True if event passes, otherwise False."""
-
-
-class IPublisher(Interface):
-
- def publish(event):
- """Publish this event to subscribers.
-
- Events will often be propagated to higher level IPublishers.
- This is a policy decision for the IPublisher.
- """
-
-
-# these are method calls and not events because they are traditional messages
-# between two objects, not events of general interest.
-class ISubscribingAware(Interface):
-
- def subscribedTo(subscribable, event_type, filter):
- """Alerts the object that it has subscribed, via a call from
- itself or from another object, to the subscribable. The
- event_type and filter match the arguments provided to the
- ISubscribable.subscribe.
-
- The subscribable must be appropriately placefully wrapped (note
- that the global event service will have no wrapping)."""
-
- def unsubscribedFrom(subscribable, event_type, filter):
- """Alerts the object that it has unsubscribed, via a call from
- itself or from another object, to the subscribable. The
- event_type and filter match the exact event_type and filter of
- the deleted subscription, rather than, necessarily, the
- arguments provided to the ISubscribable.unsubscribe.
-
- The subscribable must be appropriately placefully wrapped (note
- that the global event service will have no wrapping)."""
-
-
-class ISubscriber(Interface):
- """Interface for objects which receiving event notifications."""
-
- def notify(event):
- """ISubscribables call this method to indicate an event.
-
- This method must not block.
-
- This method may raise an exception to veto the event.
- """
-
-
-class IGlobalSubscribable(Interface):
- """Objects that broadcast events to subscribers.
-
- Subscriptions to a global subscribable are not persistent."""
-
- def globalSubscribe(subscriber, event_type=IEvent, filter=None):
- """Add subscriber to the list of subscribers for the channel.
-
- subscriber must be adaptable to ISubscriber.
-
- event_type, if supplied, is the event interface
- about which subscriber should be notified, and must implement
- IEvent. The subscriber will be notified of all events of this
- event_type and of subclasses of this event_type.
- The default value, IEvent, as the parent type, is effectively a single
- catch-all event type that will pass all event types to the subscriber.
-
- filter, if supplied, must implement IFilter; subscriber
- will be notified of events only if they pass.
-
- A subscriber may subscribe more than once, even if it has
- already been subscribed with the same event type and
- filter. In this case the subscriber will receive multiple
- calls to its notify method.
-
- If the subscriber has an ISubscribingAware adapter, this function
- will call the subscriber's subscribedTo method.
- """
-
- def unsubscribe(subscriber, event_type=IEvent, filter=None):
- """Unsubscribe subscriber from receiving event types from this
- subscribable.
-
- If event_type is IEvent, the default value, the subscriber is
- unsubscribed completely for all event types from this
- subscribable (and its parents, if the subscribable is a placeful
- service). The filter argument is ignored in this case. If no
- subscriptions for this subscriber are present, no error is
- raised.
-
- If event_type is supplied, this method will unsubscribe the
- subscriber from one subscription exactly matching the
- event_type/filter pair given (the default filter being None).
- If other subscriptions are present they will remain. If the
- subscription cannot be found and the subscribable is a placeful
- service, the unsubscription request is passed to parent
- services. Raises Zope.Exceptions.NotFound if subscriber wasn't
- subscribed as expected.
-
- If the subscriber has an ISubscribingAware adapter, this function
- will call the subscriber's unsubscribedFrom method for each
- individual unsubscribe.
- """
-
- def listSubscriptions(subscriber, event_type=IEvent):
- """Returns an iterator of the subscriptions to this channel for
- the subscriber. If event_type is supplied, the list is limited
- to that exact event_type. If the subscribable is a placeful
- service, the list will include subscriptions to parent services.
- No subscriptions returns an empty iterator. Each subscription is
- represented as a tuple (event_type, filter)."""
-
-
-class ISubscribable(Interface):
- """A subscribable that only works with physically locatable objects,
- or their paths or hubids."""
-
- def subscribe(reference, event_type=IEvent, filter=None):
- """Add subscriber to the list of subscribers for the component.
-
- Subscriber must have an ISubscriber adapter, and must be accessible
- via path. The reference passed to the method may be a hard
- reference, contextually wrapped if appropriate; or a path or
- hubid that reference the subscriber.
-
- If the subscriber is a wrapped object then it will be
- subscribed on the basis of hubid, if available for the object,
- and path otherwise; passing the path or the hubid uses that
- explicitly. In all cases, the method passes back the hubid or
- path used to subscribe on success.
-
- event_type, if supplied, is the event interface
- about which subscriber should be notified, and must implement
- IEvent. The subscriber will be notified of all events of this
- event_type and of subclasses of this event_type.
- The default value, IEvent, as the parent type, is effectively a
- single catch-all event type that will pass all event types to
- the subscriber.
-
- filter, if supplied, must implement IFilter; subscriber
- will be notified of events only if they pass. filter must be
- picklable.
-
- A subscriber may subscribe more than once, even if it has
- already been subscribed with the same event type and
- filter. In this case the subscriber will receive multiple
- calls to its notify method.
-
- If the subscriber has an ISubscribingAware adapter, this method
- will call the subscriber's subscribedTo method.
- """
-
- def unsubscribe(reference, event_type, filter=None):
- """Removes just one subscription.
-
- This is in parity with subscribe providing just one subscription.
-
- A filter of None means 'the subscription with no filter' rather
- than 'a subscription with any filter'.
-
- A subscriber is determined based on the reference supplied.
-
- If 'reference' is an object, it must be physically locatable so
- we can get its path. We try to remove a subscription based on the
- hubId (if available). If there is no hubId or no such subscription,
- we try to remove a subscription based on the path.
-
- If 'reference' is an int, it is interpreted as a hubId. We try to
- remove a subscription by hubId, and then by path.
-
- If 'reference' is a string or unicode, it is interpreted as an
- absolute path. We try to remove a subscription by path, and then
- by hubId.
-
- If a subscription is removed, and the subscriber has an
- ISubscribingAware adapter, the adapter's unsubscribedFrom method
- is called.
- If no subscription can be removed, we raise a NotFoundError.
-
- If a path or hubId is given that no longer resolves to an object,
- and such a subscription exists, then that subscription will be
- removed and a warning logged.
- """
-
- def unsubscribeAll(reference, event_type=IEvent):
- """Removes all subscriptions for subscriber that match event_type.
-
- The subscriber is determined from the reference as described in
- the docstring of the 'unsubscribe' method.
-
- If a path and hubId can be determined for the subscriber,
- all subscriptions by both path and hubId that match event_type
- are removed.
-
- Subscriptions are removed only if the event in the subscription
- is event_type, or extends event_type.
-
- Returns the number of subscriptions removed.
- """
-
- def resubscribeByHubId(reference):
- """Change all subscriptions for reference by path into subscriptions
- by hubId.
-
- The reference may be a hubId, a path or a physically locatable object.
-
- Returns the number of subscriptions converted.
- """
-
- def resubscribeByPath(reference):
- """Change all subscriptions for reference by hubId into subscriptions
- by path.
-
- The reference may be a hubId, a path or a physically locatable object.
-
- Returns the number of subscriptions converted.
- """
-
- def iterSubscriptions(reference=None, event_type=IEvent):
- """Returns an iterator of the subscriptions to this channel for
- the referenced subscriber.
-
- The reference may be a hubId, a path or a physically locatable object.
- Subscriptions by hubId and by path are returned.
- The reference may also be None, meaning that subscriptions for all
- subscribers are to be returned.
-
- If event_type is supplied, only those subscriptions where the
- event_type of the subscription extends or is equal to the given
- event_type will be returned.
-
- Each element of the iteration is a three-tuple:
-
- (reference, event_type, filter)
-
- The first element of the tuple will the int or unicode that is
- subscribed. The second element is the event_type subscribed.
- The third is the filter subscribed.
- """
-
-class ISubscriptionService(ISubscribable):
- """A Subscribable that implements the Subscription service."""
- def unsubscribe(reference, event_type, filter=None):
- '''See ISubscribable.unsubscribe
-
- In addition, if the reference cannot be unsubscribed in this service,
- pass this on to the next service.
- '''
-
- def unsubscribeAll(reference, event_type=IEvent, local_only=False):
- '''See ISubscribable.unsubscribeAll
-
- If local_only is True, only subscriptions to this event service
- instance are removed.
- Otherwise, the unsubscribeAll request is passed on to the next
- service.
- '''
-
- def resubscribeByHubId(reference):
- '''See ISubscribable.resubscribeByHubId
-
- In addition, the request is passed on to the next service.
- '''
-
- def resubscribeByPath(reference):
- '''See ISubscribable.resubscribeByPath
-
- In addition, the request is passed on to the next service.
- '''
-
- def iterSubscriptions(reference, event_type=IEvent, local_only=False):
- '''See ISubscribable.iterSubscriptions
-
- If local_only is True, only subscriptions to this event service
- instance are returned.
- Otherwise, after subscriptions to this event service, subscriptions
- to the next event service are returned.
- '''
-
-class IEventChannel(ISubscribable, ISubscriber):
- """Interface for objects which distribute events to subscribers. """
-
-class IEventService(ISubscriptionService, IPublisher):
- """Local event service implementation.
-
- Offers the Events and Subscription services.
- """
-
-
-class IObjectEvent(IEvent):
+class IObjectEvent(Interface):
"""Something has happened to an object.
The object that generated this event is not necessarily the object
Deleted: Zope3/trunk/src/zope/app/event/localservice.py
===================================================================
--- Zope3/trunk/src/zope/app/event/localservice.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/localservice.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,428 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""Local Event Service and related classes.
-
-$Id$
-"""
-import logging
-from zope.exceptions import NotFoundError
-
-from zope.app import zapi
-
-from zope.component import queryService
-from zope.app.event.interfaces import IEvent, ISubscriber, IEventChannel
-from zope.app.event.interfaces import ISubscriptionService, IEventService
-from zope.app.site.interfaces import IBindingAware
-
-from zope.component import ComponentLookupError
-from zope.app.servicenames import HubIds, EventPublication, EventSubscription
-from zope.app.component.localservice import getNextService, queryNextService
-
-from zope.proxy import removeAllProxies
-from zope.interface import implements
-
-from zope.app.event.subs import Subscribable, SubscriptionTracker
-
-from zope.security.proxy import trustedRemoveSecurityProxy
-from zope.app.container.contained import Contained
-
-
-def getSubscriptionService(context):
- return zapi.getService(context, EventSubscription)
-
-def subscribe(subscriber, event_type=IEvent, filter=None, context=None):
- if context is None and not isinstance(subscriber, (int, str, unicode)):
- context = subscriber
- return getSubscriptionService(context).subscribe(
- subscriber, event_type, filter)
-
-def subscribeMany(subscriber, event_types=(IEvent,),
- filter=None, context=None):
- if context is None and not isinstance(subscriber, (int, str, unicode)):
- context = subscriber
- subscribe = getSubscriptionService(context).subscribe
- for event_type in event_types:
- subscribe(subscriber, event_type, filter)
-
-def unsubscribe(subscriber, event_type, filter=None, context=None):
- if context is None and not isinstance(subscriber, (int, str, unicode)):
- context = subscriber
- return getSubscriptionService(context).unsubscribe(
- subscriber, event_type, filter)
-
-def unsubscribeAll(subscriber, event_type=IEvent, context=None,
- local_only=False):
- if context is None and not isinstance(subscriber, (int, str, unicode)):
- context = subscriber
- return getSubscriptionService(context).unsubscribeAll(
- subscriber, event_type, local_only=local_only)
-
-def iterSubscriptions(subscriber=None, event_type=None, local_only=False,
- context=None):
- if context is None and not isinstance(subscriber, (int, str, unicode)):
- context = subscriber
- return getSubscriptionService(context).iterSubscriptions(
- subscriber, event_type, local_only)
-
-
-class EventChannel(Subscribable):
-
- implements(IEventChannel)
-
- # needs __init__ from zope.app.event.subs.Subscribable
-
- def _notify(clean_self, wrapped_self, event):
- subscriptionsForEvent = clean_self._registry.getAllForObject(event)
- hubIdsService = queryService(wrapped_self, HubIds)
- if hubIdsService is None:
- # This will only happen if there is no HubIds service.
- # This is only true at start-up, so we don't bother testing
- # whether hubGet is None in the loop below.
- hubGet = None
- else:
- hubGet = hubIdsService.getObject
-
- root = removeAllProxies(zapi.getRoot(wrapped_self))
-
- badSubscribers = {} # using a dict as a set
- for subscriptions in subscriptionsForEvent:
- for subscriber,filter in subscriptions:
- if filter is not None and not filter(event):
- continue
- if isinstance(subscriber, int):
- try:
- obj = hubGet(subscriber)
-
- # XXX we need to figure out exactly how we want to
- # handle this. For now, we'll assume that all
- # subscriptions are trusted, so can always notify
- obj = trustedRemoveSecurityProxy(obj)
- except NotFoundError:
- badSubscribers[subscriber] = None
- continue
- else:
- try:
- obj = zapi.traverse(root, subscriber)
- except NotFoundError:
- badSubscribers[subscriber] = None
- continue
- # Get an ISubscriber adapter in the context of the object
- # This is probably the right context to use.
- #
- # Using getAdapter rather than queryAdapter because if there
- # is no ISubscriber adapter available, that is an application
- # error that should be fixed. So, failing is appropriate, and
- # adding this subscriber to badSubscribers is inappropriate.
- ISubscriber(obj).notify(event)
-
- for subscriber in badSubscribers:
- logging.getLogger('SiteError').warn(
- "Notifying a subscriber that does not exist."
- " Unsubscribing it: %s" % subscriber)
- # Also, is it right that we should sometimes have
- # "write caused by a read" semantics? I'm seeing notify() as
- # basically a read, and (un)subscribe as a write.
- wrapped_self.unsubscribeAll(subscriber)
-
- def notify(wrapped_self, event):
- clean_self = removeAllProxies(wrapped_self)
- clean_self._notify(wrapped_self, event)
-
-
-class ServiceSubscriberEventChannel(SubscriptionTracker, EventChannel):
- """An event channel that wants to subscribe to the nearest
- event service when bound, and unsubscribe when unbound.
- """
-
- implements(IBindingAware)
-
- def __init__(self):
- SubscriptionTracker.__init__(self)
- EventChannel.__init__(self)
-
- subscribeOnBind = True
- # if true, event service will subscribe
- # to the parent event service on binding, unless the parent
- # service is the global event service; see 'bound' method
- # below
-
- _serviceName = None
- # the name of the service that this object is providing, or
- # None if unbound
-
- _subscribeToServiceName = EventSubscription
- _subscribeToServiceInterface = IEvent
- _subscribeToServiceFilter = None
-
- def subscribe(self, reference, event_type=IEvent, filter=None):
- if getattr(self, "_v_ssecunbinding", None) is not None:
- raise Exception(
- 'Cannot subscribe to a subscriber that is unbinding.')
- return super(ServiceSubscriberEventChannel, self
- ).subscribe(reference, event_type, filter)
-
- def bound(wrapped_self, name):
- "See IBindingAware"
- # Note: if a component is used for more than one service then
- # this and the unbound code must be conditional for the
- # pertinent service that should trigger event subscription
- clean_self = removeAllProxies(wrapped_self)
- clean_self._serviceName = name # for ServiceSubscribable
- if clean_self.subscribeOnBind:
- es = queryService(
- wrapped_self, clean_self._subscribeToServiceName)
- if es is not None:
- if removeAllProxies(es) is clean_self:
- es = queryNextService(
- wrapped_self, clean_self._subscribeToServiceName)
- if es is None:
- subscribe_to = clean_self._subscribeToServiceName
- logging.getLogger('SiteError').warn(
- "Unable to subscribe %s service to the %s service "
- "while binding the %s service. This is because the "
- "%s service could not be found." %
- (name, subscribe_to, name, subscribe_to))
- else:
- es.subscribe(
- wrapped_self,
- clean_self._subscribeToServiceInterface,
- clean_self._subscribeToServiceFilter
- )
-
- def unbound(wrapped_self, name):
- "See IBindingAware"
- # Note: if a component is used for more than one service then
- # this and the unbound code must be conditional for the
- # pertinent service that should trigger event subscription
-
- clean_self = removeAllProxies(wrapped_self)
-
- # unsubscribe all subscriptions
- hubIds = clean_self._hubIds
- unsubscribeAll = wrapped_self.unsubscribeAll
-
- # XXX Temporary hack to make unsubscriptions local in scope when
- # this mix-in is used as part of a subscriptions service.
- # The dependences of these mixins need to be documented and
- # reevaluated.
- if ISubscriptionService.providedBy(wrapped_self):
- real_unsubscribeAll = unsubscribeAll
- unsubscribeAll = lambda x: real_unsubscribeAll(x, local_only=True)
-
- try:
- clean_self._v_ssecunbinding = True
- while hubIds:
- hubId = iter(hubIds).next()
- # XXX This code path needs a unit test!
- # This code is also wrong.
- # The call to unsubscribeAll assumes that whatever class
- # mixes this class in provides an unsubscribeAll method
- # that correctly uses the self._subscribeToServiceName
- # to decide what it should be unsubscribing from.
- # This could be any service that implements
- # ISubscriptionService
- unsubscribeAll(hubId)
-
- paths = clean_self._paths
- while paths:
- path = iter(paths).next()
- # XXX This code path needs a unit test!
- # Also, see comment above.
- unsubscribeAll(path)
- finally:
- del clean_self._v_ssecunbinding
-
- assert len(paths) == len(hubIds) == len(clean_self._registry) == 0
-
- clean_self._serviceName = None
-
-
-class ServiceSubscribable(Subscribable):
- """A mix-in for local event services.
-
- * unsubscribe() asks the next higher service to unsubscribe if this
- service cannot.
-
- * unsubscribeAll() does the same.
-
- * listSubscriptions() includes this service's subscriptions, and
- those of the next higher service.
- """
-
- _serviceName = None # should be replaced; usually done in "bound"
- # method of a subclass that is IBindingAware
-
- # requires __init__ from zope.app.event.subs.Subscribable
-
- def unsubscribe(self, reference, event_type, filter=None):
- # The point here is that if we can't unsubscribe here, we should
- # allow the next event service to unsubscribe.
- try:
- super(ServiceSubscribable, self
- ).unsubscribe(reference, event_type, filter)
- except NotFoundError:
- next_service = queryNextService(self,
- self._serviceName)
- if next_service is not None:
- next_service.unsubscribe(reference, event_type, filter)
- else:
- raise
-
- def unsubscribeAll(self, reference, event_type=IEvent,
- local_only=False):
- # unsubscribe all from here, and from the next service
-
- # n is the number of subscriptions removed
- n = super(ServiceSubscribable, self
- ).unsubscribeAll(reference, event_type)
- if not local_only:
- next_service = queryNextService(self, self._serviceName)
- if next_service is not None:
- n += next_service.unsubscribeAll(reference, event_type)
- return n
-
- def resubscribeByHubId(self, reference):
- n = super(ServiceSubscribable, self
- ).resubscribeByHubId(reference)
- next_service = queryNextService(self, self._serviceName)
- if next_service is not None:
- n += next_service.resubscribeByHubId(reference)
- return n
-
- def resubscribeByPath(self, reference):
- n = super(ServiceSubscribable, self
- ).resubscribeByPath(reference)
- next_service = queryNextService(self, self._serviceName)
- if next_service is not None:
- n += next_service.resubscribeByPath(reference)
- return n
-
- def iterSubscriptions(self, reference=None, event_type=IEvent,
- local_only=False):
- 'See ISubscriptionService'
- subs = super(ServiceSubscribable, self
- ).iterSubscriptions(reference, event_type)
- for subscription in subs:
- yield subscription
-
- if not local_only:
- next_service = queryNextService(self, self._serviceName)
- if next_service is not None:
- for subscription in next_service.iterSubscriptions(
- reference, event_type):
- yield subscription
-
-
-from zope.app.site.interfaces import ISimpleService
-
-class EventService(ServiceSubscriberEventChannel, ServiceSubscribable,
- Contained):
-
- implements(IEventService, ISubscriptionService, ISimpleService)
-
- def __init__(self):
- ServiceSubscriberEventChannel.__init__(self)
- ServiceSubscribable.__init__(self)
-
- def isPromotableEvent(self, event):
- """A hook. Returns True if, when publishing an event, the event
- should also be promoted to the next (higher) level of event service,
- and False otherwise."""
- # XXX A probably temporary appendage. Depending on the usage,
- # this should be (a) kept as is, (b) made into a registry, or
- # (c) removed.
- return True
-
- def publish(wrapped_self, event):
- "see IEventPublisher"
- clean_self = removeAllProxies(wrapped_self)
-
- publishedEvents = getattr(clean_self, "_v_publishedEvents", [])
- clean_self._v_publishedEvents = publishedEvents
- publishedEvents.append(event)
- try:
- clean_self._notify(wrapped_self, event)
- if clean_self.isPromotableEvent(event):
- getNextService(wrapped_self, EventPublication).publish(event)
- finally:
- publishedEvents.remove(event)
-
- def notify(wrapped_self, event):
- "see ISubscriber"
- clean_self = removeAllProxies(wrapped_self)
- publishedEvents = getattr(clean_self, "_v_publishedEvents", [])
- if event not in publishedEvents:
- clean_self._notify(wrapped_self, event)
-
- def bound(wrapped_self, name):
- "See IBindingAware"
- # An event service is bound as EventSubscription and EventPublication.
- # We only want to subscribe to the next event service when we're bound
- # as EventSubscription
- if name == EventSubscription:
- clean_self = removeAllProxies(wrapped_self)
- clean_self._serviceName = name # for ServiceSubscribable
- if clean_self.subscribeOnBind:
- try:
- es = getNextService(wrapped_self, EventSubscription)
- except ComponentLookupError:
- pass
- else:
- es.subscribe(wrapped_self)
-
- def unbound(self, name):
- "See IBindingAware"
- # An event service is bound as EventSubscription and EventPublication.
- # We only want to unsubscribe from the next event service when
- # we're unbound as EventSubscription
- if name == EventSubscription:
- clean_self = removeAllProxies(self)
-
- # This flag is used by the unsubscribedFrom method (below) to
- # determine that it doesn't need to further unsubscribe beyond
- # what we're already doing.
- clean_self._v_unbinding = True
- try:
- super(EventService, self).unbound(name)
- finally:
- # unset flag
- del clean_self._v_unbinding
-
- def unsubscribedFrom(self, subscribable, event_type, filter):
- "See ISubscribingAware"
- super(EventService, self
- ).unsubscribedFrom(subscribable, event_type, filter)
- clean_self = removeAllProxies(self)
- if getattr(clean_self, "_v_unbinding", None) is None:
- # we presumably have been unsubscribed from a higher-level
- # event service because that event service is unbinding
- # itself: we need to remove the higher level event service
- # from our subscriptions list and try to find another event
- # service to which to attach
- clean_subscribable = removeAllProxies(subscribable)
- if ISubscriptionService.providedBy(
- removeAllProxies(clean_subscribable)):
- try:
- context = zapi.getService(self, EventSubscription)
- # we do this instead of getNextService because the order
- # of unbinding and notification of unbinding is not
- # guaranteed
- while removeAllProxies(context) in (
- clean_subscribable, clean_self):
- context = getNextService(context, EventSubscription)
- except ComponentLookupError:
- pass
- else:
- context.subscribe(self)
-
Deleted: Zope3/trunk/src/zope/app/event/meta.zcml
===================================================================
--- Zope3/trunk/src/zope/app/event/meta.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/meta.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,16 +0,0 @@
-<configure
- xmlns='http://namespaces.zope.org/zope'
- xmlns:meta="http://namespaces.zope.org/meta"
- >
-
- <meta:directives namespace="http://namespaces.zope.org/event">
-
- <meta:directive
- name="subscribe"
- schema=".metadirectives.ISubscribeDirective"
- handler=".metaconfigure.subscribe"
- />
-
- </meta:directives>
-
-</configure>
Deleted: Zope3/trunk/src/zope/app/event/metaconfigure.py
===================================================================
--- Zope3/trunk/src/zope/app/event/metaconfigure.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/metaconfigure.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,31 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""
-$Id$
-"""
-
-from zope.app.event.interfaces import IEvent
-from globalservice import globalSubscribeMany
-
-directive_counter = 0
-def subscribe(_context, subscriber, event_types=[IEvent], filter=None):
- global directive_counter
- directive_counter += 1
-
- _context.action(
- # subscriptions can never conflict
- discriminator = ('subscribe', directive_counter),
- callable = globalSubscribeMany,
- args = (subscriber, event_types, filter)
- )
Deleted: Zope3/trunk/src/zope/app/event/metadirectives.py
===================================================================
--- Zope3/trunk/src/zope/app/event/metadirectives.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/metadirectives.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,41 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""
-$Id$
-"""
-
-from zope.interface import Interface
-from zope.configuration.fields import GlobalObject, Tokens
-
-class ISubscribeDirective(Interface):
- """
- Subscribe to events
- """
-
- subscriber = GlobalObject(
- title=u"Subscriber",
- required=True
- )
-
- event_types = Tokens(
- title=u"Events to subscribe to",
- description=u"Defaults to IEvent",
- required=False,
- value_type = GlobalObject()
- )
-
- filter = GlobalObject(
- title=u"Filter",
- required=False
- )
Modified: Zope3/trunk/src/zope/app/event/objectevent.py
===================================================================
--- Zope3/trunk/src/zope/app/event/objectevent.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/objectevent.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -23,9 +23,8 @@
from zope.app.event.interfaces import IObjectCopiedEvent
from zope.app.event.interfaces import IObjectAnnotationsModifiedEvent
from zope.app.event.interfaces import IObjectContentModifiedEvent
-from zope.app.event.interfaces import ISubscriber
from zope.interface import implements
-from zope.app.event import publish
+from zope.event import notify
from zope.component import subscribers
_marker = object()
@@ -49,7 +48,7 @@
implements(IObjectModifiedEvent)
def modified(object):
- publish(object, ObjectModifiedEvent(object))
+ notify(ObjectModifiedEvent(object))
class ObjectAnnotationsModifiedEvent(ObjectModifiedEvent):
"""An object's annotations have been modified"""
@@ -57,7 +56,7 @@
implements(IObjectAnnotationsModifiedEvent)
def annotationModified(object):
- publish(object, ObjectAnnotationModifiedEvent(object))
+ notify(ObjectAnnotationModifiedEvent(object))
class ObjectContentModifiedEvent(ObjectModifiedEvent):
"""An object's content has been modified"""
@@ -65,7 +64,7 @@
implements(IObjectContentModifiedEvent)
def contentModified(object):
- publish(object, ObjectContentModifiedEvent(object))
+ notify(ObjectContentModifiedEvent(object))
class ObjectCopiedEvent(ObjectCreatedEvent):
"""An object has been copied"""
@@ -73,37 +72,8 @@
implements(IObjectCopiedEvent)
-class ObjectEventNotifier:
+def objectEventNotify(event):
"""Event subscriber to dispatch ObjectEvents to interested adapters."""
- implements(ISubscriber)
-
- def notify(self, event):
- assert IObjectEvent.providedBy(event)
- adapters = subscribers((event.object, event), ISubscriber)
- for adapter in adapters:
- adapter.notify(event)
-
-objectEventNotifierInstance = ObjectEventNotifier()
-
-def objectEventCallbackHelper(callback):
- """Build a factory implementing ISubscriber that just calls a callback
-
- callback will be called with an ObjectEvent instance. Example usage:
-
- factory = objectEventCallbackHelper(events.append)
- getService(None, Adapters).subscribe(
- [MyObjectType, IObjectRemovedEvent], ISubscriber, factory
- )
- """
- class _CallbackHelper:
- implements(ISubscriber)
- def __init__(self, object, event):
- self.object = object
- self.event = event
-
- def notify(self, event):
- callback(event)
-
- return _CallbackHelper
-
-
+ adapters = subscribers((event.object, event), None)
+ for adapter in adapters:
+ pass # getting them does the work
Deleted: Zope3/trunk/src/zope/app/event/subs.py
===================================================================
--- Zope3/trunk/src/zope/app/event/subs.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/subs.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,520 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""
-Revision information:
-
-$Id$
-"""
-from zope.exceptions import NotFoundError
-from persistent import Persistent
-from BTrees.OOBTree import OOBTree
-from BTrees.IOBTree import IOBTree
-
-from zope.proxy import removeAllProxies
-
-from zope.app.traversing.api import getPath
-from zope.app.traversing.api import canonicalPath, traverse
-from zope.app.event.interfaces import IEvent, ISubscriber, ISubscribable
-from zope.app.event.interfaces import ISubscribingAware
-
-from zope.component import getService, queryService
-from zope.app.servicenames import HubIds
-from zope.app.interface.type import PersistentTypeRegistry
-from cPickle import dumps, PicklingError
-from zope.interface import implements
-from zope.app.container.contained import Contained
-
-import logging
-
-__metaclass__ = type
-
-class Subscribable(Persistent, Contained):
- """A local mix-in"""
-
- implements(ISubscribable)
-
- def __init__(self):
- # the type registry
- # key is an event interfaces
- # value is a list of tuples (subscriber_token, filter)
- self._registry = PersistentTypeRegistry()
-
- # hubId : { event_type : number of subscriptions }
- self._hubIds = IOBTree()
- # path : { event_type : number of subscriptions }
- self._paths = OOBTree()
-
- def subscribe(wrapped_self, reference, event_type=IEvent, filter=None):
- '''See ISubscribable'''
- if filter is not None:
- try:
- dumps(filter)
- except PicklingError:
- raise ValueError('The filter argument must be picklable',
- filter)
-
- if not event_type.extends(IEvent, strict=False):
- raise TypeError('event_type must be IEvent or extend IEvent',
- event_type)
- reftype, token, wrapped_object, clean_object = getWayToSubscribe(
- wrapped_self, reference)
-
- # If wrapped_object is None, the object can't be traversed to,
- # so raise an exception
- if wrapped_object is None:
- raise NotFoundError(reference)
-
- clean_self = removeAllProxies(wrapped_self)
-
- if clean_object is clean_self:
- raise RuntimeError("Cannot subscribe to self")
-
- # Check that ISubscriber adapter exists for the wrapped object.
- # This will raise an error if there is no such adapter.
- ISubscriber(wrapped_object)
-
- # Optimisation
- if event_type is IEvent:
- ev_type = None
- else:
- ev_type = event_type
-
- subscribers = clean_self._registry.get(ev_type)
- if subscribers is None:
- subscribers = []
- subscribers.append((token, filter))
- # Ensure that type registry is triggered for persistence
- clean_self._registry.register(ev_type, subscribers)
-
- # increment the subscription count for this subscriber
- if reftype is int:
- tokens = clean_self._hubIds
- elif reftype is unicode:
- tokens = clean_self._paths
- else:
- raise AssertionError('reftype must be int or unicode')
-
- # evtype_numsubs is a dict {ev_type : number of subscriptions}
- evtype_numsubs = tokens.get(token, {})
- evtype_numsubs.setdefault(ev_type, 0)
- evtype_numsubs[ev_type] += 1
- tokens[token] = evtype_numsubs
-
- subscribingaware = ISubscribingAware(wrapped_object, None)
- if subscribingaware is not None:
- subscribingaware.subscribedTo(wrapped_self, event_type, filter)
-
- return token
-
- def unsubscribe(wrapped_self, reference, event_type, filter=None):
- 'See ISubscribable. Remove just one subscription.'
- # Remove just one subscription.
- # If reference is an int, try removing by hubId, and if that fails
- # try by path.
- # If reference is a string, try removing by path, and if that fails
- # try by hubId.
- # If reference is an object, try removing by hubId and if that fails,
- # try by path.
-
- # check that filter is picklable
- if filter is not None:
- try:
- dumps(filter)
- except PicklingError:
- raise ValueError('The filter argument must be picklable',
- filter)
- # check that event_type is an IEvent
- if not event_type.extends(IEvent, strict=False):
- raise TypeError('event_type must extend IEvent', event_type)
-
- # Optimisation
- if event_type is IEvent:
- ev_type = None
- else:
- ev_type = event_type
-
- clean_self = removeAllProxies(wrapped_self)
- cleanobj, wrappedobj, path, hubId, reftype = getWaysToSubscribe(
- wrapped_self, reference)
-
- if path is None and hubId is None:
- raise ValueError('Can get neither path nor hubId for reference',
- reference)
-
- if cleanobj is None:
- logging.getLogger('SiteError').warn(
- "Unsubscribing an object that doesn't exist: %s" % reference)
-
- registry = clean_self._registry
-
- if reftype is unicode:
- where_to_search = ((path, clean_self._paths),
- (hubId, clean_self._hubIds))
- else:
- where_to_search = ((hubId, clean_self._hubIds),
- (path, clean_self._paths))
-
- for token, tokens in where_to_search:
-
- if token is not None:
- evtype_numsubs = tokens.get(token)
- if evtype_numsubs is not None:
- numsubs = evtype_numsubs.get(ev_type)
- if numsubs:
-
- # Go through the registrations in self._registry for
- # exactly ev_type, looking for the first occurence
- # of (path, filter)
- subscriptions = registry.get(ev_type)
- try:
- subscriptions.remove((token, filter))
- except ValueError:
- # The subscription (token, filter) was not present
- pass
- else:
- if subscriptions:
- registry.register(ev_type, subscriptions)
- else:
- registry.unregister(ev_type)
-
- if numsubs == 1:
- del evtype_numsubs[ev_type]
- else:
- evtype_numsubs[ev_type] = numsubs - 1
- if evtype_numsubs:
- tokens[token] = evtype_numsubs
- else:
- del tokens[token]
-
- break
- else:
- # No subscription was removed.
- raise NotFoundError(reference)
-
- subscribingaware = ISubscribingAware(wrappedobj, None)
- if subscribingaware is not None:
- subscribingaware.unsubscribedFrom(wrapped_self, event_type, filter)
-
- def unsubscribeAll(wrapped_self, reference, event_type=IEvent):
- 'See ISubscribable. Remove all matching subscriptions.'
- # check that event_type is an IEvent
- if not IEvent.isEqualOrExtendedBy(event_type):
- raise TypeError('event_type must extend IEvent')
-
- clean_self = removeAllProxies(wrapped_self)
- cleanobj, wrappedobj, path, hubId, reftype = getWaysToSubscribe(
- wrapped_self, reference)
-
- if path is None and hubId is None:
- raise ValueError('Can get neither path nor hubId for reference',
- reference)
-
- if cleanobj is None:
- logging.getLogger('SiteError').warn(
- "Unsubscribing all for an object that doesn't exist: %s" %
- reference)
-
- subscribingaware = ISubscribingAware(wrappedobj, None)
-
- registry = clean_self._registry
- if event_type is IEvent:
- ev_type = None
- else:
- ev_type = IEvent
- eventtypes = registry.getTypesMatching(ev_type)
-
- eventtypes_used = {} # used as a set, so values are all None
- num_registrations_removed = 0
- num_subscriptions_removed = 0
- for token, tokens in ((path, clean_self._paths),
- (hubId, clean_self._hubIds)):
-
- if token is not None:
- evtype_numsubs = tokens.get(token)
- if evtype_numsubs is not None:
- for et in eventtypes:
- numsubs = evtype_numsubs.get(et)
- if numsubs is not None:
- num_subscriptions_removed += numsubs
- del evtype_numsubs[et]
- eventtypes_used[et] = None # add key to the set
- if not evtype_numsubs:
- del tokens[token]
-
- for et in eventtypes_used:
- subscriptions = []
- for token, filter in registry.get(et):
- if token == path or token == hubId:
- num_registrations_removed += 1
- if subscribingaware is not None:
- subscribingaware.unsubscribedFrom(
- wrapped_self, et or IEvent, filter)
- else:
- subscriptions.append((token, filter))
- if subscriptions:
- registry.register(et, subscriptions)
- else:
- registry.unregister(et)
-
- assert num_registrations_removed == num_subscriptions_removed
- return num_registrations_removed
-
- def resubscribeByHubId(wrapped_self, reference):
- 'Where a subscriber has a hubId, resubscribe it by that hubid'
- clean_self = removeAllProxies(wrapped_self)
- cleanobj, wrappedobj, path, hubId, reftype = getWaysToSubscribe(
- wrapped_self, reference)
-
- if hubId is None:
- raise ValueError('Cannot get hubId for reference', reference)
-
- if path is None:
- raise ValueError('Cannot get path for reference', reference)
-
- if cleanobj is None:
- # Perhaps this should raise an exception?
- logging.getLogger('SiteError').warn(
- "resubscribeByHubId for an object that doesn't exist: %s" %
- reference)
-
- self._resubscribe(path, clean_self._paths, hubId, clean_self._hubIds)
-
- def resubscribeByPath(wrapped_self, reference):
- clean_self = removeAllProxies(wrapped_self)
- cleanobj, wrappedobj, path, hubId, reftype = getWaysToSubscribe(
- wrapped_self, reference)
-
- if path is None:
- raise ValueError('Cannot get path for reference', reference)
-
- if hubId is None:
- raise ValueError('Cannot get hubId for reference', reference)
-
- if cleanobj is None:
- # Perhaps this should raise an exception?
- logging.getLogger('SiteError').warn(
- "resubscribeByPath for an object that doesn't exist: %s" %
- reference)
-
- self._resubscribe(hubId, clean_self._hubIds, path, clean_self._paths)
-
- def iterSubscriptions(wrapped_self, reference=None, event_type=IEvent):
- '''See ISubscribable'''
- if reference is None:
- return wrapped_self._iterAllSubscriptions(wrapped_self, event_type)
- else:
- return wrapped_self._iterSomeSubscriptions(wrapped_self,
- reference,
- event_type)
-
- def _iterAllSubscriptions(self, wrapped_self, event_type):
- clean_self = removeAllProxies(wrapped_self)
- if event_type is IEvent:
- ev_type = None
- else:
- ev_type = event_type
- registry = clean_self._registry
- eventtypes = registry.getTypesMatching(ev_type)
- for et in eventtypes:
- subscribers = registry.get(et)
- if et is None:
- et = IEvent
- for token, filter in subscribers:
- yield token, et, filter
-
- def _iterSomeSubscriptions(self, wrapped_self, reference, event_type):
- clean_self = removeAllProxies(wrapped_self)
-
- cleanobj, wrappedobj, path, hubId, reftype = getWaysToSubscribe(
- wrapped_self, reference)
-
- if path is None and hubId is None:
- raise ValueError('Can get neither path nor hubId for reference',
- reference)
-
- if cleanobj is None:
- logging.getLogger('SiteError').warn(
- "iterSubscriptions for an object that doesn't exist: %s" %
- reference)
- if event_type is IEvent:
- ev_type = None
- else:
- ev_type = event_type
- registry = clean_self._registry
- eventtypes = registry.getTypesMatching(ev_type)
- eventtypes_used = {} # used as a set, so values are all None
-
- for token, tokens in ((path, clean_self._paths),
- (hubId, clean_self._hubIds)):
-
- if token is not None:
- evtype_numsubs = tokens.get(token)
- if evtype_numsubs is not None:
- for et in eventtypes:
- numsubs = evtype_numsubs.get(et)
- if numsubs is not None:
- eventtypes_used[et] = None # add key to the set
-
- for et in eventtypes_used:
- if et is None:
- et = IEvent
- for token, filter in registry.get(et):
- if token == path or token == hubId:
- yield token, et, filter
-
- def _resubscribe(self, fromtoken, fromsubs, totoken, tosubs):
- path_evtype_numsubs = fromsubs.get(fromtoken)
- if not path_evtype_numsubs:
- # nothing to do
- return 0
- del fromsubs[fromtoken]
- hubId_evtype_numsubs = tosubs.get(totoken, {})
- num_registrations_converted = 0
- num_subscriptions_converted = 0
- registry = self._registry
- for ev_type, num_subscriptions in path_evtype_numsubs.iteritems():
- num_subscriptions_converted += num_subscriptions
- hubId_evtype_numsubs[ev_type] = (
- hubId_evtype_numsubs.get(ev_type, 0) + num_subscriptions)
-
- subscriptions = registry.get(ev_type)
- if subscriptions:
- new_subscriptions = []
- for token, filter in registry.get(ev_type):
- if token == fromtoken:
- new_subscriptions.append((totoken, filter))
- num_registrations_converted += 1
- else:
- new_subscriptions.append((token, filter))
- registry[ev_type] = new_subscriptions
-
- # I'm not using this one-liner because I want to count the number
- # of registrations converted for sanity-checking.
- #
- # registry[ev_type] = [
- # (token==fromtoken and totoken or token, filter)
- # for token, filter in registry.get(ev_type)
- # ]
-
- if hubId_evtype_numsubs:
- tosubs[totoken] = hubId_evtype_numsubs
-
- assert num_registrations_converted == num_subscriptions_converted
- return num_subscriptions_converted
-
-num = 0
-class SubscriptionTracker:
- "Mix-in for subscribers that want to know to whom they are subscribed"
-
- implements(ISubscribingAware)
-
- def __init__(self):
- self._subscriptions = ()
- global num
- self.number = num
- num += 1
-
- def subscribedTo(self, subscribable, event_type, filter):
- # XXX insert super() call here
- # This raises an error for subscriptions to global event service.
- subscribable_path = getPath(subscribable)
- self._subscriptions += ((subscribable_path, event_type, filter),)
-
- def unsubscribedFrom(self, subscribable, event_type, filter):
- # XXX insert super() call here
- # This raises an error for subscriptions to global event service.
- subscribable_path = getPath(subscribable)
- sub = list(self._subscriptions)
- sub.remove((subscribable_path, event_type, filter))
- self._subscriptions = tuple(sub)
-
-def getWayToSubscribe(context, reference):
- '''Figure out the most appropriate means of subscribing the subscriber.
-
- Returns a tuple:
- (subscription_token, token-type, wrapped_subscriber_object)
- '''
- clean, wrapped, path, hubId, reftype = getWaysToSubscribe(
- context, reference, allways=False)
- if reftype is unicode or hubId is None:
- return unicode, path, wrapped, clean
- if path is None and hubId is None:
- raise Exception('Can get neither path nor hubId for reference',
- reference)
- return int, hubId, wrapped, clean
-
-def getWaysToSubscribe(context, reference, allways=True):
- '''Get the various means of subscription available for the given
- reference.
-
- Returns a tuple of:
- clean_object, wrapped_object, unicode path, hubId, reftype
-
- reftype is object, int or unicode.
- '''
- cleanobj = None
- wrappedobj = None
- hubId = None
- path = None
-
- clean_reference = removeAllProxies(reference)
-
- if isinstance(clean_reference, int):
- reftype = int
- hubId = clean_reference
- hub = getService(context, HubIds)
- try:
- wrappedobj = hub.getObject(hubId)
- except NotFoundError:
- wrappedobj = None
- else:
- if allways:
- try:
- # Hub can't resolve the object, but it might still know
- # the location the object is supposed to be at.
- path = hub.getLocation(hubId)
- # XXX remove this next line when objecthub is refactored
- path = canonicalPath(path)
- except NotFoundError:
- path = getPath(wrappedobj)
- cleanobj = removeAllProxies(wrappedobj)
- elif isinstance(clean_reference, basestring):
- reftype = unicode
- path = canonicalPath(clean_reference)
- try:
- wrappedobj = traverse(context, path)
- except NotFoundError:
- wrappedobj = None
- else:
- cleanobj = removeAllProxies(wrappedobj)
- if allways:
- hub = queryService(context, HubIds)
- if hub is not None:
- try:
- hubId = hub.getHubId(path)
- except NotFoundError:
- pass
- else:
- reftype = object
- wrappedobj = reference
- cleanobj = clean_reference
- path = getPath(wrappedobj)
- hub = queryService(context, HubIds)
- if hub is not None:
- try:
- hubId = hub.getHubId(path)
- except NotFoundError:
- pass
-
- return cleanobj, wrappedobj, path, hubId, reftype
Deleted: Zope3/trunk/src/zope/app/event/tests/eventsetup.py
===================================================================
--- Zope3/trunk/src/zope/app/event/tests/eventsetup.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/tests/eventsetup.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,25 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""Event Setup
-
-$Id$
-"""
-from zope.app.site.tests.placefulsetup import PlacefulSetup
-
-class EventSetup(PlacefulSetup):
-
- def setUp(self):
- super(EventSetup, self).setUp(site=True)
- self.createStandardServices()
-
Modified: Zope3/trunk/src/zope/app/event/tests/placelesssetup.py
===================================================================
--- Zope3/trunk/src/zope/app/event/tests/placelesssetup.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/tests/placelesssetup.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -15,22 +15,15 @@
$Id$
"""
-from zope.app.servicenames import EventPublication
-from zope.app.event.interfaces import IPublisher, ISubscriber, IObjectEvent
-from zope.app.event.globalservice import eventPublisher
-from zope.app.event.objectevent import objectEventNotifierInstance
+
+from zope.app.event.interfaces import IObjectEvent
+from zope.app.event.objectevent import objectEventNotify
from zope.interface import implements
from zope.component import getGlobalServices
+from zope.app.tests import ztapi
events = []
-class EventRecorderClass:
- implements(ISubscriber)
-
- notify = events.append
-
-EventRecorder = EventRecorderClass()
-
def getEvents(event_type=None, filter=None):
r = []
for event in events:
@@ -48,17 +41,9 @@
class PlacelessSetup:
def setUp(self):
- sm = getGlobalServices()
- defineService = sm.defineService
- provideService = sm.provideService
-
- defineService(EventPublication, IPublisher)
- provideService(EventPublication, eventPublisher)
-
clearEvents()
- eventPublisher.globalSubscribe(EventRecorder)
- eventPublisher.globalSubscribe(objectEventNotifierInstance,
- IObjectEvent)
+ ztapi.handle([None], events.append)
+ ztapi.handle([IObjectEvent], objectEventNotify)
import zope.testing.cleanup
zope.testing.cleanup.addCleanUp(clearEvents)
Deleted: Zope3/trunk/src/zope/app/event/tests/subscriber.py
===================================================================
--- Zope3/trunk/src/zope/app/event/tests/subscriber.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/tests/subscriber.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,44 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""
-This contains some dummy stuff to do with subscribing to event channels
-that's useful in several test modules.
-
-$Id$
-"""
-from zope.app.event.interfaces import IFilter, ISubscriber
-from zope.interface import implements
-
-class DummySubscriber:
-
- implements(ISubscriber)
-
- def __init__(self):
- self.notified = 0
-
- def notify(self, event):
- self.notified += 1
-
-subscriber = DummySubscriber()
-
-class DummyFilter:
- implements(IFilter)
-
- def __init__(self,value=1):
- self.value = value
-
- def __call__(self, event):
- return self.value
-
-filter = DummyFilter
Deleted: Zope3/trunk/src/zope/app/event/tests/test_directives.py
===================================================================
--- Zope3/trunk/src/zope/app/event/tests/test_directives.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/tests/test_directives.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,80 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""
-$Id$
-"""
-from unittest import TestCase, main, makeSuite
-
-from zope.configuration.xmlconfig import xmlconfig, XMLConfig
-import zope.app.event
-from StringIO import StringIO
-
-from zope.exceptions import NotFoundError
-from zope.app.event import globalUnsubscribe, publish
-from zope.app.container.contained import ObjectAddedEvent
-from zope.app.container.contained import ObjectRemovedEvent
-from zope.app.event.objectevent import ObjectModifiedEvent
-from zope.app.event.tests.test_eventpublisher import DummyEvent
-from zope.component.tests.placelesssetup import PlacelessSetup
-from zope.component import getGlobalServices
-from zope.app.servicenames import EventPublication
-from zope.app.event.interfaces import IEvent
-
-class Test(PlacelessSetup, TestCase):
-
- def setUp(self):
- super(Test, self).setUp()
- from zope.app.event.interfaces import IPublisher
- getGlobalServices().defineService(EventPublication, IPublisher)
- from zope.app.event.globalservice import eventPublisher
- getGlobalServices().provideService(EventPublication, eventPublisher)
-
- def testSubscribe(self):
- from zope.app.event.tests.subscriber import subscriber
- # This should do nothing silently, as the event_type is default
- globalUnsubscribe(subscriber)
- # This should fail, since we're not subscribed
- self.assertRaises(NotFoundError, globalUnsubscribe, subscriber, IEvent)
- XMLConfig('meta.zcml', zope.app.event)()
- xmlconfig(StringIO(
- '''<configure xmlns='http://namespaces.zope.org/zope'
- xmlns:test='http://namespaces.zope.org/event'>
- <test:subscribe
- subscriber="zope.app.event.tests.subscriber.subscriber"
- event_types=
- "zope.app.container.interfaces.IObjectAddedEvent
- zope.app.container.interfaces.IObjectRemovedEvent"
- filter="zope.app.event.tests.subscriber.filter" />
- </configure>'''
- ))
-
- parent= object()
- publish(None, ObjectAddedEvent(None, parent, 'foo'))
- self.assertEqual(subscriber.notified, 1)
- publish(None, ObjectRemovedEvent(object(), parent, 'foo'))
- self.assertEqual(subscriber.notified, 2)
- publish(None, ObjectModifiedEvent(None))
- self.assertEqual(subscriber.notified, 2) # NB: no increase ;-)
- publish(None, DummyEvent())
- self.assertEqual(subscriber.notified, 4) # NB: increased by 2 ;-)
-
- globalUnsubscribe(subscriber)
-
- subscriber.notified = 0
-
-def test_suite():
- return makeSuite(Test)
-
-if __name__ == '__main__':
- main(defaultTest='test_suite')
Copied: Zope3/trunk/src/zope/app/event/tests/test_dispatching.py (from rev 25030, Zope3/branches/jim-simplifyevents/src/zope/app/event/tests/test_dispatching.py)
Property changes on: Zope3/trunk/src/zope/app/event/tests/test_dispatching.py
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Deleted: Zope3/trunk/src/zope/app/event/tests/test_eventpublisher.py
===================================================================
--- Zope3/trunk/src/zope/app/event/tests/test_eventpublisher.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/tests/test_eventpublisher.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,283 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""
-$Id$
-"""
-import unittest
-
-from zope.app.event.interfaces import IObjectEvent
-from zope.app.container.interfaces import IObjectAddedEvent
-from zope.app.container.interfaces import IObjectRemovedEvent
-from zope.app.event.interfaces import IObjectModifiedEvent
-from zope.app.event.objectevent import ObjectModifiedEvent
-from zope.app.container.contained import ObjectAddedEvent
-from zope.app.event.globalservice import GlobalEventPublisher
-from zope.exceptions import NotFoundError
-from zope.app.event.interfaces import IEvent
-from zope.component.tests.placelesssetup import PlacelessSetup
-
-from zope.app.event.tests.subscriber import DummySubscriber, DummyFilter
-from zope.interface import implements
-
-class DummyEvent:
-
- implements(IObjectAddedEvent, IObjectRemovedEvent)
- object = None
-
-class ObjectEvent:
-
- implements(IObjectEvent)
- object = None
-
-class TestEventService(PlacelessSetup, unittest.TestCase):
-
- def setUp(self):
- super(TestEventService, self).setUp()
- self.service = GlobalEventPublisher()
- parent = object()
- self.event = ObjectAddedEvent(None, parent, 'foo')
- self.subscriber = DummySubscriber()
-
- def testSubscribe1(self):
- # Test subscribe method with one parameter
- self.service.globalSubscribe(self.subscriber)
- self.service.publish(self.event)
- self.assertEqual(self.subscriber.notified, 1)
-
- def testSubscribe2(self):
- # Test subscribe method with two parameters
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectAddedEvent
- )
- self.service.publish(self.event)
- self.assertEqual(self.subscriber.notified, 1)
-
- def testSubscribe3(self):
- # Test subscribe method with three parameters
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectAddedEvent,
- filter=DummyFilter()
- )
- self.service.publish(self.event)
- self.assertEqual(self.subscriber.notified, 1)
-
- def testSubscribe4(self):
- # Test subscribe method with three parameters and an always failing
- # filter.
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectAddedEvent,
- filter=DummyFilter(0)
- )
- self.service.publish(self.event)
- self.assertEqual(self.subscriber.notified, 0)
-
- def testSubscribe5(self):
- # Test subscribe method with three parameters and an irrelevent event
- # type.
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectModifiedEvent,
- filter=DummyFilter()
- )
- self.service.publish(self.event)
- self.assertEqual(self.subscriber.notified, 0)
-
- def testSubscribe6(self):
- # Test subscribe method where the event type registered is a
- # generalised interface of the event passed to the 'publish' method.
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectEvent
- )
- self.service.publish(self.event)
- self.assertEqual(self.subscriber.notified, 1)
-
- def testSubscribe7(self):
- # Test subscribe method where one of the event types registered is not
- # interested in the published event.
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectModifiedEvent
- )
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectAddedEvent
- )
- self.service.publish(self.event)
- self.assertEqual(self.subscriber.notified, 1)
-
- def testSubscribe8(self):
- # Test subscribe method where the same subscriber subscribes multiple
- # times.
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectAddedEvent,
- filter=DummyFilter()
- )
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectAddedEvent,
- filter=DummyFilter()
- )
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectAddedEvent,
- filter=DummyFilter(0)
- )
- self.service.publish(self.event)
- self.assertEqual(self.subscriber.notified, 2)
-
- def testUnsubscribe1(self):
- # Test unsubscribe method
- subscriber = self.subscriber
- self.service.globalSubscribe(subscriber)
- self.service.publish(self.event)
- self.assertEqual(self.subscriber.notified, 1)
- self.service.unsubscribe(subscriber)
- self.service.publish(self.event)
- self.assertEqual(self.subscriber.notified, 1)
-
- def testUnsubscribe2(self):
- # Test unsubscribe of something that hasn't been subscribed
- subscriber = self.subscriber
- self.assertRaises(NotFoundError,
- self.service.unsubscribe,
- subscriber, IObjectEvent)
- self.assertEqual(None,
- self.service.unsubscribe(subscriber))
-
- def testUnsubscribe3(self):
- # Test selective unsubscribe
- subscriber2=DummySubscriber()
- filter=DummyFilter()
- event2=ObjectModifiedEvent(None)
- self.service.globalSubscribe(
- self.subscriber)
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectAddedEvent,
- filter=filter
- )
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectAddedEvent
- )
- self.service.globalSubscribe(
- subscriber2,
- event_type=IObjectAddedEvent
- )
- self.service.publish(self.event)
- self.assertEqual(self.subscriber.notified, 3)
- self.assertEqual(subscriber2.notified, 1)
- self.service.publish(event2)
- self.assertEqual(self.subscriber.notified, 4)
- self.assertEqual(subscriber2.notified, 1)
- self.service.unsubscribe(self.subscriber, IObjectAddedEvent)
- self.service.publish(self.event)
- self.assertEqual(self.subscriber.notified, 6)
- self.assertEqual(subscriber2.notified, 2)
- self.service.unsubscribe(self.subscriber, IEvent)
- self.service.publish(event2)
- self.assertEqual(self.subscriber.notified, 6)
- self.assertEqual(subscriber2.notified, 2)
- self.assertRaises(NotFoundError, self.service.unsubscribe,
- self.subscriber, IObjectAddedEvent)
- self.service.unsubscribe(self.subscriber, IObjectAddedEvent, filter)
- self.service.publish(self.event)
- self.assertEqual(self.subscriber.notified, 6)
- self.assertEqual(subscriber2.notified, 3)
- self.service.unsubscribe(subscriber2, IObjectAddedEvent)
- self.service.publish(self.event)
- self.assertEqual(self.subscriber.notified, 6)
- self.assertEqual(subscriber2.notified, 3)
-
- def testpublish1(self):
- # Test publish method
- subscriber = self.subscriber
- self.service.globalSubscribe(subscriber)
- self.assertEqual(self.subscriber.notified, 0)
- self.service.publish(self.event)
- self.assertEqual(self.subscriber.notified, 1)
-
- def testpublish2(self):
- # Test publish method where subscriber has been subscribed twice, with
- # a more generalised version of the initially subscribed interface in
- # the second subscription.
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectEvent,
- )
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectAddedEvent,
- )
- self.service.publish(self.event)
- self.assertEqual(self.subscriber.notified, 2)
-
- def testpublish3(self):
- # Test publish method where subscriber has been to two interfaces and
- # a single event implements both of those interfaces.
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectRemovedEvent
- )
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectAddedEvent
- )
- self.service.publish(DummyEvent())
- self.assertEqual(self.subscriber.notified, 2)
-
- def testpublish4(self):
- # Test publish method to make sure that we don't 'leak registrations
- # up' sez Jim.
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectEvent
- )
- self.service.globalSubscribe(
- self.subscriber,
- event_type=IObjectAddedEvent
- )
- self.service.publish(ObjectEvent())
- self.assertEqual(self.subscriber.notified, 1)
-
- def testListSubscriptions1(self):
- # a non-subscribed subscriber gets an empty array
- self.assertEqual([], self.service.listSubscriptions(self.subscriber))
-
- def testListSubscriptions2(self):
- # one subscription
- self.service.globalSubscribe(
- self.subscriber, event_type=IObjectAddedEvent)
- self.assertEqual([(IObjectAddedEvent, None)],
- self.service.listSubscriptions(self.subscriber))
-
- def testListSubscriptions3(self):
- # listing limited subscription
- self.service.globalSubscribe(
- self.subscriber, event_type=IObjectAddedEvent)
- L = self.service.listSubscriptions(self.subscriber,
- IObjectRemovedEvent)
- self.assertEqual([], L)
-
-
-def test_suite():
- return unittest.makeSuite(TestEventService)
-
-if __name__ == '__main__':
- unittest.main(defaultTest='test_suite')
Deleted: Zope3/trunk/src/zope/app/event/tests/test_globaleventchannel.py
===================================================================
--- Zope3/trunk/src/zope/app/event/tests/test_globaleventchannel.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/tests/test_globaleventchannel.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,207 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""A functional GlobalEventChannel test.
-
-$Id$
-"""
-from unittest import TestCase, TestSuite, main, makeSuite
-
-from zope.interface import Interface, implements
-from zope.component.tests.placelesssetup import PlacelessSetup
-from zope.component.tests.components import RecordingAdapter
-from zope.app.event.interfaces import IEvent, ISubscribingAware, ISubscriber
-from zope.app.tests import ztapi
-
-class ISomeEvent(IEvent):
- pass
-
-class ISomeSubEvent(ISomeEvent):
- pass
-
-class ISomeOtherEvent(IEvent):
- pass
-
-class ISubscriberStub(ISubscriber):
- pass
-
-class INonSubscriberStub(Interface):
- pass
-
-class SomeEvent:
- implements(ISomeEvent)
-
-class SomeSubEvent:
- implements(ISomeSubEvent)
-
-class SomeOtherEvent:
- implements(ISomeOtherEvent)
-
-class SubscriberStub:
- implements(ISubscriberStub)
- received = None
- def notify(self, event):
- self.received = event
-
-class NonSubscriberStub:
- implements(INonSubscriberStub)
-
-
-class Test(PlacelessSetup, TestCase):
-
- def test_notify(self):
- from zope.app.event.globalservice import GlobalEventChannel
-
- subscriber = SubscriberStub()
- ec = GlobalEventChannel()
- ec.globalSubscribe(subscriber, ISomeEvent)
-
- ev = SomeEvent()
- ec.notify(ev)
- self.assertEquals(subscriber.received, ev,
- "Did not get event registered for")
-
- ev = SomeSubEvent()
- ec.notify(ev)
- self.assertEquals(
- subscriber.received, ev, "Did not get subclassed event")
-
- ev = SomeOtherEvent()
- ec.notify(ev)
- self.assertNotEquals(subscriber.received, ev, "Got unrelated event")
-
- def test_notify_filter(self):
- from zope.app.event.globalservice import GlobalEventChannel
-
- true = lambda x: True
- false = lambda x: False
-
- subscriber = SubscriberStub()
- ec = GlobalEventChannel()
- ec.globalSubscribe(subscriber, ISomeEvent, true)
-
- ev = SomeEvent()
- ec.notify(ev)
- self.assertEquals(subscriber.received, ev,
- "Did not get event registered for")
-
- subscriber = SubscriberStub()
- ec = GlobalEventChannel()
- ec.globalSubscribe(subscriber, ISomeEvent, false)
-
- ev = SomeEvent()
- ec.notify(ev)
- self.assertEquals(subscriber.received, None,
- "Event was not filtered")
-
-class SubAware(RecordingAdapter):
- implements(ISubscribingAware)
-
- def subscribedTo(self, subscribable, event_type, filter):
- self.record.append(('subscribed', self.context, subscribable,
- event_type, filter))
-
- def unsubscribedFrom(self, subscribable, event_type, filter):
- self.record.append(('unsubscribed', self.context, subscribable,
- event_type, filter))
-
-
-class TestSubscribingAwareChannel(PlacelessSetup, TestCase):
-
- def setUpChannel(self):
- from zope.app.event.globalservice import GlobalEventChannel
- self.ec = GlobalEventChannel()
-
- def setUp(self):
- super(TestSubscribingAwareChannel, self).setUp()
- self.setUpChannel()
- self.subscriber = SubscriberStub()
- self.filter = lambda x: True
- self.subaware = SubAware()
- ztapi.provideAdapter(ISubscriberStub, ISubscribingAware, self.subaware)
-
- def test_subscribe(self):
- self.ec.globalSubscribe(self.subscriber, ISomeEvent, self.filter)
- self.subaware.check(
- ('subscribed', self.subscriber, self.ec, ISomeEvent, self.filter)
- )
-
- def test_unsubscribe(self):
- self.test_subscribe()
- self.ec.unsubscribe(self.subscriber, ISomeEvent, self.filter)
- self.subaware.check(
- ('subscribed', self.subscriber, self.ec, ISomeEvent, self.filter),
- ('unsubscribed', self.subscriber, self.ec, ISomeEvent, self.filter),
- )
-
-class TestSubscribingAwareGlobalPublisher(TestSubscribingAwareChannel):
-
- def setUpChannel(self):
- from zope.app.event.globalservice import GlobalEventPublisher
- self.ec = GlobalEventPublisher()
-
-class SubscriberAdapter(RecordingAdapter):
- implements(ISubscriber)
-
- def notify(self, event):
- self.record.append(('notified', self.context, event))
-
-class TestAdaptingToISubscriberBase(PlacelessSetup, TestCase):
-
- def setUpChannel(self):
- raise NotImplementedError('You need to write a setUpChannel method.')
-
- def setUp(self):
- super(TestAdaptingToISubscriberBase, self).setUp()
- self.setUpChannel()
- self.subscriber = NonSubscriberStub()
- self.event = SomeEvent()
- self.adapter = SubscriberAdapter()
- ztapi.provideAdapter(INonSubscriberStub, ISubscriber, self.adapter)
-
-class TestAdaptingToISubscriberOnNotify(TestAdaptingToISubscriberBase):
- def setUpChannel(self):
- from zope.app.event.globalservice import GlobalEventChannel
- self.ec = GlobalEventChannel()
-
- def test_notify(self):
- self.ec.globalSubscribe(self.subscriber, ISomeEvent)
- self.ec.notify(self.event)
- self.adapter.check(
- ('notified', self.subscriber, self.event)
- )
-
-class TestAdaptingToISubscriberOnPublish(TestAdaptingToISubscriberBase):
- def setUpChannel(self):
- from zope.app.event.globalservice import GlobalEventPublisher
- self.ec = GlobalEventPublisher()
-
- def test_notify(self):
- self.ec.globalSubscribe(self.subscriber, ISomeEvent)
- self.ec.publish(self.event)
- self.adapter.check(
- ('notified', self.subscriber, self.event)
- )
-
-
-def test_suite():
- return TestSuite((
- makeSuite(Test),
- makeSuite(TestSubscribingAwareChannel),
- makeSuite(TestSubscribingAwareGlobalPublisher),
- makeSuite(TestAdaptingToISubscriberOnNotify),
- makeSuite(TestAdaptingToISubscriberOnPublish),
- ))
-
-if __name__=='__main__':
- main(defaultTest='test_suite')
Deleted: Zope3/trunk/src/zope/app/event/tests/test_localservice.py
===================================================================
--- Zope3/trunk/src/zope/app/event/tests/test_localservice.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/tests/test_localservice.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,979 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""
-$Id$
-"""
-from unittest import TestCase, TestLoader, TextTestRunner
-
-import zope.interface
-from zope.interface import Interface, implements
-from zope.exceptions import NotFoundError
-from zope.component.tests.components import RecordingAdapter
-
-from zope.app.servicenames import EventPublication, EventSubscription
-from zope.app.event.localservice import EventService
-from zope.app.event.localservice import subscribe, unsubscribe, unsubscribeAll
-from zope.app.event.localservice import getSubscriptionService
-
-from zope.app.event import publish
-from zope.app.event.tests.subscriber import DummySubscriber, DummyFilter
-from zope.app.event.interfaces import IObjectEvent, IObjectModifiedEvent
-from zope.app.event.objectevent import ObjectModifiedEvent
-from zope.app.event.interfaces import IEvent, ISubscriber, ISubscribingAware
-
-from zope.app.traversing.api import getPath, traverse
-from zope.app.traversing.interfaces import IContainmentRoot
-from zope.app.container.interfaces import IObjectAddedEvent, IObjectRemovedEvent
-from zope.app.container.contained import ObjectAddedEvent, Contained
-from zope.app.registration.interfaces import RegisteredStatus
-from zope.app.site.interfaces import ISimpleService
-from zope.app.tests import ztapi, setup
-from eventsetup import EventSetup
-
-class Folder(Contained):
- pass
-
-root = Folder()
-zope.interface.directlyProvides(root, IContainmentRoot)
-foo = Folder()
-foo.__parent__ = root
-foo.__name__ = 'foo'
-
-
-class UnpromotingEventService(EventService):
-
- def isPromotableEvent(self, event):
- "see EventService implementation"
- return False
-
-class DummyEvent:
-
- implements(IObjectAddedEvent, IObjectRemovedEvent)
- object = None
-
-class ObjectEvent:
-
- implements(IObjectEvent)
- object = None
-
-class IObjectHub(Interface):
- def getObject(hubid):
- "gets object"
-
- def getHubId(object):
- "gets hubid"
-
- def getLocation(hubId):
- "gets location"
-
-class DumbObjectHub:
- implements(IObjectHub, ISimpleService)
-
- __name__ = __parent__ = None
-
- def __init__(self):
- # (location, object)
- self.lib = []
-
- def getObject(self, hubid):
- try:
- return self.lib[hubid][1]
- except IndexError:
- raise NotFoundError
-
- def getHubId(self, object_or_path):
- for i in range(len(self.lib)):
- if self.lib[i][0] == object_or_path:
- return i
- if self.lib[i][1] is object_or_path:
- return i
- raise NotFoundError, object_or_path
-
- def getLocation(self, hubId):
- return self.lib[hubId][0]
-
-class IHasSubscribingAwareAdapter(Interface):
- pass
-
-class HasSubscribingAwareAdapter(DummySubscriber):
- implements(IHasSubscribingAwareAdapter, ISubscriber)
-
-
-class SubscribingAwareAdapter(RecordingAdapter):
-
- implements(ISubscribingAware)
-
- def subscribedTo(self, subscribable, event_type, filter):
- self.record.append(('subscribed', self.context, subscribable,
- event_type, filter))
-
- def unsubscribedFrom(self, subscribable, event_type, filter):
- self.record.append(('unsubscribed', self.context, subscribable,
- event_type, filter))
-
-
-class TestEventPublisher(EventSetup, TestCase):
-
- def setUp(self):
- EventSetup.setUp(self)
-
- def getObjectHub(self):
- self.objectHub = DumbObjectHub()
- return self.objectHub
-
- def _createNestedServices(self):
- for path in ('folder1', 'folder1/folder1_1',
- 'folder1/folder1_1/folder1_1_1'):
- sm = self.makeSite(path)
- events = EventService()
- setup.addService(sm, EventPublication, events)
- setup.addService(sm, EventSubscription, events, suffix='s')
-
- def _createSubscribers(self):
- self.rootFolder["rootFolderSubscriber"] = DummySubscriber()
- self.rootFolderSubscriber = self.rootFolder["rootFolderSubscriber"]
- self.folder1["folder1Subscriber"] = DummySubscriber()
- self.folder1Subscriber = self.folder1["folder1Subscriber"]
- self.folder1_1["folder1_1Subscriber"] = DummySubscriber()
- self.folder1_1Subscriber = self.folder1_1["folder1_1Subscriber"]
-
- def _createHubIdSubscribers(self):
- self._createSubscribers()
- self.objectHub.lib = [
- ('/rootFolderSubscriber', self.rootFolderSubscriber),
- ('/folder1/folder1Subscriber', self.folder1Subscriber),
- ('/folder1/folder1_1/folder1_1Subscriber', self.folder1_1Subscriber)
- ]
- self.rootSubscriberHubId = 0
- self.folder1SubscriberHubId = 1
- self.folder1_1SubscriberHubId = 2
-
- def testCreateNestedServices(self):
- self._createNestedServices()
-
- def testByPath(self):
- # test complex interaction, with no hubids available
- self._createSubscribers()
- root = subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectAddedEvent
- )
- folder1 = subscribe(self.folder1Subscriber,
- event_type=IObjectAddedEvent)
- folder1_1 = subscribe(self.folder1_1Subscriber,
- event_type=IObjectAddedEvent)
- self.assertEqual(root, getPath(self.rootFolderSubscriber))
- self.assertEqual(folder1, getPath(self.folder1Subscriber))
- self.assertEqual(folder1_1, getPath(self.folder1_1Subscriber))
- publish(self.folder1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
- self.assertEqual(self.folder1Subscriber.notified, 1)
- self.assertEqual(self.folder1_1Subscriber.notified, 1)
- rootPath = getPath(self.rootFolderSubscriber)
- folder1Path = getPath(self.folder1Subscriber)
- folder1_1Path = getPath(self.folder1_1Subscriber)
- unsubscribeAll(rootPath, context=self.rootFolder)
- # curve ball:
- unsubscribeAll(self.folder1Subscriber, context=self.folder1_1)
- unsubscribe(folder1_1Path,
- event_type=IObjectAddedEvent,
- context=self.folder1_1)
- publish(self.folder1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
- self.assertEqual(self.folder1Subscriber.notified, 1)
- self.assertEqual(self.folder1_1Subscriber.notified, 1)
-
- def testByHubId(self):
- # test complex interaction, with hubids available
- self._createHubIdSubscribers()
- root = subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectAddedEvent
- )
- folder1 = subscribe(self.folder1Subscriber,
- event_type=IObjectAddedEvent)
- folder1_1 = subscribe(self.folder1_1Subscriber,
- event_type=IObjectAddedEvent)
- self.assertEqual(
- self.objectHub.lib[self.rootSubscriberHubId],
- ('/rootFolderSubscriber', self.rootFolderSubscriber)
- )
- self.assertEqual(
- self.objectHub.lib[self.folder1SubscriberHubId],
- ('/folder1/folder1Subscriber', self.folder1Subscriber)
- )
- self.assertEqual(
- self.objectHub.lib[self.folder1_1SubscriberHubId],
- ('/folder1/folder1_1/folder1_1Subscriber',
- self.folder1_1Subscriber)
- )
- publish(self.folder1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
- self.assertEqual(self.folder1Subscriber.notified, 1)
- self.assertEqual(self.folder1_1Subscriber.notified, 1)
- unsubscribe(getPath(self.rootFolderSubscriber),
- event_type=IObjectAddedEvent,
- context=self.rootFolder)
- subscribe(self.rootFolderSubscriber,
- event_type=IObjectAddedEvent)
- unsubscribeAll(self.rootSubscriberHubId, context=self.rootFolder)
- # curve balls:
- unsubscribeAll(self.folder1Subscriber, context=self.folder1_1)
- unsubscribe(2,
- event_type=IObjectAddedEvent,
- context=self.folder1_1)
- publish(self.folder1, ObjectAddedEvent(None, 'fauxparent', 'foo'))
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
- self.assertEqual(self.folder1Subscriber.notified, 1)
- self.assertEqual(self.folder1_1Subscriber.notified, 1)
-
- def testBadSubscriber(self):
- self._createSubscribers()
- root = subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectAddedEvent
- )
- folder1 = subscribe(self.folder1Subscriber,
- event_type=IObjectAddedEvent)
- folder1_1 = subscribe(self.folder1_1Subscriber,
- event_type=IObjectAddedEvent)
- self.assertEqual(root, getPath(self.rootFolderSubscriber))
- self.assertEqual(folder1, getPath(self.folder1Subscriber))
- self.assertEqual(folder1_1, getPath(self.folder1_1Subscriber))
- # Remove folder1Subscriber, so that the event service will not
- # be able to notify it.
- folder1Subscriber = self.folder1['folder1Subscriber']
- del self.folder1['folder1Subscriber']
-
- publish(self.folder1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
- self.assertEqual(self.folder1Subscriber.notified, 0)
- self.assertEqual(self.folder1_1Subscriber.notified, 1)
-
- # Now, put folder1Subscriber back. This incidentally fires off a
- # ObjectAddedEvent, since self.folder1 is decorated with a context
- # decorator.
- self.folder1['folder1Subscriber'] = folder1Subscriber
- self.assertEqual(self.rootFolderSubscriber.notified, 2)
- self.assertEqual(self.folder1Subscriber.notified, 0)
- self.assertEqual(self.folder1_1Subscriber.notified, 2)
-
- # folder1Subscriber should not be notified now, because it was removed
- # as a bad subscriber.
- publish(self.folder1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 3)
- self.assertEqual(self.folder1Subscriber.notified, 0)
- self.assertEqual(self.folder1_1Subscriber.notified, 3)
-
- def testByPathExplicit(self):
- # test complex interaction, with hubids available but explicitly
- # using paths
- self._createHubIdSubscribers()
- rootPath = getPath(self.rootFolderSubscriber)
- folder1Path = getPath(self.folder1Subscriber)
- folder1_1Path = getPath(self.folder1_1Subscriber)
- self.assertEqual(
- rootPath,
- subscribe(
- rootPath,
- event_type=IObjectAddedEvent,
- context=self.rootFolder))
- self.assertEqual(
- folder1Path,
- subscribe(
- folder1Path,
- event_type=IObjectAddedEvent,
- context=self.folder1))
- self.assertEqual(
- folder1_1Path,
- subscribe(
- folder1_1Path,
- event_type=IObjectAddedEvent,
- context=self.folder1_1))
- publish(self.folder1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
- self.assertEqual(self.folder1Subscriber.notified, 1)
- self.assertEqual(self.folder1_1Subscriber.notified, 1)
- unsubscribeAll(rootPath, context=self.rootFolder)
- # curve balls:
- unsubscribeAll(self.folder1Subscriber, context=self.folder1_1)
- unsubscribe(2, event_type=IObjectAddedEvent, context=self.folder1_1)
- subscribe(2, event_type=IObjectAddedEvent, context=self.folder1_1)
-
- # this is supposed to unsubscribe '2'
- unsubscribe(folder1_1Path,
- event_type=IObjectAddedEvent,
- context=self.folder1_1)
- publish(self.folder1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
- self.assertEqual(self.folder1Subscriber.notified, 1)
- self.assertEqual(self.folder1_1Subscriber.notified, 1)
-
- def testByHubIdExplicit(self):
- # test complex interaction, with hubids available and explicitly
- # using them
- self._createHubIdSubscribers()
- root = subscribe(
- 0,
- event_type=IObjectAddedEvent,
- context = self.folder1_1
- )
- folder1 = subscribe(1,
- event_type=IObjectAddedEvent,
- context = self.folder1)
- folder1_1 = subscribe(2,
- event_type=IObjectAddedEvent,
- context = self.rootFolder)
- self.assertEqual(
- self.objectHub.lib[root],
- ('/rootFolderSubscriber', self.rootFolderSubscriber)
- )
- self.assertEqual(
- self.objectHub.lib[folder1],
- ('/folder1/folder1Subscriber', self.folder1Subscriber)
- )
- self.assertEqual(
- self.objectHub.lib[folder1_1],
- ('/folder1/folder1_1/folder1_1Subscriber',
- self.folder1_1Subscriber)
- )
- publish(self.folder1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
- self.assertEqual(self.folder1Subscriber.notified, 1)
- self.assertEqual(self.folder1_1Subscriber.notified, 1)
- unsubscribe(getPath(self.rootFolderSubscriber),
- event_type=IObjectAddedEvent,
- context=self.rootFolder)
- subscribe(self.rootFolderSubscriber, event_type=IObjectAddedEvent,
- context=self.rootFolder)
- unsubscribeAll(root, context=self.rootFolder)
- # curve ball:
- unsubscribeAll(self.folder1Subscriber, context=self.folder1_1)
- unsubscribe(2,
- event_type=IObjectAddedEvent,
- context=self.folder1_1)
- publish(self.folder1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
- self.assertEqual(self.folder1Subscriber.notified, 1)
- self.assertEqual(self.folder1_1Subscriber.notified, 1)
-
- def _testIterSubscriptions1(self):
- # a non-subscribed subscriber gets an empty array
- events = getSubscriptionService(self.rootFolder)
-
- self.assertEqual(
- [x for x in events.iterSubscriptions(self.rootFolderSubscriber)],
- [])
-
- def testPathIterSubscriptions1(self):
- self._createSubscribers()
- self._testIterSubscriptions1()
-
- def testHubIdIterSubscriptions1(self):
- self._createHubIdSubscribers()
- self._testIterSubscriptions1()
-
- def _testIterSubscriptions2(self, subscription_type):
- # one subscription
- subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectAddedEvent
- )
- if subscription_type is int:
- reference = 0
- else:
- reference = u'/rootFolderSubscriber'
- events = getSubscriptionService(self.rootFolder)
- self.assertEqual(
- [x for x in events.iterSubscriptions(self.rootFolderSubscriber)],
- [(reference, IObjectAddedEvent, None)]
- )
-
- def testPathIterSubscriptions2(self):
- self._createSubscribers()
- self._testIterSubscriptions2(unicode)
-
- def testHubIdIterSubscriptions2(self):
- self._createHubIdSubscribers()
- self._testIterSubscriptions2(int)
-
- def _testIterSubscriptions3(self):
- # listing limited subscription
- subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectAddedEvent
- )
- self.assertEqual(
- [],
- [x for x in getSubscriptionService(self.rootFolder)
- .iterSubscriptions(self.rootFolderSubscriber, IObjectRemovedEvent)]
- )
-
- def testPathIterSubscriptions3(self):
- self._createSubscribers()
- self._testIterSubscriptions3()
-
- def testHubIdIterSubscriptions3(self):
- self._createHubIdSubscribers()
- self._testIterSubscriptions3()
-
- def _testIterSubscriptions4(self):
- # a non-subscribed subscriber gets an empty array
- events = getSubscriptionService(self.rootFolder)
-
- self.assertEqual(
- [x for x in events.iterSubscriptions(self.rootFolderSubscriber)],
- [])
-
- def testPathIterSubscriptions4(self):
- self._createSubscribers()
- self._testIterSubscriptions4()
-
- def testHubIdIterSubscriptions4(self):
- self._createHubIdSubscribers()
- self._testIterSubscriptions4()
-
- def _testIterSubscriptions5(self, subscription_type):
- if subscription_type is int:
- reference = 0
- else:
- reference = u'/rootFolderSubscriber'
- # one subscription
- subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectAddedEvent
- )
- self.assertEqual(
- [x for x in getSubscriptionService(self.rootFolder)
- .iterSubscriptions(self.rootFolderSubscriber)],
- [(reference, IObjectAddedEvent, None)]
- )
-
- def testPathIterSubscriptions5(self):
- self._createSubscribers()
- self._testIterSubscriptions5(unicode)
-
- def testHubIdIterSubscriptions5(self):
- self._createHubIdSubscribers()
- self._testIterSubscriptions5(int)
-
- def _testIterSubscriptions6(self):
- # listing limited subscription
- subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectAddedEvent
- )
- self.assertEqual(
- [x for x in getSubscriptionService(self.rootFolder)
- .iterSubscriptions(self.rootFolderSubscriber, IObjectRemovedEvent)],
- []
- )
-
- def testPathIterSubscriptions6(self):
- self._createSubscribers()
- self._testIterSubscriptions6()
-
- def testHubIdIterSubscriptions6(self):
- self._createHubIdSubscribers()
- self._testIterSubscriptions6()
-
- def _testSubscribe1(self):
- # Test subscribe method with one parameter
- subscribe(self.rootFolderSubscriber)
- publish(self.rootFolder, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
-
- def testPathSubscribe1(self):
- self._createSubscribers()
- self._testSubscribe1()
-
- def testHubIdSubscribe1(self):
- self._createHubIdSubscribers()
- self._testSubscribe1()
-
- def _testSubscribe2(self):
- # Test subscribe method with two parameters
- subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectAddedEvent
- )
- publish(self.folder1_1_1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
-
- def testPathSubscribe2(self):
- self._createSubscribers()
- self._testSubscribe2()
-
- def testHubIdSubscribe2(self):
- self._createHubIdSubscribers()
- self._testSubscribe2()
-
- def _testSubscribe3(self):
- # Test subscribe method with three parameters
- subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectAddedEvent,
- filter=DummyFilter()
- )
- publish(self.folder1_1_1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
-
- def testPathSubscribe3(self):
- self._createSubscribers()
- self._testSubscribe3()
-
- def testHubIdSubscribe3(self):
- self._createHubIdSubscribers()
- self._testSubscribe3()
-
- def _testSubscribe4(self):
- # Test subscribe method with three parameters and an always failing
- # filter.
- subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectAddedEvent,
- filter=DummyFilter(0)
- )
- publish(self.folder1_1_1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 0)
-
- def testPathSubscribe4(self):
- self._createSubscribers()
- self._testSubscribe4()
-
- def testHubIdSubscribe4(self):
- self._createHubIdSubscribers()
- self._testSubscribe4()
-
- def _testSubscribe5(self):
- # Test subscribe method with three parameters and an irrelevent event
- # type.
- subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectModifiedEvent,
- filter=DummyFilter()
- )
- publish(self.folder1_1_1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 0)
-
- def testPathSubscribe5(self):
- self._createSubscribers()
- self._testSubscribe5()
-
- def testHubIdSubscribe5(self):
- self._createHubIdSubscribers()
- self._testSubscribe5()
-
- def _testSubscribe6(self):
- # Test subscribe method where the event type registered is a
- # generalised interface of the event passed to the 'publish' method.
- subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectEvent
- )
- publish(self.folder1_1_1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
-
- def testPathSubscribe6(self):
- self._createSubscribers()
- self._testSubscribe6()
-
- def testHubIdSubscribe6(self):
- self._createHubIdSubscribers()
- self._testSubscribe6()
-
- def _testSubscribe7(self):
- # Test subscribe method where one of the event types registered is not
- # interested in the published event.
- subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectModifiedEvent
- )
- subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectAddedEvent
- )
- publish(self.folder1_1_1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
-
- def testPathSubscribe7(self):
- self._createSubscribers()
- self._testSubscribe7()
-
- def testHubIdSubscribe7(self):
- self._createHubIdSubscribers()
- self._testSubscribe7()
-
- def _testSubscribe8(self):
- # Test subscribe method where the same subscriber subscribes multiple
- # times.
- subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectAddedEvent
- )
- subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectAddedEvent
- )
- subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectAddedEvent,
- filter=DummyFilter(0)
- )
- publish(self.folder1_1_1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 2)
-
- def testPathSubscribe8(self):
- self._createSubscribers()
- self._testSubscribe8()
-
- def testHubIdSubscribe8(self):
- self._createHubIdSubscribers()
- self._testSubscribe8()
-
- def _testUnsubscribe1(self):
- # Test unsubscribe method
- subscribe(
- self.rootFolderSubscriber
- )
- publish(self.folder1_1_1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
- unsubscribeAll(
- self.rootFolderSubscriber
- )
- publish(self.folder1_1_1, ObjectAddedEvent(foo))
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
-
- def testPathUnsubscribe1(self):
- self._createSubscribers()
- self._testUnsubscribe1()
-
- def testHubIdUnsubscribe1(self):
- self._createHubIdSubscribers()
- self._testUnsubscribe1()
-
- def _testUnsubscribe2(self):
- # Test unsubscribe of something that hasn't been subscribed
- self.assertRaises(NotFoundError,
- unsubscribe,
- 69,
- IObjectEvent)
- unsubscribeAll(self.rootFolderSubscriber)
-
- def testPathUnsubscribe2(self):
- self._createSubscribers()
- self._testUnsubscribe2()
-
- def testHubIdUnsubscribe2(self):
- self._createHubIdSubscribers()
- self._testUnsubscribe2()
-
- def _testUnsubscribe3(self):
- # Test selective unsubscribe
- subscriber = self.rootFolderSubscriber
- subscriber2 = self.folder1Subscriber
- filter = DummyFilter()
- event = ObjectAddedEvent(foo)
- event2 = ObjectModifiedEvent(None)
- subscribe(
- subscriber)
- subscribe(
- subscriber,
- event_type=IObjectAddedEvent,
- filter=filter
- )
- subscribe(
- subscriber,
- event_type=IObjectAddedEvent
- )
- subscribe(
- subscriber2,
- event_type=IObjectAddedEvent
- )
- publish(self.folder1_1_1, event)
- self.assertEqual(subscriber.notified, 3)
- self.assertEqual(subscriber2.notified, 1)
- publish(self.folder1_1_1, event2)
- self.assertEqual(subscriber.notified, 4)
- self.assertEqual(subscriber2.notified, 1)
- unsubscribe(subscriber, IObjectAddedEvent)
- publish(self.folder1_1_1, event)
- self.assertEqual(subscriber.notified, 6)
- self.assertEqual(subscriber2.notified, 2)
- unsubscribe(subscriber, IEvent)
- publish(self.folder1_1_1, event2)
- self.assertEqual(subscriber.notified, 6)
- self.assertEqual(subscriber2.notified, 2)
- publish(self.folder1_1_1, event)
- self.assertEqual(subscriber.notified, 7)
- self.assertEqual(subscriber2.notified, 3)
- self.assertRaises(NotFoundError, unsubscribe, subscriber,
- IObjectAddedEvent)
- unsubscribe(subscriber, IObjectAddedEvent, filter)
- publish(self.folder1_1_1, event)
- self.assertEqual(subscriber.notified, 7)
- self.assertEqual(subscriber2.notified, 4)
- unsubscribe(subscriber2, IObjectAddedEvent)
- publish(self.folder1_1_1, event)
- self.assertEqual(subscriber.notified, 7)
- self.assertEqual(subscriber2.notified, 4)
-
- def testPathUnsubscribe3(self):
- self._createSubscribers()
- self._testUnsubscribe3()
-
- def testHubIdUnsubscribe3(self):
- self._createHubIdSubscribers()
- self._testUnsubscribe3()
-
- def testPathUnsubscribe4(self):
- self._createNestedServices()
- self._createSubscribers()
- self._testUnsubscribe3()
-
- def testHubIdUnsubscribe4(self):
- self._createNestedServices()
- self._createHubIdSubscribers()
- self._testUnsubscribe3()
-
- def _testpublish1(self):
- # Test publish method
- subscriber = self.rootFolderSubscriber
- subscribe(subscriber)
- self.assertEqual(subscriber.notified, 0)
- publish(self.folder1_1_1, ObjectAddedEvent(foo))
- self.assertEqual(subscriber.notified, 1)
-
- def testPathPublish1(self):
- self._createSubscribers()
- self._testpublish1()
-
- def testHubIdPublish1(self):
- self._createHubIdSubscribers()
- self._testpublish1()
-
- def _testpublish2(self):
- # Test publish method where subscriber has been subscribed twice, with
- # a more generalised version of the initially subscribed interface in
- # the second subscription.
- subscriber = self.rootFolderSubscriber
- subscribe(
- subscriber,
- event_type=IObjectEvent,
- )
- subscribe(
- subscriber,
- event_type=IObjectAddedEvent,
- )
- publish(self.folder1_1_1, ObjectAddedEvent(foo))
- self.assertEqual(subscriber.notified, 2)
-
- def testPathPublish2(self):
- self._createSubscribers()
- self._testpublish2()
-
- def testHubIdPublish2(self):
- self._createHubIdSubscribers()
- self._testpublish2()
-
- def _testpublish3(self):
- # Test publish method where subscriber has been to two interfaces and
- # a single event implements both of those interfaces.
- subscriber = self.rootFolderSubscriber
- subscribe(
- subscriber,
- event_type=IObjectRemovedEvent
- )
- subscribe(
- subscriber,
- event_type=IObjectAddedEvent
- )
- publish(self.folder1_1_1, DummyEvent())
- self.assertEqual(subscriber.notified, 2)
-
- def testPathPublish3(self):
- self._createSubscribers()
- self._testpublish3()
-
- def testHubIdPublish3(self):
- self._createHubIdSubscribers()
- self._testpublish3()
-
- def _testpublish4(self):
- # Test publish method to make sure that we don't 'leak registrations
- # up' sez Jim.
- subscriber = self.rootFolderSubscriber
- subscribe(
- subscriber,
- event_type=IObjectEvent
- )
- subscribe(
- subscriber,
- event_type=IObjectAddedEvent
- )
- publish(self.folder1_1_1, ObjectEvent())
- self.assertEqual(subscriber.notified, 1)
-
- def testPathPublish4(self):
- self._createSubscribers()
- self._testpublish4()
-
- def testHubIdPublish4(self):
- self._createHubIdSubscribers()
- self._testpublish4()
-
- def _createAlternateService(self, service):
- self.folder2["folder2Subscriber"] = DummySubscriber()
- self.folder2Subscriber = self.folder2["folder2Subscriber"]
-
- sm = self.makeSite('folder2')
- setup.addService(sm, EventPublication, service);
- setup.addService(sm, EventSubscription, service, suffix='s');
-
- subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectAddedEvent
- )
- subscribe(
- self.folder2Subscriber,
- event_type=IObjectAddedEvent
- )
-
- def testNonPromotingEventPublisher(self):
- # test to see if events are not passed on to a parent event service
- # with the appropriate isPromotableEvent setting
- self._createHubIdSubscribers()
- self._createAlternateService(UnpromotingEventService())
- publish(self.folder2, ObjectAddedEvent(foo))
- self.assertEqual(self.folder2Subscriber.notified, 1)
- self.assertEqual(self.rootFolderSubscriber.notified, 0)
-
- def testPromotingEventPublisher1(self):
- # test to see if events are passed on to a parent event service with
- # the appropriate isPromotableEvent setting
- self._createHubIdSubscribers()
- self._createAlternateService(EventService())
- publish(self.folder2, ObjectAddedEvent(foo))
- self.assertEqual(self.folder2Subscriber.notified, 1)
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
-
- def testUnbindingResubscribing1(self):
- # an event service is unbound; a lower event service should then
- # rebind to upper event service
- self._createNestedServices()
- self._createHubIdSubscribers()
- subscribe(
- self.rootFolderSubscriber,
- event_type=IObjectAddedEvent
- )
- subscribe(
- self.folder1Subscriber,
- event_type=IObjectAddedEvent
- )
- subscribe(
- self.folder1_1Subscriber,
- event_type=IObjectAddedEvent
- )
-
- sm = traverse(self.rootFolder, "folder1/++etc++site")
- registration = sm.queryRegistrations(EventPublication).active()
- registration.status = RegisteredStatus
- publish(self.rootFolder, ObjectAddedEvent(foo))
- self.assertEqual(self.folder1Subscriber.notified, 1)
- self.assertEqual(self.folder1_1Subscriber.notified, 1)
-
- registration = sm.queryRegistrations(EventSubscription).active()
- registration.status = RegisteredStatus
-
- publish(self.rootFolder, ObjectAddedEvent(foo))
- self.assertEqual(self.folder1Subscriber.notified, 1)
- self.assertEqual(self.folder1_1Subscriber.notified, 2)
-
- def testNoSubscribeOnBind(self):
- # if subscribeOnBind is 0, service should not subscribe to parent
- sv = EventService()
- sv.subscribeOnBind = 0
- self._createHubIdSubscribers()
- self._createAlternateService(sv)
- publish(self.rootFolder, ObjectAddedEvent(foo))
- self.assertEqual(self.folder2Subscriber.notified, 0)
- self.assertEqual(self.rootFolderSubscriber.notified, 1)
-
- sm = traverse(self.rootFolder, "folder2/++etc++site")
- registration = sm.queryRegistrations(EventSubscription).active()
- # make sure it doesn't raise any errors
- registration.status = RegisteredStatus
- registration = sm.queryRegistrations(EventPublication).active()
- # make sure it doesn't raise any errors
- registration.status = RegisteredStatus
-
- def testSubscriptionAwareInteraction(self):
- adapter = SubscribingAwareAdapter()
- ztapi.provideAdapter(IHasSubscribingAwareAdapter,
- ISubscribingAware,
- adapter)
- self.rootFolder["mySubscriber"] = HasSubscribingAwareAdapter()
- self.mySubscriber = self.rootFolder["mySubscriber"]
- filter = DummyFilter()
- subscribe(
- self.mySubscriber,
- event_type=IObjectAddedEvent,
- filter=filter)
- adapter.check(
- ('subscribed',
- self.mySubscriber,
- getSubscriptionService(self.rootFolder),
- IObjectAddedEvent,
- filter
- )
- )
- #self.assertEqual(
- # self.mySubscriber.subscribable,
- # getEventService(self.rootFolder))
- #self.assertEqual(
- # self.mySubscriber.subscribable,
- # getSubscriptionService(self.rootFolder))
- #self.assertEqual(
- # self.mySubscriber.event_type,
- # IObjectAddedEvent)
- #self.assertEqual(
- # self.mySubscriber.filter,
- # filter)
- unsubscribe(
- self.mySubscriber,
- event_type=IObjectAddedEvent,
- filter=filter)
- adapter.check(
- ('subscribed',
- self.mySubscriber,
- getSubscriptionService(self.rootFolder),
- IObjectAddedEvent,
- filter
- ),
- ('unsubscribed',
- self.mySubscriber,
- getSubscriptionService(self.rootFolder),
- IObjectAddedEvent,
- filter
- )
- )
-
-
-
-def test_suite():
- loader = TestLoader()
- return loader.loadTestsFromTestCase(TestEventPublisher)
-
-if __name__=='__main__':
- TextTestRunner().run(test_suite())
Deleted: Zope3/trunk/src/zope/app/event/tests/test_logger.py
===================================================================
--- Zope3/trunk/src/zope/app/event/tests/test_logger.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/tests/test_logger.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,116 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""
-$Id$
-"""
-
-import unittest
-import logging
-
-from zope.component.tests.placelesssetup import PlacelessSetup
-from zope.component import getGlobalServices
-from zope.app.servicenames import EventPublication
-
-from zope.app.event import globalSubscribe, globalUnsubscribe, publish
-from zope.app.container.contained import ObjectAddedEvent
-from zope.app.event.globalservice import Logger, eventPublisher
-from zope.app.event.interfaces import IPublisher
-
-class DopeyHandler(logging.Handler):
-
- def __init__(self):
- logging.Handler.__init__(self)
- self.results = []
-
- def emit(self, record):
- self.results.append(record)
-
-class TestLogger1(PlacelessSetup,unittest.TestCase):
-
- eventlogger = Logger()
-
- def setUp(self):
- super(TestLogger1, self).setUp()
- getGlobalServices().defineService(EventPublication, IPublisher)
- getGlobalServices().provideService(EventPublication, eventPublisher)
- # futz a handler in for testing
- self.logger = logging.getLogger("Event.Logger")
- self.oldlevel = self.logger.level
- self.oldprop = self.logger.propagate
- self.logger.propagate = False
- self.logger.setLevel(logging.DEBUG)
- self.handler = DopeyHandler()
- self.logger.addHandler(self.handler)
- # register a logger
- globalSubscribe(self.eventlogger)
- # send an event
- publish(None, ObjectAddedEvent(None, "parent", 'foo'))
-
- def tearDown(self):
- globalUnsubscribe(self.eventlogger)
- self.logger.removeHandler(self.handler)
- self.logger.setLevel(self.oldlevel)
- self.logger.propagate = self.oldprop
- PlacelessSetup.tearDown(self)
-
- def testLogger(self):
- # Test the logger logs appropriately
- results = self.handler.results
- self.assertEqual(len(results), 1)
- result = results[0]
- self.assertEqual(result.name, "Event.Logger")
- self.assertEqual(result.levelno, logging.INFO)
- self.assertEqual(
- result.getMessage(),
- "zope.app.container.contained.ObjectAddedEvent: ["
- "('newName', 'foo'),\n "
- "('newParent', 'parent'),\n "
- "('object', None),\n "
- "('oldName', None),\n "
- "('oldParent', None)"
- "]\n"
- )
- self.assertEqual(result.exc_info, None)
-
-class TestLogger2(TestLogger1):
-
- eventlogger = Logger(logging.CRITICAL)
-
- def testLogger(self):
- # Test the logger logs appropriately
- results = self.handler.results
- self.assertEqual(len(results), 1)
- result = results[0]
- self.assertEqual(result.name, "Event.Logger")
- self.assertEqual(result.levelno, logging.CRITICAL)
- self.assertEqual(
- result.getMessage(),
- "zope.app.container.contained.ObjectAddedEvent: ["
- "('newName', 'foo'),\n "
- "('newParent', 'parent'),\n "
- "('object', None),\n "
- "('oldName', None),\n "
- "('oldParent', None)"
- "]\n"
- )
- self.assertEqual(result.exc_info, None)
-
-def test_suite():
- return unittest.TestSuite([
- unittest.makeSuite(TestLogger1),
- unittest.makeSuite(TestLogger2),
- ])
-
-if __name__ == '__main__':
- unittest.main(defaultTest='test_suite')
Modified: Zope3/trunk/src/zope/app/event/tests/test_objectevent.py
===================================================================
--- Zope3/trunk/src/zope/app/event/tests/test_objectevent.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/event/tests/test_objectevent.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -28,11 +28,9 @@
from zope.app.container.contained import Contained, ObjectRemovedEvent
from zope.app.container.interfaces import IContained, IObjectRemovedEvent
from zope.app.container.interfaces import IObjectEvent
-from zope.app.event.interfaces import ISubscriber
from zope.app.container.sample import SampleContainer
from zope.app.tests.placelesssetup import setUp, tearDown
-from zope.app.servicenames import Adapters, EventPublication
-from zope.component import getService
+from zope.app.tests import ztapi
class TestObjectModifiedEvent(unittest.TestCase):
@@ -58,33 +56,29 @@
setUp()
def testNotify(self):
- notifier = objectevent.ObjectEventNotifier()
events = []
- factory = objectevent.objectEventCallbackHelper(events.append)
- getService(None, Adapters).subscribe(
- [IContained, IObjectRemovedEvent], ISubscriber, factory
- )
+ def record(*args):
+ events.append(args)
+ ztapi.handle([IContained, IObjectRemovedEvent], record)
+
item = Contained()
event = ObjectRemovedEvent(item)
- notifier.notify(event)
- self.assertEqual([event], events)
+ objectevent.objectEventNotify(event)
+ self.assertEqual([(item, event)], events)
def testNotifyNobody(self):
# Check that notify won't raise an exception in absence of
# of subscribers.
- notifier = objectevent.ObjectEventNotifier()
events = []
item = Contained()
evt = ObjectRemovedEvent(item)
- notifier.notify(evt)
+ objectevent.objectEventNotify(evt)
self.assertEqual([], events)
def testVeto(self):
- eventPublication = getService(None, EventPublication)
- eventPublication.globalSubscribe(objectevent.ObjectEventNotifier(),
- IObjectEvent)
+ ztapi.handle([IObjectEvent], objectevent.objectEventNotify)
container = SampleContainer()
item = Contained()
@@ -94,15 +88,12 @@
class Veto(Exception):
pass
- def callback(event):
+ def callback(item, event):
self.callbackTriggered = True
self.assertEqual(item, event.object)
raise Veto
- factory = objectevent.objectEventCallbackHelper(callback)
- getService(None, Adapters).subscribe(
- [IContained, IObjectRemovedEvent], ISubscriber, factory
- )
+ ztapi.handle([IContained, IObjectRemovedEvent], callback)
# del container['Fred'] will fire an ObjectRemovedEvent event.
self.assertRaises(Veto, container.__delitem__, 'Fred')
Modified: Zope3/trunk/src/zope/app/form/browser/add.py
===================================================================
--- Zope3/trunk/src/zope/app/form/browser/add.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/form/browser/add.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -18,7 +18,7 @@
import sys
from zope.app import zapi
-from zope.app.event import publish
+from zope.event import notify
from zope.app.event.objectevent import ObjectCreatedEvent
from zope.app.form.utility import setUpWidgets, getWidgetsData
from zope.app.i18n import ZopeMessageIDFactory as _
@@ -103,7 +103,7 @@
if errors:
raise WidgetsError(*errors)
- publish(self.context, ObjectCreatedEvent(content))
+ notify(ObjectCreatedEvent(content))
content = self.add(content)
Modified: Zope3/trunk/src/zope/app/form/browser/addwizard.py
===================================================================
--- Zope3/trunk/src/zope/app/form/browser/addwizard.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/form/browser/addwizard.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -18,7 +18,7 @@
import sys
from zope.app import zapi
-from zope.app.event import publish
+from zope.event import notify
from zope.app.event.objectevent import ObjectCreatedEvent
from zope.app.form.utility import setUpWidgets
from zope.app.form.interfaces import WidgetsError, IInputWidget
@@ -87,7 +87,7 @@
if errors:
raise WidgetsError(*errors)
- publish(self.context, ObjectCreatedEvent(content))
+ notify(ObjectCreatedEvent(content))
content = self.context.add(content)
Modified: Zope3/trunk/src/zope/app/form/browser/editview.py
===================================================================
--- Zope3/trunk/src/zope/app/form/browser/editview.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/form/browser/editview.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -23,7 +23,7 @@
from zope.component import getAdapter
from zope.app import zapi
-from zope.app.event import publish
+from zope.event import notify
from zope.app.event.objectevent import ObjectModifiedEvent
from zope.app.i18n import ZopeMessageIDFactory as _
from zope.app.form.interfaces import WidgetsError
@@ -100,7 +100,7 @@
# We should not generate events when an adapter is used.
# That's the adapter's job.
if changed and self.context is self.adapted:
- publish(content, ObjectModifiedEvent(content))
+ notify(ObjectModifiedEvent(content))
except WidgetsError, errors:
self.errors = errors
status = _("An error occured.")
Modified: Zope3/trunk/src/zope/app/form/browser/editwizard.py
===================================================================
--- Zope3/trunk/src/zope/app/form/browser/editwizard.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/form/browser/editwizard.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -21,7 +21,7 @@
from zope.security.checker import defineChecker, NamesChecker
from zope.app import zapi
-from zope.app.event import publish
+from zope.event import notify
from zope.app.event.objectevent import ObjectModifiedEvent
from zope.app.i18n import ZopeMessageIDFactory as _
from zope.app.location.interfaces import ILocation
@@ -183,7 +183,7 @@
# We should not generate events when an adapter is used.
# That's the adapter's job
if changed and self.context is self.adapted:
- publish(content, ObjectModifiedEvent(content))
+ notify(ObjectModifiedEvent(content))
return not changed
def renderHidden(self):
Modified: Zope3/trunk/src/zope/app/form/browser/tests/test_configure.py
===================================================================
--- Zope3/trunk/src/zope/app/form/browser/tests/test_configure.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/form/browser/tests/test_configure.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -28,7 +28,6 @@
xmlconfig.string(
"""<configure xmlns='http://namespaces.zope.org/zope'>
<include package='zope.app.component' file='meta.zcml' />
- <include package='zope.app.event' file='meta.zcml' />
<include package='zope.app.publisher.browser'
file='meta.zcml' />
Modified: Zope3/trunk/src/zope/app/fssync/committer.py
===================================================================
--- Zope3/trunk/src/zope/app/fssync/committer.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/fssync/committer.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -32,7 +32,7 @@
from zope.app.traversing.api import traverseName, getName
from zope.app.filerepresentation.interfaces import IFileFactory
from zope.app.filerepresentation.interfaces import IDirectoryFactory
-from zope.app.event import publish
+from zope.event import notify
from zope.app.event.objectevent import ObjectCreatedEvent
from zope.app.event.objectevent import ObjectModifiedEvent
from zope.app.container.contained import contained
@@ -359,7 +359,7 @@
except:
pass
else:
- publish(obj, ObjectModifiedEvent(obj))
+ notify(ObjectModifiedEvent(obj))
def create_object(self, container, name, entry, fspath, replace=False,
context=None):
@@ -428,7 +428,7 @@
"""Helper to set an item in a container or mapping."""
if IContainer.providedBy(container):
if not replace:
- publish(container, ObjectCreatedEvent(obj))
+ notify(ObjectCreatedEvent(obj))
if replace:
del container[name]
Modified: Zope3/trunk/src/zope/app/ftp/__init__.py
===================================================================
--- Zope3/trunk/src/zope/app/ftp/__init__.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/ftp/__init__.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -29,7 +29,7 @@
from zope.app.filerepresentation.interfaces import IFileFactory
from zope.app.filerepresentation.interfaces import IDirectoryFactory
-from zope.app.event import publish
+from zope.event import notify
from zope.app.event.objectevent import ObjectCreatedEvent
from zope.app.dublincore.interfaces import IZopeDublinCore
from zope.app.copypastemove import rename
@@ -144,7 +144,7 @@
dir = IWriteDirectory(self.context, None)
factory = IDirectoryFactory(self.context)
newdir = factory(name)
- publish(self.context, ObjectCreatedEvent(newdir))
+ notify(ObjectCreatedEvent(newdir))
dir[name] = newdir
def remove(self, name):
@@ -213,7 +213,7 @@
factory = IFileFactory(self.context)
newfile = factory(name, '', data)
- publish(self.context, ObjectCreatedEvent(newfile))
+ notify(ObjectCreatedEvent(newfile))
dir[name] = newfile
def writable(self, name):
Modified: Zope3/trunk/src/zope/app/generations/generations.py
===================================================================
--- Zope3/trunk/src/zope/app/generations/generations.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/generations/generations.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -18,7 +18,6 @@
from interfaces import GenerationTooHigh, GenerationTooLow, UnableToEvolve
from interfaces import ISchemaManager
-from zope.app.event.interfaces import ISubscriber
import logging
import os
import zope.interface
@@ -352,18 +351,13 @@
conn.close()
-class EvolveSubscriber:
- zope.interface.implements(ISubscriber)
+def evolveSubscriber(event):
+ evolve(event.database, EVOLVE)
- def __init__(self, flag):
- self.flag = flag
+def evolveNotSubscriber(event):
+ evolve(event.database, EVOLVENOT)
- def notify(self, event):
- evolve(event.database, self.flag)
+def evolveMinimumSubscriber(event):
+ evolve(event.database, EVOLVEMINIMUM)
-
-evolveSubscriber = EvolveSubscriber(EVOLVE)
-evolveNotSubscriber = EvolveSubscriber(EVOLVENOT)
-evolveMinimumSubscriber = EvolveSubscriber(EVOLVEMINIMUM)
-
Modified: Zope3/trunk/src/zope/app/generations/subscriber.zcml
===================================================================
--- Zope3/trunk/src/zope/app/generations/subscriber.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/generations/subscriber.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,28 +1,28 @@
-<configure xmlns="http://namespaces.zope.org/event">
+<configure xmlns="http://namespaces.zope.org/zope">
<!--
-<subscribe
- subscriber=".generations.evolveSubscriber"
- event_types="zope.app.appsetup.IDatabaseOpenedEvent"
+<subscriber
+ factory=".generations.evolveSubscriber"
+ for="zope.app.appsetup.IDatabaseOpenedEvent"
>
Evolve to current generation on startup
-</subscribe>
+</subscriber>
-->
<!--
-<subscribe
- subscriber=".generations.evolveNotSubscriber"
- event_types="zope.app.appsetup.IDatabaseOpenedEvent"
+<subscriber
+ factory=".generations.evolveNotSubscriber"
+ for="zope.app.appsetup.IDatabaseOpenedEvent"
>
Don't evolve, but check for minimum generations on startup
-</subscribe>
+</subscriber>
-->
-<subscribe
- subscriber=".generations.evolveMinimumSubscriber"
- event_types="zope.app.appsetup.IDatabaseOpenedEvent"
+<subscriber
+ factory=".generations.evolveMinimumSubscriber"
+ for="zope.app.appsetup.IDatabaseOpenedEvent"
>
Only evolve to minimum generations on startup
-</subscribe>
+</subscriber>
</configure>
Modified: Zope3/trunk/src/zope/app/http/put.py
===================================================================
--- Zope3/trunk/src/zope/app/http/put.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/http/put.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -17,7 +17,7 @@
from zope.app.http.interfaces import INullResource
from zope.app.filerepresentation.interfaces import IWriteFile
from zope.app.filerepresentation.interfaces import IWriteDirectory, IFileFactory
-from zope.app.event import publish
+from zope.event import notify
from zope.app.event.objectevent import ObjectCreatedEvent
from zope.interface import implements
@@ -76,7 +76,7 @@
data = body.read()
newfile = factory(name, request.getHeader('content-type', ''), data)
- publish(self.context, ObjectCreatedEvent(newfile))
+ notify(ObjectCreatedEvent(newfile))
dir[name] = newfile
Modified: Zope3/trunk/src/zope/app/mail/interfaces.py
===================================================================
--- Zope3/trunk/src/zope/app/mail/interfaces.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/mail/interfaces.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -58,7 +58,6 @@
from zope.interface import Interface, Attribute
from zope.schema import Object, TextLine, Int, Password, BytesLine
-from zope.app.event.interfaces import IEvent
from zope.app.i18n import ZopeMessageIDFactory as _
@@ -176,7 +175,7 @@
default="/usr/lib/sendmail -oem -oi -f %(from)s %(to)s")
-class IMailEvent(IEvent):
+class IMailEvent(Interface):
"""Generic mail event."""
messageId = Attribute("Message id according to RFC 2822")
Modified: Zope3/trunk/src/zope/app/meta.zcml
===================================================================
--- Zope3/trunk/src/zope/app/meta.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/meta.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -8,7 +8,6 @@
<include package="zope.app.publisher" file="meta.zcml" />
<include package="zope.app.security" file="meta.zcml" />
<include package="zope.app.form.browser" file="meta.zcml" />
-<include package="zope.app.event" file="meta.zcml" />
<include package="zope.app.i18n" file="meta.zcml" />
<include package="zope.app.pagetemplate" file="meta.zcml" />
<include package="zope.app.schema" file="meta.zcml" />
Modified: Zope3/trunk/src/zope/app/module/__init__.py
===================================================================
--- Zope3/trunk/src/zope/app/module/__init__.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/module/__init__.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -20,7 +20,6 @@
from zope.interface import implements
from zope.security.proxy import trustedRemoveSecurityProxy
-from zope.app.event import function
from zope.app.annotation.interfaces import IAttributeAnnotatable
from zope.app.filerepresentation.interfaces import IFileFactory
from zope.app.module.interfaces import IModuleManager
@@ -108,6 +107,3 @@
def installPersistentModuleImporter(event):
from zodbcode.module import PersistentModuleImporter
PersistentModuleImporter().install()
-
-installPersistentModuleImporter = function.Subscriber(
- installPersistentModuleImporter)
Modified: Zope3/trunk/src/zope/app/module/browser/__init__.py
===================================================================
--- Zope3/trunk/src/zope/app/module/browser/__init__.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/module/browser/__init__.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -16,7 +16,7 @@
$Id$
"""
from zope.app.module import Manager
-from zope.app.event import publish
+from zope.event import notify
from zope.app.event.objectevent import ObjectCreatedEvent
from zope.app.publisher.browser import BrowserView
from zope.proxy import removeAllProxies
@@ -35,7 +35,7 @@
mgr = self.context.add(mgr) # local registration
mgr.execute()
self.request.response.redirect(self.context.nextURL())
- publish(self.context.context, ObjectCreatedEvent(mgr))
+ notify(ObjectCreatedEvent(mgr))
class EditModule(BrowserView):
Modified: Zope3/trunk/src/zope/app/module/configure.zcml
===================================================================
--- Zope3/trunk/src/zope/app/module/configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/module/configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,7 +1,4 @@
-<configure
- xmlns="http://namespaces.zope.org/zope"
- xmlns:event="http://namespaces.zope.org/event"
- >
+<configure xmlns="http://namespaces.zope.org/zope">
<content class=".Manager">
<require
@@ -20,9 +17,9 @@
/>
<!-- Enable import of persistent modules -->
- <event:subscribe
- subscriber=".installPersistentModuleImporter"
- event_types="zope.app.appsetup.IProcessStartingEvent"
+ <subscriber
+ factory=".installPersistentModuleImporter"
+ for="zope.app.appsetup.IProcessStartingEvent"
/>
<include package=".browser" />
Modified: Zope3/trunk/src/zope/app/observable/configure.zcml
===================================================================
--- Zope3/trunk/src/zope/app/observable/configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/observable/configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,10 +1,8 @@
-<configure
- xmlns="http://namespaces.zope.org/zope"
- xmlns:event="http://namespaces.zope.org/event"
- >
+<configure xmlns="http://namespaces.zope.org/zope">
-<event:subscribe
- subscriber=".observerevent.observerEventNotifierInstance"
- event_types="zope.app.event.interfaces.IObjectEvent" />
+<subscriber
+ factory=".observerevent.observerEventNotifier"
+ for="zope.app.event.interfaces.IObjectEvent"
+ />
</configure>
Modified: Zope3/trunk/src/zope/app/observable/observerevent.py
===================================================================
--- Zope3/trunk/src/zope/app/observable/observerevent.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/observable/observerevent.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -16,19 +16,10 @@
$Id$
"""
-from zope.app.event.interfaces import ISubscriber
from zope.app.observable.interfaces import IObservable
-from zope.interface import implements
-class ObserverEventNotifier:
+def observerEventNotifier(event):
+ adapter = IObservable(event.object, None)
+ if adapter is not None:
+ adapter.notify(event)
- implements(ISubscriber)
-
- def notify (self, event):
- adapter = IObservable(event.object, None)
-
- if adapter is not None:
- adapter.notify(event)
-
-observerEventNotifierInstance = ObserverEventNotifier()
-
Modified: Zope3/trunk/src/zope/app/observable/tests.py
===================================================================
--- Zope3/trunk/src/zope/app/observable/tests.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/observable/tests.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -146,8 +146,7 @@
handlers are notified.
>>> event = DummyObservableEvent()
- >>> notifier = observerevent.ObserverEventNotifier()
- >>> notifier.notify(event)
+ >>> observerevent.observerEventNotifier(event)
>>> event.object.flag
True
"""
@@ -159,8 +158,7 @@
ObserverEventNotifier doesn't do anything to it.
>>> event = DummyNotObservableEvent()
- >>> notifier = observerevent.ObserverEventNotifier()
- >>> notifier.notify(event)
+ >>> observerevent.observerEventNotifier(event)
>>> event.object.flag
False
"""
Modified: Zope3/trunk/src/zope/app/pluggableauth/__init__.py
===================================================================
--- Zope3/trunk/src/zope/app/pluggableauth/__init__.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/pluggableauth/__init__.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -186,60 +186,45 @@
del self[id]
-class PluggableAuthenticationServiceAddSubscriber:
+def PluggableAuthenticationServiceAddSubscriber(self, event):
+ r"""Generates an earmark if one is not provided.
- zope.interface.implements(zope.app.event.interfaces.ISubscriber)
+ Define a stub for PluggableAuthenticationService
- def __init__(self, pluggable_auth_service, event):
- self.pluggable_auth_service = pluggable_auth_service
- self.event = event
+ >>> from zope.app.traversing.interfaces import IPhysicallyLocatable
+ >>> class PluggableAuthStub:
+ ... implements(IPhysicallyLocatable)
+ ... def __init__(self, earmark=None):
+ ... self.earmark = earmark
+ ... def getName(self):
+ ... return 'PluggableAuthName'
- def notify(self, event):
- r"""Generates an earmark if one is not provided.
+ The subscriber generates an earmark for the auth service if one is not
+ set in the init.
- Define a stub for PluggableAuthenticationService
+ >>> stub = PluggableAuthStub()
+ >>> event = ''
+ >>> PluggableAuthenticationServiceAddSubscriber(stub, event)
+ >>> stub.earmark is not None
+ True
- >>> from zope.app.traversing.interfaces \
- ... import IPhysicallyLocatable
- >>> class PluggableAuthStub:
- ... implements(IPhysicallyLocatable)
- ... def __init__(self, earmark=None):
- ... self.earmark = earmark
- ... def getName(self):
- ... return 'PluggableAuthName'
+ The subscriber does not modify an earmark for the auth service if one
+ exists already.
- The subscriber generates an earmark for the auth service if one is not
- set in the init.
-
- >>> stub = PluggableAuthStub()
- >>> event = ''
- >>> subscriber = \
- ... PluggableAuthenticationServiceAddSubscriber(stub,
- ... event)
- >>> subscriber.notify(event)
- >>> stub.earmark is not None
- True
-
- The subscriber does not modify an earmark for the auth service if one
- exists already.
-
- >>> earmark = 'my sample earmark'
- >>> stub = PluggableAuthStub(earmark=earmark)
- >>> event = ''
- >>> subscriber = \
- ... PluggableAuthenticationServiceAddSubscriber(stub, event)
- >>> subscriber.notify(event)
- >>> stub.earmark == earmark
- True
- """
- self = self.pluggable_auth_service
- if self.earmark is None:
- # we manufacture what is intended to be a globally unique
- # earmark if one is not provided in __init__
- myname = zapi.name(self)
- rand_id = gen_key()
- t = int(time.time())
- self.earmark = '%s-%s-%s' % (myname, rand_id, t)
+ >>> earmark = 'my sample earmark'
+ >>> stub = PluggableAuthStub(earmark=earmark)
+ >>> event = ''
+ >>> PluggableAuthenticationServiceAddSubscriber(stub, event)
+ >>> stub.earmark == earmark
+ True
+ """
+ if self.earmark is None:
+ # we manufacture what is intended to be a globally unique
+ # earmark if one is not provided in __init__
+ myname = zapi.name(self)
+ rand_id = gen_key()
+ t = int(time.time())
+ self.earmark = '%s-%s-%s' % (myname, rand_id, t)
class IBTreePrincipalSource(
Modified: Zope3/trunk/src/zope/app/pluggableauth/configure.zcml
===================================================================
--- Zope3/trunk/src/zope/app/pluggableauth/configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/pluggableauth/configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -27,10 +27,9 @@
</content>
<subscriber
- factory=".PluggableAuthenticationServiceAddSubscriber"
for=".interfaces.IPluggableAuthenticationService
zope.app.container.interfaces.IObjectAddedEvent"
- provides="zope.app.event.interfaces.ISubscriber"
+ factory=".PluggableAuthenticationServiceAddSubscriber"
/>
<content class=".BTreePrincipalSource">
Modified: Zope3/trunk/src/zope/app/presentation/configure.zcml
===================================================================
--- Zope3/trunk/src/zope/app/presentation/configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/presentation/configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -32,14 +32,12 @@
factory=".presentation.PageRegistrationAddSubscriber"
for=".presentation.IPageRegistration
zope.app.container.interfaces.IObjectAddedEvent"
- provides="zope.app.event.interfaces.ISubscriber"
/>
<subscriber
factory=".presentation.PageRegistrationRemoveSubscriber"
for=".presentation.IPageRegistration
zope.app.container.interfaces.IObjectRemovedEvent"
- provides="zope.app.event.interfaces.ISubscriber"
/>
<include file="pagefolder.zcml" />
Modified: Zope3/trunk/src/zope/app/presentation/presentation.py
===================================================================
--- Zope3/trunk/src/zope/app/presentation/presentation.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/presentation/presentation.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -23,7 +23,6 @@
from zope.component.presentation import PresentationRegistration
import zope.app.container.contained
-import zope.app.event.interfaces
import zope.app.registration.interfaces
import zope.app.site.interfaces
import zope.app.adapter
@@ -473,37 +472,21 @@
factory = property(factory)
-class PageRegistrationAddSubscriber(object):
- implements(zope.app.event.interfaces.ISubscriber)
+def PageRegistrationAddSubscriber(self, event):
+ if self.template:
+ template = zapi.traverse(self.__parent__.__parent__,self.template)
+ dependents = IDependable(template)
+ objectpath = zapi.getPath(self)
+ dependents.addDependent(objectpath)
- def __init__(self, page_registration, event):
- self.page_registration = page_registration
- self.event = event
-
- def notify(self, event):
- self = self.page_registration
- if self.template:
- template = zapi.traverse(self.__parent__.__parent__,self.template)
- dependents = IDependable(template)
- objectpath = zapi.getPath(self)
- dependents.addDependent(objectpath)
+def PageRegistrationRemoveSubscriber(self, event):
+ if self.template:
+ template = zapi.traverse(self.__parent__.__parent__,self.template)
+ dependents = IDependable(template)
+ objectpath = zapi.getPath(self)
+ dependents.removeDependent(objectpath)
-class PageRegistrationRemoveSubscriber(object):
- implements(zope.app.event.interfaces.ISubscriber)
-
- def __init__(self, page_registration, event):
- self.page_registration = page_registration
- self.event = event
-
- def notify(self, event):
- self = self.page_registration
- if self.template:
- template = zapi.traverse(self.__parent__.__parent__,self.template)
- dependents = IDependable(template)
- objectpath = zapi.getPath(self)
- dependents.removeDependent(objectpath)
-
#XXX can't make new-style class b/c of unpickling error...
class TemplateViewFactory:
Modified: Zope3/trunk/src/zope/app/presentation/tests/test_presentation.py
===================================================================
--- Zope3/trunk/src/zope/app/presentation/tests/test_presentation.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/presentation/tests/test_presentation.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -26,7 +26,6 @@
from zope.app.container.interfaces import IObjectAddedEvent
from zope.app.container.interfaces import IObjectRemovedEvent
-from zope.app.event.interfaces import ISubscriber
from zope.app.folder import rootFolder
from zope.app.presentation.zpt import IZPTTemplate
from zope.app.site.service import ServiceManager
@@ -462,8 +461,8 @@
def test_registerAddSubscriber_template(self):
ztapi.provideAdapter(ILocation, IPhysicallyLocatable,
PhonyPathAdapter)
- ztapi.subscribe((IPageRegistration, IObjectAddedEvent), ISubscriber,
- PageRegistrationAddSubscriber)
+ ztapi.handle((IPageRegistration, IObjectAddedEvent),
+ PageRegistrationAddSubscriber)
registration = PageRegistration(I1, 'test', 'zope.View', "Foo.Bar.A",
template='/++etc++site/default/t')
@@ -475,8 +474,8 @@
def test_registerRemoveSubscriber_template(self):
ztapi.provideAdapter(ILocation, IPhysicallyLocatable,
PhonyPathAdapter)
- ztapi.subscribe((IPageRegistration, IObjectRemovedEvent), ISubscriber,
- PageRegistrationRemoveSubscriber)
+ ztapi.handle((IPageRegistration, IObjectRemovedEvent),
+ PageRegistrationRemoveSubscriber)
registration = PageRegistration(I1, 'test', 'zope.View', "Foo.Bar.A",
template='/++etc++site/default/t')
Modified: Zope3/trunk/src/zope/app/presentation/zpt.py
===================================================================
--- Zope3/trunk/src/zope/app/presentation/zpt.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/presentation/zpt.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -24,7 +24,6 @@
from zope.app.container.contained import Contained
from zope.app.registration.interfaces import IRegisterable
-from zope.app.index.interfaces.text import ISearchableText
from zope.fssync.server.entryadapter import ObjectEntryAdapter, AttrMapping
from zope.fssync.server.interfaces import IObjectFile
from zope.app.filerepresentation.interfaces import IReadFile, IWriteFile
@@ -105,31 +104,6 @@
return self.pt_render(namespace)
-# Adapter for ISearchableText
-
-tag = re.compile(r"<[^>]+>")
-class SearchableText:
-
- implements(ISearchableText)
- __used_for__ = IZPTTemplate
-
- def __init__(self, page):
- self.page = page
-
- def getSearchableText(self):
- text = self.page.source
- if isinstance(text, str):
- text = unicode(self.page.source, 'utf-8')
- # else:
- # text was already Unicode, which happens, but unclear how it
- # gets converted to Unicode since the ZPTPage stores UTF-8 as
- # an 8-bit string.
-
- if self.page.contentType.startswith('text/html'):
- text = tag.sub('', text)
-
- return [text]
-
# Adapters for file-system emulation
class ReadFile:
Modified: Zope3/trunk/src/zope/app/publication/interfaces.py
===================================================================
--- Zope3/trunk/src/zope/app/publication/interfaces.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/publication/interfaces.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -17,9 +17,7 @@
"""
from zope.interface import implements, Interface
-from zope.app.event.interfaces import IEvent
-
class IPublicationRequestFactoryFactory(Interface):
"""Publication request factory factory"""
@@ -47,7 +45,7 @@
"""
-class IBeforeTraverseEvent(IEvent):
+class IBeforeTraverseEvent(Interface):
"""An event which gets sent on publication traverse"""
@@ -59,7 +57,7 @@
self.request = request
-class IEndRequestEvent(IEvent):
+class IEndRequestEvent(Interface):
"""An event which gets sent when the publication is ended"""
Modified: Zope3/trunk/src/zope/app/publication/tests/test_zopepublication.py
===================================================================
--- Zope3/trunk/src/zope/app/publication/tests/test_zopepublication.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/publication/tests/test_zopepublication.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -440,40 +440,29 @@
def testSiteEvents(self):
from zope.app.publication.interfaces import IBeforeTraverseEvent
from zope.app.publication.interfaces import IEndRequestEvent
- from zope.app.event.interfaces import ISubscriber
- from zope.app.servicenames import EventPublication
- from zope.app.event.localservice import EventService
- class Subscriber:
- implements(ISubscriber)
- def __init__(self):
- self.events = []
- def notify(self, event):
- self.events.append(event)
+ set = []
+ clear = []
+ ztapi.handle([IBeforeTraverseEvent], set.append)
+ ztapi.handle([IEndRequestEvent], clear.append)
- events = zapi.getService(EventPublication)
- set = Subscriber()
- clear = Subscriber()
- events.globalSubscribe(set, IBeforeTraverseEvent)
- events.globalSubscribe(clear, IEndRequestEvent)
-
ob = object()
# This should fire the BeforeTraverseEvent
self.publication.callTraversalHooks(self.request, ob)
- self.assertEqual(len(set.events), 1)
- self.assertEqual(len(clear.events), 0)
- self.assertEqual(set.events[0].object, ob)
+ self.assertEqual(len(set), 1)
+ self.assertEqual(len(clear), 0)
+ self.assertEqual(set[0].object, ob)
ob2 = object()
# This should fire the EndRequestEvent
self.publication.endRequest(self.request, ob2)
- self.assertEqual(len(set.events), 1)
- self.assertEqual(len(clear.events), 1)
- self.assertEqual(clear.events[0].object, ob2)
+ self.assertEqual(len(set), 1)
+ self.assertEqual(len(clear), 1)
+ self.assertEqual(clear[0].object, ob2)
def test_suite():
Modified: Zope3/trunk/src/zope/app/publication/zopepublication.py
===================================================================
--- Zope3/trunk/src/zope/app/publication/zopepublication.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/publication/zopepublication.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -46,7 +46,7 @@
from zope.app.publication.publicationtraverse import PublicationTraverse
from zope.app.traversing.interfaces import IPhysicallyLocatable
from zope.app.location import LocationProxy
-from zope.app.event import publish
+from zope.event import notify
from zope.app.publication.interfaces import BeforeTraverseEvent
from zope.app.publication.interfaces import EndRequestEvent
@@ -110,7 +110,7 @@
def callTraversalHooks(self, request, ob):
# Call __before_publishing_traverse__ hooks
- publish(None, BeforeTraverseEvent(ob, request))
+ notify(BeforeTraverseEvent(ob, request))
# This is also a handy place to try and authenticate.
self._maybePlacefullyAuthenticate(request, ob)
@@ -160,7 +160,7 @@
def endRequest(self, request, ob):
endInteraction()
- publish(None, EndRequestEvent(ob, request))
+ notify(EndRequestEvent(ob, request))
def annotateTransaction(self, txn, request, ob):
"""Set some useful meta-information on the transaction. This
Modified: Zope3/trunk/src/zope/app/registration/configure.zcml
===================================================================
--- Zope3/trunk/src/zope/app/registration/configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/registration/configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -41,28 +41,24 @@
<subscriber
factory=".registration.SimpleRegistrationRemoveSubscriber"
- provides="zope.app.event.interfaces.ISubscriber"
for=".interfaces.IRegistration
zope.app.container.interfaces.IObjectRemovedEvent"
/>
<subscriber
factory=".registration.ComponentRegistrationRemoveSubscriber"
- provides="zope.app.event.interfaces.ISubscriber"
for=".interfaces.IComponentRegistration
zope.app.container.interfaces.IObjectRemovedEvent"
/>
<subscriber
factory=".registration.ComponentRegistrationAddSubscriber"
- provides="zope.app.event.interfaces.ISubscriber"
for=".interfaces.IComponentRegistration
zope.app.container.interfaces.IObjectAddedEvent"
/>
<subscriber
factory=".registration.RegistrationManagerRemoveSubscriber"
- provides="zope.app.event.interfaces.ISubscriber"
for=".interfaces.IRegistrationManager
zope.app.container.interfaces.IObjectRemovedEvent"
/>
Modified: Zope3/trunk/src/zope/app/registration/registration.py
===================================================================
--- Zope3/trunk/src/zope/app/registration/registration.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/registration/registration.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -30,7 +30,6 @@
from zope.app.container.contained import Contained
from zope.app.container.contained import setitem, contained, uncontained
from zope.app.dependable.interfaces import IDependable, DependencyError
-from zope.app.event.interfaces import ISubscriber
from zope.app.module.interfaces import IModuleManager
from zope.app.registration import interfaces
@@ -515,27 +514,20 @@
registration.deactivated()
self.__parent__.notifyDeactivated(self, registration)
-class SimpleRegistrationRemoveSubscriber:
+def SimpleRegistrationRemoveSubscriber(registration, event):
+ """Receive notification of remove event."""
+ objectstatus = registration.status
- implements(ISubscriber)
+ if objectstatus == interfaces.ActiveStatus:
+ try:
+ objectpath = zapi.getPath(registration)
+ except: # XXX
+ objectpath = str(registration)
+ raise DependencyError("Can't delete active registration (%s)"
+ % objectpath)
+ elif objectstatus == interfaces.RegisteredStatus:
+ registration.status = interfaces.UnregisteredStatus
- def __init__(self, simple_registration, event):
- self.registration = simple_registration
-
- def notify(self, event):
- """Receive notification of remove event."""
- objectstatus = self.registration.status
-
- if objectstatus == interfaces.ActiveStatus:
- try:
- objectpath = zapi.getPath(self.registration)
- except: # XXX
- objectpath = str(self.registration)
- raise DependencyError("Can't delete active registration (%s)"
- % objectpath)
- elif objectstatus == interfaces.RegisteredStatus:
- self.registration.status = interfaces.UnregisteredStatus
-
class SimpleRegistration(Persistent, Contained):
"""Registration objects that just contain registration data"""
@@ -623,40 +615,28 @@
return component
-class ComponentRegistrationRemoveSubscriber(object):
- implements(ISubscriber)
-
- def __init__(self, component_registration, event):
- self.component_registration = component_registration
+def ComponentRegistrationRemoveSubscriber(component_registration, event):
+ """Receive notification of remove event."""
+ component = component_registration.getComponent()
+ dependents = IDependable(component)
+ objectpath = zapi.getPath(component_registration)
+ dependents.removeDependent(objectpath)
+ # Also update usage, if supported
+ adapter = interfaces.IRegistered(component, None)
+ if adapter is not None:
+ adapter.removeUsage(zapi.getPath(component_registration))
- def notify(self, event):
- """Receive notification of remove event."""
- component = self.component_registration.getComponent()
- dependents = IDependable(component)
- objectpath = zapi.getPath(self.component_registration)
- dependents.removeDependent(objectpath)
- # Also update usage, if supported
- adapter = interfaces.IRegistered(component, None)
- if adapter is not None:
- adapter.removeUsage(zapi.getPath(self.component_registration))
+def ComponentRegistrationAddSubscriber(component_registration, event):
+ """Receive notification of add event."""
+ component = component_registration.getComponent()
+ dependents = IDependable(component)
+ objectpath = zapi.getPath(component_registration)
+ dependents.addDependent(objectpath)
+ # Also update usage, if supported
+ adapter = interfaces.IRegistered(component, None)
+ if adapter is not None:
+ adapter.addUsage(objectpath)
-class ComponentRegistrationAddSubscriber(object):
- implements(ISubscriber)
-
- def __init__(self, component_registration, event):
- self.component_registration = component_registration
-
- def notify(self, event):
- """Receive notification of add event."""
- component = self.component_registration.getComponent()
- dependents = IDependable(component)
- objectpath = zapi.getPath(self.component_registration)
- dependents.addDependent(objectpath)
- # Also update usage, if supported
- adapter = interfaces.IRegistered(component, None)
- if adapter is not None:
- adapter.addUsage(objectpath)
-
from zope.app.dependable import PathSetAnnotation
class Registered(PathSetAnnotation):
@@ -681,17 +661,10 @@
return [zapi.traverse(self.context, path)
for path in self.getPaths()]
-class RegistrationManagerRemoveSubscriber:
- """Subscriber for RegistrationManager remove events."""
- implements(ISubscriber)
-
- def __init__(self, registration_manager, event):
- self.registration_manager = registration_manager
-
- def notify(self, event):
- """Receive notification of remove event."""
- for name in self.registration_manager:
- del self.registration_manager[name]
+def RegistrationManagerRemoveSubscriber(registration_manager, event):
+ """Receive notification of remove event."""
+ for name in registration_manager:
+ del registration_manager[name]
class RegistrationManager(Persistent, Contained):
"""Registration manager
Modified: Zope3/trunk/src/zope/app/registration/tests/test_registrationmanager.py
===================================================================
--- Zope3/trunk/src/zope/app/registration/tests/test_registrationmanager.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/registration/tests/test_registrationmanager.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -18,7 +18,8 @@
from doctest import DocTestSuite
from zope.app.registration.interfaces import IRegistrationManager
from zope.app.registration.registration import RegistrationManager
-from zope.app.registration.registration import RegistrationManagerRemoveSubscriber
+from zope.app.registration.registration \
+ import RegistrationManagerRemoveSubscriber
from zope.app.site.tests import placefulsetup
from zope.app.tests.placelesssetup import PlacelessSetup
from zope.app.traversing.api import traverse
@@ -354,18 +355,17 @@
First create a dummy registration manager with some
initial data.
- >>> regmgr = DummyRM()
- >>> regmgr['foo'] = 'bar'
+ >>> regmgr = DummyRM()
+ >>> regmgr['foo'] = 'bar'
- Create an adapter for it.
- >>> adapter = RegistrationManagerRemoveSubscriber(regmgr, None)
+ Notify:
- Trigger the event.
- >>> adapter.notify(None)
+ >>> RegistrationManagerRemoveSubscriber(regmgr, None)
Check the results.
- >>> regmgr
- {}
+
+ >>> regmgr
+ {}
"""
Modified: Zope3/trunk/src/zope/app/registration/tests/test_registrations.py
===================================================================
--- Zope3/trunk/src/zope/app/registration/tests/test_registrations.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/registration/tests/test_registrations.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -34,7 +34,6 @@
from zope.app.tests import ztapi
from zope.app.registration.interfaces import IRegistration
from zope.app.container.interfaces import IObjectRemovedEvent
-from zope.app.event.interfaces import ISubscriber
from zope.app.registration.registration import \
SimpleRegistrationRemoveSubscriber, \
ComponentRegistrationRemoveSubscriber, \
@@ -82,15 +81,15 @@
def test_RemoveSubscriber(self):
reg = DummyRegistration()
- adapter = SimpleRegistrationRemoveSubscriber(reg, None)
+ reg.status = ActiveStatus
# test that removal fails with Active status
- reg.status = ActiveStatus
- self.assertRaises(DependencyError, adapter.notify, None)
+ self.assertRaises(DependencyError,
+ SimpleRegistrationRemoveSubscriber, reg, None)
# test that removal succeeds with Registered status
reg.status = RegisteredStatus
- adapter.notify(None)
+ SimpleRegistrationRemoveSubscriber(reg, None)
self.assertEquals(reg.status, UnregisteredStatus)
@@ -140,40 +139,43 @@
class TestComponentRegistrationEvents:
def test_addNotify(self):
"""
- First we create a dummy registration and an adapter for it.
+ First we create a dummy registration
- >>> reg = DummyRegistration()
- >>> adapter = ComponentRegistrationAddSubscriber(reg, None)
+ >>> reg = DummyRegistration()
Now call notification
- >>> adapter.notify(None)
+ >>> ComponentRegistrationAddSubscriber(reg, None)
+
Check to make sure the adapter added the path
- >>> reg.dependents()
- ('dummy!',)
+
+ >>> reg.dependents()
+ ('dummy!',)
"""
def test_removeNotify_dependents(self):
"""
- First we create a dummy registration and an adapter for it.
+ First we create a dummy registration
- >>> reg = DummyRegistration()
- >>> adapter = ComponentRegistrationAddSubscriber(reg, None)
+ >>> reg = DummyRegistration()
Now call notification
- >>> adapter.notify(None)
+ >>> ComponentRegistrationAddSubscriber(reg, None)
+
Check to make sure the adapter added the path
- >>> reg.dependents()
- ('dummy!',)
- Now create a removal adapter and call it.
- >>> removal_adapter = ComponentRegistrationRemoveSubscriber(reg, None)
- >>> removal_adapter.notify(None)
+ >>> reg.dependents()
+ ('dummy!',)
+ Now remove notify:
+
+ >>> ComponentRegistrationRemoveSubscriber(reg, None)
+
Check to make sure the adapter removed the dependencie(s).
- >>> reg.dependents()
- ()
+
+ >>> reg.dependents()
+ ()
"""
Modified: Zope3/trunk/src/zope/app/rotterdam/tests/test_xmlnavigationviews.py
===================================================================
--- Zope3/trunk/src/zope/app/rotterdam/tests/test_xmlnavigationviews.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/rotterdam/tests/test_xmlnavigationviews.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -23,20 +23,22 @@
from zope.app.tests import ztapi
from zope.app.traversing.api import traverse
-from zope.app.event.tests.eventsetup import EventSetup
from zope.app.container.interfaces import IReadContainer
from zope.app.rotterdam.tests import util
from zope.app.rotterdam.xmlobject import ReadContainerXmlObjectView
from zope.app.rotterdam.xmlobject import XmlObjectView
+from zope.app.site.tests.placefulsetup import PlacefulSetup
+
class File:
pass
-class TestXmlObject(EventSetup, TestCase):
+class TestXmlObject(PlacefulSetup, TestCase):
def setUp(self):
- super(TestXmlObject, self).setUp()
+ PlacefulSetup.setUp(self, site=True)
+ self.createStandardServices()
def testXMLTreeViews(self):
rcxov = ReadContainerXmlObjectView
Modified: Zope3/trunk/src/zope/app/server/main.py
===================================================================
--- Zope3/trunk/src/zope/app/server/main.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/server/main.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -26,7 +26,7 @@
import ThreadedAsync
import zope.app.appsetup
-from zope.app.event import publish
+from zope.event import notify
from zope.server.taskthreads import ThreadedTaskDispatcher
CONFIG_FILENAME = "zope.conf"
@@ -89,7 +89,7 @@
db = options.database.open()
- publish(None, zope.app.appsetup.DatabaseOpened(db))
+ notify(zope.app.appsetup.DatabaseOpened(db))
task_dispatcher = ThreadedTaskDispatcher()
task_dispatcher.setThreadCount(options.threads)
@@ -97,4 +97,4 @@
for server in options.servers:
server.create(task_dispatcher, db)
- publish(None, zope.app.appsetup.ProcessStarting())
+ notify(zope.app.appsetup.ProcessStarting())
Modified: Zope3/trunk/src/zope/app/servicenames.py
===================================================================
--- Zope3/trunk/src/zope/app/servicenames.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/servicenames.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,3 +1,4 @@
+
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
@@ -22,8 +23,5 @@
Authentication = 'Authentication'
BrowserMenu = 'BrowserMenu'
-EventPublication = 'EventPublication'
-EventSubscription = 'Subscription'
ErrorLogging = 'ErrorLogging'
-HubIds = 'HubIds'
PrincipalAnnotation = 'PrincipalAnnotation'
Modified: Zope3/trunk/src/zope/app/site/browser/tests/test_services.py
===================================================================
--- Zope3/trunk/src/zope/app/site/browser/tests/test_services.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/site/browser/tests/test_services.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -43,8 +43,6 @@
expected = [{'url': '', 'disabled': False, 'manageable': False,
'name': 'Adapters', 'parent': u'global'},
{'url': '', 'disabled': False, 'manageable': False,
- 'name': 'EventPublication', 'parent': u'global'},
- {'url': '', 'disabled': False, 'manageable': False,
'name': 'Presentation', 'parent': u'global'},
{'url': '', 'disabled': False, 'manageable': False,
'name': 'Services', 'parent': u'global'},
Modified: Zope3/trunk/src/zope/app/site/service.py
===================================================================
--- Zope3/trunk/src/zope/app/site/service.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/site/service.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -41,7 +41,6 @@
from zope.app.container.constraints import ItemTypePrecondition
from zope.app.container.contained import Contained
from zope.app.container.interfaces import IContainer
-from zope.app.event.function import Subscriber
from zope.app.registration.interfaces import IRegistry
from zope.app.traversing.interfaces import IContainmentRoot
from zope.app.traversing.api import getPath
Modified: Zope3/trunk/src/zope/app/site/tests/placefulsetup.py
===================================================================
--- Zope3/trunk/src/zope/app/site/tests/placefulsetup.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/site/tests/placefulsetup.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -75,14 +75,7 @@
def createRootFolder(self):
self.rootFolder = rootFolder()
- # The following is a hook that some base classes might want to override.
- def getObjectHub(self):
- from zope.app.hub import ObjectHub
- return ObjectHub()
-
def createStandardServices(self):
'''Create a bunch of standard placeful services'''
- setup.createStandardServices(self.rootFolder,
- hubids=self.getObjectHub())
-
+ setup.createStandardServices(self.rootFolder)
Modified: Zope3/trunk/src/zope/app/tests/setup.py
===================================================================
--- Zope3/trunk/src/zope/app/tests/setup.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/tests/setup.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -182,36 +182,11 @@
zapi.traverse(default.getRegistrationManager(), key).status = ActiveStatus
return zapi.traverse(servicemanager, path)
-from zope.app.hub.interfaces import IObjectHub
-from zope.app.event.interfaces import ISubscriptionService
-from zope.app.event.localservice import EventService
-from zope.app.hub import ObjectHub
-from zope.app.utility import LocalUtilityService
-from zope.app.servicenames import HubIds, Utilities
-from zope.app.servicenames import EventPublication, EventSubscription
-def createStandardServices(folder, hubids=None):
+def createStandardServices(folder):
'''Create a bunch of standard placeful services
- Well, uh, 3
+ Well, uh, 0
'''
sm = createServiceManager(folder)
- defineService = zapi.getGlobalServices().defineService
- defineService(EventSubscription, ISubscriptionService)
- # EventPublication service already defined by
- # zope.app.events.tests.PlacelessSetup
-
- defineService(HubIds, IObjectHub)
-
- # EventService must be IAttributeAnnotatable so that it can support
- # dependencies.
- classImplements(EventService, IAttributeAnnotatable)
- events = EventService()
- addService(sm, EventPublication, events)
- addService(sm, EventSubscription, events, suffix='sub')
- if hubids is None:
- hubids = ObjectHub()
-
- addService(sm, HubIds, hubids)
-
Modified: Zope3/trunk/src/zope/app/tests/ztapi.py
===================================================================
--- Zope3/trunk/src/zope/app/tests/ztapi.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/tests/ztapi.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -74,6 +74,9 @@
s = zapi.getGlobalServices().getService(Adapters)
s.subscribe(required, provided, factory)
+def handle(required, handler):
+ subscribe(required, None, handler)
+
def provideUtility(provided, component, name=''):
s = zapi.getGlobalServices().getService(Utilities)
s.provideUtility(provided, component, name)
Modified: Zope3/trunk/src/zope/app/undo/__init__.py
===================================================================
--- Zope3/trunk/src/zope/app/undo/__init__.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/undo/__init__.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -19,7 +19,6 @@
from zope.exceptions import NotFoundError
from zope.app import zapi
-from zope.app.event import function
from zope.app.undo.interfaces import IUndoManager, UndoError
from zope.app.servicenames import Utilities
from zope.app.traversing.interfaces import IPhysicallyLocatable
@@ -31,8 +30,6 @@
svc = zapi.getGlobalService(Utilities)
svc.provideUtility(IUndoManager, ZODBUndoManager(event.database))
-undoSetup = function.Subscriber(undoSetup)
-
class Prefix(str):
"""A prefix is equal to any string it is a prefix of.
Modified: Zope3/trunk/src/zope/app/undo/configure.zcml
===================================================================
--- Zope3/trunk/src/zope/app/undo/configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/undo/configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,7 +1,6 @@
<configure
xmlns="http://namespaces.zope.org/zope"
xmlns:browser="http://namespaces.zope.org/browser"
- xmlns:event="http://namespaces.zope.org/event"
i18n_domain="zope"
>
@@ -20,9 +19,9 @@
/>
- <event:subscribe
- subscriber=".undoSetup"
- event_types="zope.app.appsetup.IDatabaseOpenedEvent"
+ <subscriber
+ factory=".undoSetup"
+ for="zope.app.appsetup.IDatabaseOpenedEvent"
/>
Modified: Zope3/trunk/src/zope/app/wiki/browser/wiki.py
===================================================================
--- Zope3/trunk/src/zope/app/wiki/browser/wiki.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/wiki/browser/wiki.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -20,10 +20,8 @@
from zope.app import zapi
from zope.app.dublincore.interfaces import ICMFDublinCore
-from zope.app.servicenames import HubIds
from zope.app.traversing.api import getName, getPath
from zope.app.container.browser.adding import Adding
-from zope.app.hub import Registration
from zope.app.wiki.interfaces import IWikiPageHierarchy
@@ -32,15 +30,6 @@
def createAndAdd(self, data):
content = super(AddWiki, self).createAndAdd(data)
- if self.request.get('textindex'):
- # Get the environment
- sm = zapi.getServices()
- pkg = sm['default']
- # Create, subscribe and add a Registration object.
- if 'WikiReg' not in pkg:
- reg = Registration()
- pkg['WikiReg'] = reg
- reg.subscribe()
if self.request.get('frontpage'):
page = removeAllProxies(
Modified: Zope3/trunk/src/zope/app/wiki/configure.zcml
===================================================================
--- Zope3/trunk/src/zope/app/wiki/configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/wiki/configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,6 +1,5 @@
<configure
xmlns="http://namespaces.zope.org/zope"
- xmlns:event="http://namespaces.zope.org/event"
xmlns:mail="http://namespaces.zope.org/mail"
i18n_domain="zope"
>
@@ -206,13 +205,14 @@
mailer="wiki-smtp" />
<!-- Register event listener for change mails -->
- <event:subscribe
- subscriber=".wikipage.mailer"
- event_types="zope.app.container.interfaces.IObjectAddedEvent
- zope.app.event.interfaces.IObjectModifiedEvent
- zope.app.container.interfaces.IObjectRemovedEvent
- zope.app.container.interfaces.IObjectMovedEvent"
+ <subscriber
+ factory=".wikipage.mailer"
+ for="zope.app.container.interfaces.IObjectMovedEvent"
/>
+ <subscriber
+ factory=".wikipage.mailer"
+ for="zope.app.event.interfaces.IObjectModifiedEvent"
+ />
<!-- Register various browser related components, including all views -->
Modified: Zope3/trunk/src/zope/app/wiki/tests/test_wikimail.py
===================================================================
--- Zope3/trunk/src/zope/app/wiki/tests/test_wikimail.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/wiki/tests/test_wikimail.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -22,7 +22,6 @@
from zope.app.tests.placelesssetup import PlacelessSetup
from zope.app.site.tests.placefulsetup import PlacefulSetup
from zope.app.annotation.interfaces import IAnnotations, IAttributeAnnotatable
-from zope.app.event.interfaces import ISubscriber
from zope.app.event.objectevent import ObjectModifiedEvent
from zope.app.annotation.attribute import AttributeAnnotations
from zope.app.mail.interfaces import IMailDelivery
@@ -129,9 +128,6 @@
ztapi.provideUtility(IMailDelivery, delivery,
name='wiki-delivery')
- def test_Interface(self):
- self.failUnless(ISubscriber.providedBy(mailer))
-
def test_getAllSubscribers(self):
wiki = Wiki()
wiki_sub = MailSubscriptions(wiki)
@@ -155,7 +151,7 @@
wiki['page1'] = page
page.source = 'Hello World!'
event = ObjectModifiedEvent(page)
- mailer.notify(event)
+ mailer(event)
self.assertEqual('wiki at zope3.org',
mail_result[0][0])
self.assertEqual(('blah at bar.com', 'foo at bar.com'), mail_result[0][1])
Modified: Zope3/trunk/src/zope/app/wiki/wikipage.py
===================================================================
--- Zope3/trunk/src/zope/app/wiki/wikipage.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/wiki/wikipage.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -25,7 +25,7 @@
from zope.app.dublincore.interfaces import ICMFDublinCore
from zope.app.filerepresentation.interfaces import IReadFile, IWriteFile
from zope.app.annotation.interfaces import IAnnotations
-from zope.app.event.interfaces import ISubscriber, IObjectModifiedEvent
+from zope.app.event.interfaces import IObjectModifiedEvent
from zope.app.container.interfaces import \
IObjectAddedEvent, IObjectRemovedEvent, IObjectMovedEvent
from zope.app.mail.interfaces import IMailDelivery
@@ -208,15 +208,13 @@
class WikiMailer:
"""Class to handle all outgoing mail."""
- implements(ISubscriber)
-
def __init__(self, host="localhost", port="25"):
"""Initialize the the object."""
self.host = host
self.port = port
- def notify(self, event):
- """See zope.app.event.interfaces.ISubscriber"""
+ def __call__(self, event):
+ # XXX event handling should be separated from mailing
if IWikiPage.providedBy(event.object):
if IObjectAddedEvent.providedBy(event):
self.handleAdded(event.object)
Modified: Zope3/trunk/src/zope/app/workflow/interfaces/__init__.py
===================================================================
--- Zope3/trunk/src/zope/app/workflow/interfaces/__init__.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/workflow/interfaces/__init__.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -18,10 +18,9 @@
from zope.interface import Interface, Attribute
from zope.app.i18n import ZopeMessageIDFactory as _
from zope.app.container.interfaces import IContainer
-from zope.app.event.interfaces import IEvent
-class IWorkflowEvent(IEvent):
+class IWorkflowEvent(Interface):
"""This event describes a generic event that is triggered by the workflow
mechanism."""
Modified: Zope3/trunk/src/zope/app/workflow/stateful/configure.zcml
===================================================================
--- Zope3/trunk/src/zope/app/workflow/stateful/configure.zcml 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/workflow/stateful/configure.zcml 2004-05-27 13:00:48 UTC (rev 25041)
@@ -130,7 +130,6 @@
<subscriber
for="..interfaces.IProcessInstanceContainerAdaptable
zope.app.event.objectevent.IObjectCreatedEvent"
- provides="zope.app.event.interfaces.ISubscriber"
factory=".contentworkflow.NewObjectProcessInstanceCreator"
>
Modified: Zope3/trunk/src/zope/app/workflow/stateful/contentworkflow.py
===================================================================
--- Zope3/trunk/src/zope/app/workflow/stateful/contentworkflow.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/workflow/stateful/contentworkflow.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -21,9 +21,8 @@
from persistent.dict import PersistentDict
from zope.app import zapi
-from zope.app.event.interfaces import ISubscriber
from zope.app.event.interfaces import IObjectCreatedEvent
-from zope.app.servicenames import EventSubscription, Utilities
+from zope.app.servicenames import Utilities
from zope.app.workflow.interfaces import IProcessInstanceContainer
from zope.app.workflow.interfaces import IProcessInstanceContainerAdaptable
@@ -33,41 +32,29 @@
from zope.app.container.contained import Contained
-class NewObjectProcessInstanceCreator(object):
- implements(ISubscriber)
-
- __used_for__ = (IProcessInstanceContainerAdaptable, IObjectCreatedEvent)
+def NewObjectProcessInstanceCreator(obj, event):
+ # used for: IProcessInstanceContainerAdaptable, IObjectCreatedEvent
- __slots__ = ('event', )
+ pi_container = IProcessInstanceContainer(obj)
- def __init__(self, obj, event):
- self.event = event
+ for (ignored, cwf) in zapi.getUtilitiesFor(IContentWorkflowsManager):
+ # here we will lookup the configured processdefinitions
+ # for the newly created compoent. For every pd_name
+ # returned we will create a processinstance.
- def notify(self, ignored_event):
- """See zope.app.event.interfaces.ISubscriber"""
- event = self.event
- obj = event.object
+ # Note that we use getUtilitiesFor rather than getAllUtilitiesFor
+ # so that we don't use overridden content-workflow managers.
- pi_container = IProcessInstanceContainer(obj)
+ for pd_name in cwf.getProcessDefinitionNamesForObject(obj):
- for (ignored, cwf) in zapi.getUtilitiesFor(IContentWorkflowsManager):
- # here we will lookup the configured processdefinitions
- # for the newly created compoent. For every pd_name
- # returned we will create a processinstance.
-
- # Note that we use getUtilitiesFor rather than getAllUtilitiesFor
- # so that we don't use overridden content-workflow managers.
-
- for pd_name in cwf.getProcessDefinitionNamesForObject(obj):
-
- if pd_name in pi_container.keys():
- continue
- try:
- pi = createProcessInstance(cwf, pd_name)
- except KeyError:
- # No registered PD with that name..
- continue
- pi_container[pd_name] = pi
+ if pd_name in pi_container.keys():
+ continue
+ try:
+ pi = createProcessInstance(cwf, pd_name)
+ except KeyError:
+ # No registered PD with that name..
+ continue
+ pi_container[pd_name] = pi
class ContentWorkflowsManager(Persistent, Contained):
Modified: Zope3/trunk/src/zope/app/workflow/stateful/definition.py
===================================================================
--- Zope3/trunk/src/zope/app/workflow/stateful/definition.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/workflow/stateful/definition.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -24,7 +24,7 @@
from zope.app.container.interfaces import IReadContainer
from zope.app.container.contained import Contained, containedEvent
-from zope.app.event import publish
+from zope.event import notify
from zope.app.event.objectevent import ObjectEvent, modified
from zope.app.workflow.definition import ProcessDefinition
from zope.app.workflow.definition import ProcessDefinitionElementContainer
@@ -118,7 +118,7 @@
def _publishModified(self, name, object):
object, event = containedEvent(object, self, name)
if event:
- publish(self, event)
+ notify(event)
modified(self)
def getRelevantDataSchema(self):
Modified: Zope3/trunk/src/zope/app/workflow/stateful/instance.py
===================================================================
--- Zope3/trunk/src/zope/app/workflow/stateful/instance.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/workflow/stateful/instance.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -19,7 +19,7 @@
from persistent.dict import PersistentDict
from zope.app import zapi
-from zope.app.event import publish
+from zope.event import notify
from zope.app.workflow.interfaces import IProcessDefinition
from zope.app.workflow.stateful.interfaces import AUTOMATIC
from zope.app.workflow.stateful.interfaces import IAfterTransitionEvent
@@ -125,14 +125,14 @@
process = self.__parent__
# Send an Event before RelevantData changes
oldvalue = getattr(self, key, None)
- publish(self, BeforeRelevantDataChangeEvent(
+ notify(BeforeRelevantDataChangeEvent(
process, self.__schema, key, oldvalue, value))
super(RelevantData, self).__setattr__(key, value)
if is_schema_field:
# Send an Event after RelevantData has changed
- publish(self, AfterRelevantDataChangeEvent(
+ notify(AfterRelevantDataChangeEvent(
process, self.__schema, key, oldvalue, value))
def getChecker(self):
@@ -204,13 +204,13 @@
obj = getParent(self)
# Send an event before the transition occurs.
- publish(self, BeforeTransitionEvent(obj, self, transition))
+ notify(BeforeTransitionEvent(obj, self, transition))
# change status
self._status = transition.destinationState
# Send an event after the transition occured.
- publish(self, AfterTransitionEvent(obj, self, transition))
+ notify(AfterTransitionEvent(obj, self, transition))
# check for automatic transitions and fire them if necessary
self._checkAndFireAuto(clean_pd)
Modified: Zope3/trunk/src/zope/app/workflow/stateful/tests/test_contentworkflow.py
===================================================================
--- Zope3/trunk/src/zope/app/workflow/stateful/tests/test_contentworkflow.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/workflow/stateful/tests/test_contentworkflow.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -24,10 +24,8 @@
from zope.app.annotation.interfaces import IAttributeAnnotatable
from zope.app.container.contained import Contained
from zope.app.event.objectevent import ObjectCreatedEvent
-from zope.app.event.tests.placelesssetup import eventPublisher, EventRecorder
-from zope.app.event.tests.placelesssetup import clearEvents
from zope.app.annotation.interfaces import IAnnotatable, IAttributeAnnotatable
-from zope.app.event.interfaces import IObjectCreatedEvent, ISubscriber
+from zope.app.event.interfaces import IObjectCreatedEvent
from zope.app.utility import UtilityRegistration
from zope.app.utility.interfaces import ILocalUtility
from zope.app.registration.interfaces import ActiveStatus
@@ -161,8 +159,7 @@
obj = TestObject2()
event = ObjectCreatedEvent(obj)
- subscriber = NewObjectProcessInstanceCreator(obj, event)
- subscriber.notify(event)
+ NewObjectProcessInstanceCreator(obj, event)
pi = obj.__annotations__['zope.app.worfklow.ProcessInstanceContainer']
self.assertEqual(pi.keys(), ['definition2', 'definition1'])
Modified: Zope3/trunk/src/zope/app/workflow/stateful/tests/test_instance.py
===================================================================
--- Zope3/trunk/src/zope/app/workflow/stateful/tests/test_instance.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/workflow/stateful/tests/test_instance.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -22,7 +22,6 @@
from zope.schema import Text, Int
from zope.component.service import serviceManager
-from zope.app.event.tests.placelesssetup import eventPublisher, EventRecorder
from zope.app.event.tests.placelesssetup import events, clearEvents
from zope.app.security.interfaces import IPermission
from zope.app.security.permission import Permission
@@ -114,7 +113,6 @@
self.pi = createProcessInstance(self.sm, 'definition1')
# Let's also listen to the fired events
clearEvents()
- eventPublisher.globalSubscribe(EventRecorder)
def testInterface(self):
Modified: Zope3/trunk/src/zope/app/workflow/tests/workflowsetup.py
===================================================================
--- Zope3/trunk/src/zope/app/workflow/tests/workflowsetup.py 2004-05-27 04:15:38 UTC (rev 25040)
+++ Zope3/trunk/src/zope/app/workflow/tests/workflowsetup.py 2004-05-27 13:00:48 UTC (rev 25041)
@@ -1,4 +1,4 @@
-##############################################################################
+ ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
More information about the Zope3-Checkins
mailing list