Esempio n. 1
0
 def testSetUp(self):
     super(TestLayer, self).testSetUp()
     # Because it is difficult to dynamically register a
     # entry_point in tests, we do the setup by hand:
     resource_factory = create_factory(foo)
     getGlobalSiteManager().registerAdapter(
         resource_factory, (IBrowserRequest,), Interface, foo.name)
Esempio n. 2
0
 def test_behavior_default_page_layout(self):
     import os.path
     
     from zope.component import provideUtility
     from zope.component import getGlobalSiteManager
     
     from plone.resource.directory import FilesystemResourceDirectory
     from plone.resource.interfaces import IResourceDirectory
     
     from plone.app.blocks.layoutbehavior import ILayoutAware
     
     basePath = os.path.dirname(__file__)
     resourcePath = os.path.join(basePath, 'resources', 'pagelayout', 'default')
     
     resourceDir = FilesystemResourceDirectory(resourcePath)
     provideUtility(resourceDir, provides=IResourceDirectory, name=u'++pagelayout++default')
     
     self.layer['folder'].invokeFactory('page', 'dp')
     
     obj = self.layer['folder']['dp']
     layout = ILayoutAware(obj)
     
     self.assertEqual(layout.content, u"<div>a page</div>")
     self.assertEqual(layout.pageSiteLayout, None)
     self.assertEqual(layout.sectionSiteLayout, None)
     
     getGlobalSiteManager().unregisterUtility(resourceDir,
             provided=IResourceDirectory,
             name=u'++pagelayout++default',
         )
     
Esempio n. 3
0
def getCrowdsUtility():
    """Helper - returns crowds utility and registers new one if missing."""
    utility = queryUtility(ICrowdsUtility)
    if not utility:
        utility = CrowdsUtility()
        getGlobalSiteManager().registerUtility(utility, ICrowdsUtility)
    return utility
Esempio n. 4
0
 def _registerTraversable(self):
     from zope.component import getGlobalSiteManager
     from zope.interface import Interface
     from zope.traversing.interfaces import ITraversable
     from zope.traversing.adapters import DefaultTraversable
     getGlobalSiteManager().registerAdapter(
         DefaultTraversable, [Interface], ITraversable)
    def testObject_pasteUncommitOnException(self):
        """Ensure that pasted objects aren't commited if an IObjectMovedEvent raises an exception.
        See https://dev.plone.org/ticket/9365
        """
        # register event handler
        provideHandler(failingEventHandler, [IContentish, IObjectMovedEvent])
        try:
            browser = self.getBrowser()
            browser.open(self.folder['source-folder']['doc'].absolute_url())
            browser.getLink('Cut').click()
            browser.open(self.folder['destination-folder'].absolute_url())
            try:
                browser.getLink('Paste').click()
            except HTTPError:
                # a HTTP 500 Server error is currently expected,
                # unless we find a better way to abort the
                # transaction.
                pass

            # test if document is not moved
            self.assertTrue('doc' in self.folder['source-folder'])
            self.assertFalse('doc' in self.folder['destination-folder'])

        finally:
            # unregister event handler
            getGlobalSiteManager().unregisterHandler(
                failingEventHandler, [IContentish, IObjectMovedEvent])
Esempio n. 6
0
 def setUp(self):
     from Products.Reflecto.catalog import \
         FileProxyIndexableContentAdapter
     self.reflector = MockReflector()
     provideAdapter(FileProxyIndexableContentAdapter) 
     getGlobalSiteManager().registerUtility(FakeConverter, IConverter,
             'image/jpeg')
 def testFacetDependencies(self):
     cfg = SolrConnectionConfig()
     provideUtility(cfg, ISolrConnectionConfig)
     # dependency info can be set via the configuration utility...
     cfg.facets = ['foo:bar']
     context = Dummy()
     request = {}
     view = DummyView(context, request)
     self.assertEqual(facetParameters(view),
                      (['foo:bar'], dict(foo=['bar'])))
     # overridden on the context
     context.facet_fields = ['bar:foo']
     self.assertEqual(facetParameters(view),
                      (['bar:foo'], dict(bar=['foo'])))
     # and via the request
     request['facet.field'] = ['foo:bar', 'bar:foo']
     self.assertEqual(
         facetParameters(view),
         (['foo:bar', 'bar:foo'], dict(foo=['bar'], bar=['foo']))
     )
     # white space shouldn't matter
     request['facet.field'] = ['foo : bar', 'bar  :foo']
     self.assertEqual(
         facetParameters(view),
         (['foo : bar', 'bar  :foo'], dict(foo=['bar'], bar=['foo']))
     )
     # clean up...
     getGlobalSiteManager().unregisterUtility(cfg, ISolrConnectionConfig)
Esempio n. 8
0
 def test_getSiteManager(self):
     self.assertEqual(getSiteManager(None), getGlobalSiteManager())
     self.assertEqual(getSiteManager(self.root), getGlobalSiteManager())
     self.assertEqual(getSiteManager(self.f1), self.sm1)
     self.assertEqual(getSiteManager(self.f2), self.sm2)
     setSite(self.f2)
     self.assertEqual(getSiteManager(None), self.sm2)
Esempio n. 9
0
    def setUp(self):
        self.etree = etreeSetup(key = "py25")
        component.getGlobalSiteManager().registerAdapter(
            widgets.TextDAVWidget,
            (zope.schema.interfaces.ITextLine,
             z3c.dav.interfaces.IWebDAVRequest))

        foofield = schema.List(__name__ = self.name,
                               title = u"Foo Title",
                               description = u"Foo field",
                               value_type = schema.TextLine(
                                   __name__ = "name",
                                   title = u"Foo Title",
                                   description = u"Foo field"))

        class IDemoContent(Interface):
            foo = foofield

        class DemoContent(object):
            implements(IDemoContent)

        self.field_content = [u"firstitem", u"seconditem"]
        self.content = DemoContent()
        field = IDemoContent['foo']
        self.field = field.bind(self.content)
        self.setUpWidget()
Esempio n. 10
0
    def test_query(self):
        from zope.site import SiteManagerAdapter
        from zope import component
        component.provideAdapter(SiteManagerAdapter)
        top_site = SiteManagerContainer()
        top_sm = LocalSiteManager(top_site)
        top_site.setSiteManager(top_sm)
        assert_that(top_sm.__parent__, is_(top_site))
        assert_that(top_site, provides(ISite))
        interface.alsoProvides(top_site, ILocationInfo)

        child_site = SiteManagerContainer()
        child_site.__parent__ = top_site
        child_site.getParent = lambda: child_site.__parent__
        interface.alsoProvides(child_site, ILocationInfo)
        child_sm = LocalSiteManager(child_site)
        child_site.setSiteManager(child_sm)

        assert_that(child_sm.__bases__, is_((top_sm,)))


        class IFoo(Interface):
            pass

        @interface.implementer(IFoo)
        class Foo(Contained):
            pass

        child_foo = Foo()
        top_foo = Foo()

        child_foo.__parent__ = child_site
        top_foo.__parent__ = top_site

        top_sm.registerUtility(top_foo, IFoo)
        child_sm.registerUtility(child_foo, IFoo)

        child_foo.__conform__ = lambda self, _:  child_sm
        from zope import component
        component.getSiteManager(child_foo)


        x = queryNextUtility(child_foo, IFoo)
        assert_that(x, is_(top_foo))

        class IBaz(Interface): pass

        x = queryNextUtility(child_foo, IBaz)
        assert_that(x, is_(none()))

        x = queryNextUtility(top_foo, IFoo)
        assert_that(x, is_(none()))

        x = queryNextUtility(component.getGlobalSiteManager(), IFoo)
        assert_that(x, is_(none()))

        global_foo = Foo()
        component.provideUtility(global_foo, IFoo)
        x = queryNextUtility(component.getGlobalSiteManager(), IFoo)
        assert_that(x, is_(global_foo))
Esempio n. 11
0
    def setUp(self):
        self.etree = etreeSetup(key = "py25")

        foofield = schema.Object(__name__ = self.name,
                                 title = u"Foo Title",
                                 description = u"Foo field",
                                 schema = ISimpleInterface)
        class IDemoContent(Interface):
            foo = foofield

        class DemoContent(object):
            implements(IDemoContent)

        self.field_content = SimpleObject(name = u"Michael Kerrin",
                                          age = 26)
        self.content = DemoContent()
        field = IDemoContent['foo']
        self.field = field.bind(self.content)
        self.setUpWidget()

        component.getGlobalSiteManager().registerAdapter(
            widgets.TextDAVWidget,
            (zope.schema.interfaces.ITextLine,
             z3c.dav.interfaces.IWebDAVRequest))
        component.getGlobalSiteManager().registerAdapter(
            widgets.IntDAVWidget,
            (zope.schema.interfaces.IInt,
             z3c.dav.interfaces.IWebDAVRequest))
Esempio n. 12
0
def getDescriptionUtility():
    """Helper - returns crowd description utility and registers
    a new one if missing.
    """
    utility = queryUtility(IDescriptionUtility)
    if not utility:
        utility = DescriptionUtility()
        getGlobalSiteManager().registerUtility(utility, IDescriptionUtility)
    return utility
Esempio n. 13
0
 def tearDown(self):
     # unregister IRedisStoreConfig utils, if they are registered.
     for name in ("psj.content.redis-GND", "psj.content.redis_conf"):
         util = queryUtility(IRedisStoreConfig, name=name)
         if util is None:
             continue
         getGlobalSiteManager().unregisterUtility(
             util, provided=IRedisStoreConfig, name=name)
     super(MetadataBehaviorsTests, self).tearDown()
 def setUp(self):
     super(BrowserTestCase, self).setUp()
     self._testapp = TestApp(self.layer.make_wsgi_app())
     # Typically this would be done by zope.app.principalannotation's
     # bootstrap.zcml but we don't have a dep on that.
     from zope.principalannotation.utility import PrincipalAnnotationUtility
     from zope.principalannotation.interfaces import IPrincipalAnnotationUtility
     component.getGlobalSiteManager().registerUtility(PrincipalAnnotationUtility(),
                                                      IPrincipalAnnotationUtility)
Esempio n. 15
0
    def __init__(self, paster_variables):
        setHooks()

        self.paster = toargs(self, IPasterVariables, paster_variables)

        getGlobalSiteManager().registerUtility(provided=IConfiguration,
            component=self)
        
        load_configuration(self.paster['configure_zcml'])
 def setUp(self):
     # Typically this would be done by zope.app.principalannotation's
     # bootstrap.zcml but we don't have a dep on that.
     super(_AppComponentBrowserLayer, self).setUp()
     from zope.principalannotation.utility import PrincipalAnnotationUtility
     from zope.principalannotation.interfaces import IPrincipalAnnotationUtility
     from zope import component
     component.getGlobalSiteManager().registerUtility(PrincipalAnnotationUtility(),
                                                      IPrincipalAnnotationUtility)
Esempio n. 17
0
def getReportRegistrationUtility():
    """Helper - returns report registration utility and registers a new one
    if missing."""
    utility = queryUtility(IRegisteredReportsUtility)
    if not utility:
        utility = RegisteredReportsUtility()
        getGlobalSiteManager().registerUtility(utility,
            IRegisteredReportsUtility)
    return utility
    def test_FileResource_GET_works_without_IETag_adapter(self):
        # Test backwards compatibility with users of <3.11 that do not provide an ETagAdatper

        getGlobalSiteManager().unregisterAdapter(MyETag)
        factory = FileResourceFactory(self.testFilePath, self.nullChecker, 'test.txt')
        request = TestRequest()
        resource = factory(request)
        self.assertTrue(resource.GET())
        self.assertIsNone(request.response.getHeader('ETag'))
Esempio n. 19
0
def setUp( test ):
    _setUp( test )
    from ore.contentmirror import interfaces
    from mirror.async import operation, interfaces as async_interfaces
    
    component.getGlobalSiteManager().unregisterUtility( provided=interfaces.IOperationBufferFactory )
    component.provideUtility( operation.AsyncOperationBufferFactory() )
    component.provideAdapter( operation.OperationIO, ( interfaces.IOperation, ), async_interfaces.IOperationSerializer)
    component.provideUtility( operation.OperationIO(), async_interfaces.IOperationLoader )
Esempio n. 20
0
 def testVetoRegisteredForOtherType(self):
     self.createContent()
     provideAdapter(factory=Veto, name="euphorie.solution")
     try:
         fti = getattr(self.portal.portal_types, "euphorie.module")
         self.assertEqual(fti.isConstructionAllowed(self.module), True)
     finally:
         from zope.component import getGlobalSiteManager
         getGlobalSiteManager().unregisterAdapter(
                 Veto, name="euphorie.solution")
Esempio n. 21
0
 def tearDownPackages(cls):
     """
     Tear down all configured packages in the global site manager.
     """
     # This is a duplicate of zope.component.globalregistry
     logger.info('Tearing down packages %s for layer %s', cls.set_up_packages, cls)
     gc.collect()
     component.getGlobalSiteManager().__init__('base')
     gc.collect()
     cls.configuration_context = None
Esempio n. 22
0
def get_graph():
    """ returns the graph database connection object
    """
    global_registry = component.getGlobalSiteManager()
    graph = global_registry.queryUtility(IGraph)
    if not graph:
        global_registry = component.getGlobalSiteManager()
        graph = graph_factory()
        global_registry.registerUtility(graph)
    return graph
Esempio n. 23
0
 def tearDown(self):
     component.getGlobalSiteManager().unregisterAdapter(
         widgets.TextDAVWidget,
         (zope.schema.interfaces.ITextLine,
          z3c.dav.interfaces.IWebDAVRequest))
     component.getGlobalSiteManager().unregisterAdapter(
         widgets.IntDAVWidget,
         (zope.schema.interfaces.IInt,
          z3c.dav.interfaces.IWebDAVRequest))
     super(ObjectDAVWidgetTest, self).tearDown()
Esempio n. 24
0
 def test_missing_jar_path_causes_converter_to_raise(self):
     # Since the path is configured in the IZCMLTikaConfig from the ZCML
     # loaded in the testing layer, we need to unregister the config for
     # this test to verify the exception.
     config = getUtility(IZCMLTikaConfig)
     getGlobalSiteManager().unregisterUtility(provided=IZCMLTikaConfig)
     try:
         with self.assertRaises(TikaJarNotConfigured):
             TikaConverter().convert('')
     finally:
         getGlobalSiteManager().registerUtility(component=config)
Esempio n. 25
0
def view_registered(factory, name, required=(Interface, Interface)):
    options = dict(
        factory=factory,
        required=required,
        provided=IBrowserView,
        name=name,
    )
    getGlobalSiteManager().registerAdapter(**options)
    try:
        yield
    finally:
        getGlobalSiteManager().unregisterAdapter(**options)
Esempio n. 26
0
    def setUp(self):
        super(TestGenerator, self).setUp()
        getGlobalSiteManager().registerUtility(
            factory=DefaultPermissionCollector,
            provided=IPermissionCollector)

        # The IActionGroupRegistry utility registration is lazy.
        # Map a fake permission so that the utility is registered.
        self.map_permissions(['__fake_permission__'],
                             '__force_registry_registration__')

        import plone.i18n.normalizer
        self.layer.load_zcml_file('configure.zcml', plone.i18n.normalizer)
Esempio n. 27
0
 def setUp(self):
     # global component registrations
     getGlobalSiteManager().registerAdapter(dummy_uuid_adapter)
     xmlconfig.file(
         'configure.zcml',
         plone.uuid,
         context=self.layer['configurationContext'],
         )
     # site integration fixture/layer stuff:
     self.site = self.layer['site']
     setSite(self.site)
     self.catalog = self.site['portal_catalog']
     self._temporary_content_ids = set()
Esempio n. 28
0
    def test_getNextSiteManager(self):
        from zope.app.component import getNextSiteManager
        self.assertRaises(ComponentLookupError, getNextSiteManager, self.root)
        self.assertEqual(getNextSiteManager(self.f1), getGlobalSiteManager())
        self.assertEqual(getNextSiteManager(self.f2), self.sm1)
        self.assertEqual(getNextSiteManager(self.sm1), getGlobalSiteManager())
        self.assertEqual(getNextSiteManager(self.sm2), self.sm1)
        self.assertRaises(ComponentLookupError, getNextSiteManager, self.p1)
        self.assertRaises(ComponentLookupError, getNextSiteManager, self.p2)

        self.assertRaises(ComponentLookupError,
                          getNextSiteManager, self.unparented_folder)
        self.assertRaises(ComponentLookupError,
                          getNextSiteManager, self.unrooted_subfolder)
Esempio n. 29
0
    def test_queryNextSiteManager(self):
        from zope.app.component import queryNextSiteManager
        marker = object()
        self.assert_(queryNextSiteManager(self.root, marker) is marker)
        self.assert_(queryNextSiteManager(self.f1, marker) is getGlobalSiteManager())
        self.assertEqual(queryNextSiteManager(self.f2, marker), self.sm1)
        self.assertEqual(queryNextSiteManager(self.sm1), getGlobalSiteManager())
        self.assertEqual(queryNextSiteManager(self.sm2), self.sm1)
        self.assert_(queryNextSiteManager(self.p1, marker) is marker)
        self.assert_(queryNextSiteManager(self.p2, marker) is marker)

        self.assert_(queryNextSiteManager(self.unparented_folder, marker)
                     is marker)
        self.assert_(queryNextSiteManager(self.unrooted_subfolder, marker)
                     is marker)
Esempio n. 30
0
 def test_hit_registered_for_None(self):
     from zope.interface import Interface
     from zope.interface import implementer
     from zope.component import getGlobalSiteManager
     class IFoo(Interface):
         pass
     @implementer(IFoo)
     class Baz(object):
         def __init__(self, context):
             self.context = context
     getGlobalSiteManager().registerAdapter(Baz, (None,), IFoo, '')
     ctx = object()
     adapted = IFoo(ctx)
     self.assertTrue(adapted.__class__ is Baz)
     self.assertTrue(adapted.context is ctx)
Esempio n. 31
0
    def test_localroles_modified_event(self):
        from zope.interface import Interface
        from zope.interface import implementer
        from zope.event import notify
        from zope.component import getGlobalSiteManager
        from plone.app.workflow.interfaces import ILocalrolesModifiedEvent
        from plone.app.workflow.events import LocalrolesModifiedEvent

        # define local roles modified sensitive interface and class
        class ILRMEContext(Interface):
            pass

        @implementer(ILRMEContext)
        class LRMEContext(object):
            def __init__(self):
                # gets set by handler
                self.context = None
                self.event = None

        # define handler
        def lrme_handler(context, event):
            context.context = context
            context.event = event

        # register handler
        gsm = getGlobalSiteManager()
        gsm.registerHandler(lrme_handler,
                            (ILRMEContext, ILocalrolesModifiedEvent))
        # create object and notify subscriber
        context = LRMEContext()
        request = self.app.REQUEST
        event = LocalrolesModifiedEvent(context, request)
        notify(event)
        # check subscriber called
        self.assertEqual(context.context, context)
        self.assertEqual(context.event, event)
Esempio n. 32
0
    def test_post_to_folder_fires_proper_events(self):
        sm = getGlobalSiteManager()
        fired_events = []

        def record_event(event):
            fired_events.append(event.__class__.__name__)

        sm.registerHandler(record_event, (IObjectCreatedEvent, ))
        sm.registerHandler(record_event, (IObjectWillBeAddedEvent, ))
        sm.registerHandler(record_event, (IObjectAddedEvent, ))
        sm.registerHandler(record_event, (IObjectModifiedEvent, ))

        requests.post(
            self.portal.folder1.absolute_url(),
            headers={"Accept": "application/json"},
            auth=(SITE_OWNER_NAME, SITE_OWNER_PASSWORD),
            json={
                "@type": "Document",
                "id": "mydocument",
                "title": "My Document",
                "description": "123",
            },
        )

        self.assertEqual(
            fired_events,
            [
                "ObjectInitializedEvent", "ObjectAddedEvent",
                "ContainerModifiedEvent"
            ],
        )

        sm.unregisterHandler(record_event, (IObjectCreatedEvent, ))
        sm.unregisterHandler(record_event, (IObjectWillBeAddedEvent, ))
        sm.unregisterHandler(record_event, (IObjectAddedEvent, ))
        sm.unregisterHandler(record_event, (IObjectModifiedEvent, ))
Esempio n. 33
0
    def test_old_factory_not_unregistered_if_not_created_by_dexterity(self):
        portal_type = u"testtype"
        fti = DexterityFTI(portal_type)

        # Mock the lookup of the site and the site manager at the site root
        dummy_site = self.create_dummy()
        self.mock_utility(dummy_site, ISiteRoot)

        site_manager_mock = Mock(
            wraps=PersistentComponents(bases=(getGlobalSiteManager(),)))
        from zope.component.hooks import getSiteManager
        self.patch_global(getSiteManager, return_value=site_manager_mock)

        # Pretend like we have a utility registered

        reg1 = self.create_dummy()
        reg1.provided = IFactory
        reg1.name = 'old-factory'
        reg1.info = None

        site_manager_mock.registeredUtilities = Mock(return_value=[reg1])

        fti.factory = 'new-factory'
        ftiModified(
            fti,
            ObjectModifiedEvent(
                fti,
                DexterityFTIModificationDescription('factory', 'old-factory')
            )
        )

        # This should not be removed, since we didn't create it
        self.assertFalse(site_manager_mock.unregisterUtility.called)
        # A new one may still be created, however
        self.assertEqual(
            site_manager_mock.registerUtility.call_args[0][2], 'new-factory')
Esempio n. 34
0
 def __init__(self, fti=None):
     if not fti:
         return
     sql_connection = queryUtility(ISQLBaseConnectionUtility,
                                   name=fti.sql_connection,
                                   default=None)
     if sql_connection:
         self.connection_name = sql_connection.name
     else:
         sql_connection = queryUtility(ISQLBaseConnectionUtility,
                                       name=fti.sql_table,
                                       default=None)
     if sql_connection:
         self.connection_name = sql_connection.name
     else:
         processor = SQLBaseConnectionUtility(fti)
         connection_name = processor.name
         LOG.info('Base connection utility registered as ' +
                  connection_name)
         gsm = getGlobalSiteManager()
         gsm.registerUtility(processor,
                             ISQLBaseConnectionUtility,
                             name=connection_name)
         self.connection_name = connection_name
     self.sql_table = fti.sql_table
     self.factory = fti.factory
     self.sql_id_column = getattr(fti, 'sql_id_column', None) and getattr(
         fti, 'sql_id_column', None) or 'id'
     fieldnames = {}
     for field_name, field in schema.getFieldsInOrder(fti.lookupSchema()):
         if getattr(field, 'sql_column', None):
             sql_column = getattr(field, 'sql_column', None)
             fieldnames[field_name] = sql_column
     for line in getattr(fti, 'sql_fields_columns', []):
         fieldnames[line.split(':')[0]] = line.split(':')[1]
     self.fieldnames = fieldnames
Esempio n. 35
0
    def test_components_not_registered_on_add_if_exist(self):
        portal_type = u"testtype"
        fti = DexterityFTI(portal_type)
        container_dummy = self.create_dummy()

        # Mock the lookup of the site and the site manager at the site root
        dummy_site = self.create_dummy()
        self.mock_utility(dummy_site, ISiteRoot)

        site_manager_mock = self.mocker.proxy(
            PersistentComponents(bases=(getGlobalSiteManager(), )))
        getSiteManager_mock = self.mocker.replace(
            'zope.component.hooks.getSiteManager')
        self.expect(getSiteManager_mock(dummy_site)).result(site_manager_mock)

        # Register FTI utility and factory utility

        self.mock_utility(fti, IDexterityFTI, name=portal_type)
        self.mock_utility(DexterityFactory(portal_type),
                          IFactory,
                          name=portal_type)

        # We expect that all components are registered, so do not expect any registrations

        self.expect(
            site_manager_mock.registerUtility(
                fti, IDexterityFTI, portal_type)).passthrough().count(0)
        self.expect(
            site_manager_mock.registerUtility(
                mocker.MATCH(lambda x: isinstance(x, DexterityFactory) and x.
                             portal_type == portal_type), IFactory,
                portal_type)).passthrough().count(0)

        self.replay()

        ftiAdded(fti, ObjectAddedEvent(fti, container_dummy, fti.getId()))
Esempio n. 36
0
def unsubscribe_task_configs_for_content_type(task_config, event):
    """
    Unregister adapter returning 'task_config' to the interface
    of the content_type selected in the field 'task_container'.
    """

    gsm = getGlobalSiteManager()
    schedule_config = task_config.get_schedule_config()

    previous_interfaces = getattr(schedule_config, '_scheduled_interface_',
                                  None)
    if previous_interfaces and type(
            previous_interfaces[0]) not in [list, tuple]:
        previous_interfaces = (previous_interfaces, )
    previous_interfaces = [tuple_to_interface(i) for i in previous_interfaces]

    for previous_interface in previous_interfaces:
        removed = gsm.unregisterAdapter(required=(previous_interface, ),
                                        provided=IToTaskConfig,
                                        name=task_config.UID())
        if removed:
            msg = "Unregistered IToTaskConfig adapter '{}' for {}".format(
                task_config.Title(), previous_interface)
            logger.info(msg)
Esempio n. 37
0
def register_task_collection_criterion(task_config, event):
    """
    Register adapter turning a task config into a collection
    criterion filtering all tasks from this task config.
    """

    gsm = getGlobalSiteManager()
    task_config_UID = task_config.UID()

    class FilterTasksCriterion(object):
        def __init__(self, context):
            self.context = context

        @property
        def query(self):
            return {'task_config_UID': {'query': task_config_UID}}

    gsm.registerAdapter(factory=FilterTasksCriterion,
                        required=(Interface, ),
                        provided=ICompoundCriterionFilter,
                        name=task_config.UID())
    msg = "Registered task CollectionCriterion adapter '{}'".format(
        task_config.Title())
    logger.info(msg)
Esempio n. 38
0
    def _update(self, portal):
        sm = portal.getSiteManager()

        if sm.__name__ == '++etc++site':
            sm.__name__ = 'database'
            self.log.info("Set name of local site manager to %r", sm.__name__)

        bundle = portal.get_bundle()
        portal_cls_name = portal.__class__.__name__
        if bundle is getGlobalSiteManager() or bundle is bundles.get('Naaya'):
            bundle_name = bundle_for_site_cls.get(portal_cls_name, 'Naaya')
            bundle = bundles.get(bundle_name)
            portal.set_bundle(bundle)
            self.log.info("Portal bundle set to %r", bundle_name)
        else:
            self.log.info("Not changing portal bundle %r", bundle)

        forms_tool = portal.getFormsTool()
        for template in forms_tool.objectValues():
            name = template.getId()
            sm.registerUtility(template, ITemplate, name)
            self.log.info("Registered ITemplate %r", name)

        return True
Esempio n. 39
0
 def tearDown(self):
     gsm = getGlobalSiteManager()
     gsm.unregisterUtility(self.config, ISolrConnectionConfig)
Esempio n. 40
0
 def __init__(self, adapter, from_, provides):
     self.adapter = adapter
     self.from_ = from_
     self.provides = provides
     self.gsm = getGlobalSiteManager()
def includeme(*args, **kwargs):
    getGlobalSiteManager().registerUtility(Configurator(config, {}),
                                           IProjectConfigurator)
Esempio n. 42
0
        filename = '%s.pdf' % filename or obj.REQUEST.get(
            'filename') or obj.getId()

        try:
            res = obj.restrictedTraverse('@@wkpdf').get_pdf_file()
        except Exception as err:

            msg1 = "%s" % (str(err))
            msg2 = "Attenzione! Non è stato possibile allegare il file: %s" % filename
            api.portal.show_message(message=msg1,
                                    request=obj.REQUEST,
                                    type='error')
            api.portal.show_message(message=msg2,
                                    request=obj.REQUEST,
                                    type='warning')
        else:
            (f, c) = obj.setfile(res,
                                 filename=filename,
                                 overwrite=overwrite,
                                 contenttype='application/pdf')
            if f and c:
                old_item = obj.getItem(itemname, {}) or {}
                old_item[filename] = c
                obj.setItem(itemname, old_item)


#############################################################################
app = defaultApp()
gsm = component.getGlobalSiteManager()
gsm.registerUtility(app, IIolDocument, 'default')
Esempio n. 43
0
def includeme(config):
    global _producer_connection, _exchange
    setup_logging(loglevel='DEBUG')
    url = (config.registry.settings.get('celery_tasks.broker') or
           config.registry.settings.get('celery_tasks.imap.broker'))
    _producer_connection = BrokerConnection(url)



if __name__ == '__main__':
    if len(sys.argv) != 2:
        print "usage: python source_reader.py configuration.ini"
    config_file_name = sys.argv[-1]
    settings = get_appsettings(config_file_name, 'assembl')
    registry = getGlobalSiteManager()
    registry.settings = settings
    set_config(settings)
    fileConfig(config_file_name)
    # set the basic session maker without zope or autoflush
    engine = configure_engine(settings, False, autoflush=False, max_overflow=20)

    # @event.listens_for(engine, "checkin")
    def show_checkin(*args):
        global pool_counter
        pool_counter -= 1
        print "checkin pool: %d in %s" % (pool_counter, currentThread())
        print_stack()

    # @event.listens_for(engine, "checkout")
    def show_checkout(*args):
Esempio n. 44
0
 def start(self):
     gsm = component.getGlobalSiteManager()
     gsm.registerHandler(self, self._required)
Esempio n. 45
0
 def setUp(self):
     super(ZopeAdapterFixture, self).setUp()
     site_manager = getGlobalSiteManager()
     site_manager.registerAdapter(*self._args, **self._kwargs)
     self.addCleanup(site_manager.unregisterAdapter, *self._args,
                     **self._kwargs)
Esempio n. 46
0
def create_emailUtilities(instance_id=None):
    '''Create the utilities to send the email messages

:param str instance_id: The indentifier for the GroupServer instance
:returns: ``None``

The :func:`create_emailUtilities` function loads the ``smtp`` section of the
configuration of the instance specified by ``instance_id``. If no instance
is specified then :func:`gs.config.getInstanceId` is used to determine the
current instance. It then loads the following configuration options:

* ``hostname``
* ``port``
* ``username``
* ``password``
* ``no_tls``
* ``force_tls``
* ``queuepath``
* ``processorthread``
* ``xverp``

If the XVERP option is ``True`` then
:class:`gs.email.mailer.XVERPSMTPMailer` is registered as the utility used
to connect to the SMTP host; otherwise
:class:`zope.sendmail.mailer.SMTPMailer` is used. In either case the mailer
is configured with the options in the config file.'''
    if not instance_id:
        instance_id = getInstanceId()

    config = Config(instance_id)
    config.set_schema('smtp', {'hostname': str, 'port': int,
                               'username': str, 'password': str,
                               'no_tls': bool_, 'force_tls': bool_,
                               'queuepath': str, 'processorthread': bool_,
                               'xverp': bool_})
    smtpconfig = config.get('smtp', strict=False)
    name = ''
    for key in ('hostname', 'port', 'username', 'password', 'no_tls',
                'force_tls'):
        name += '+%s+' % smtpconfig.get(key, None)

    gsm = getGlobalSiteManager()
    if not queryUtility(IMailer, 'gs.mailer.%s' % name):
        if smtpconfig.get('xverp', False):
            Mailer = XVERPSMTPMailer
        else:
            Mailer = SMTPMailer

        gsm.registerUtility(
            Mailer(
                hostname=smtpconfig.get('hostname', None),
                port=smtpconfig.get('port', None),
                username=smtpconfig.get('username', None),
                password=smtpconfig.get('password', None),
                no_tls=smtpconfig.get('no_tls', None),
                force_tls=smtpconfig.get('force_tls', None)),
            IMailer, name='gs.mailer.%s' % name)
    queuePath = smtpconfig.get('queuepath', '/tmp/mailqueue')
    if not queryUtility(IMailDelivery, name='gs.maildelivery'):
        delivery = QueuedMailDelivery(queuePath)
        gsm.registerUtility(delivery, IMailDelivery, name='gs.maildelivery')
        if smtpconfig.get('processorthread', True):
            mailerObject = getUtility(IMailer, 'gs.mailer.%s' % name)
            thread = QueueProcessorThread()
            thread.setMailer(mailerObject)
            thread.setQueuePath(queuePath)
            thread.start()
Esempio n. 47
0
def register_static_uuid_utility(prefix):
    prefix = re.sub(r'[^a-zA-Z0-9\-_]', '', prefix)
    generator = StaticUUIDGenerator(prefix)
    getGlobalSiteManager().registerUtility(component=generator)
Esempio n. 48
0
def getSiteManager(context=None):
    if _site is not None:
        return _site.getSiteManager()
    return component.getGlobalSiteManager()
Esempio n. 49
0
 def __init__(self):
     super(SiteManager, self).__init__()
     self.__bases__ = (component.getGlobalSiteManager(),)
Esempio n. 50
0
 def setUp(self):
     super(ZopeUtilityFixture, self).setUp()
     gsm = getGlobalSiteManager()
     gsm.registerUtility(self.component, self.intf, self.name)
     self.addCleanup(gsm.unregisterUtility, self.component, self.intf,
                     self.name)
Esempio n. 51
0
    else:
        assert IIModelInterface.providedBy(cls), "Invalid Interface"
        return cls


def queryModelDescriptor(ob):
    if not IInterface.providedBy(ob):
        ob = filter(IIModelInterface.providedBy, 
            list(interface.implementedBy(ob)))[0]    
    name = "%s.%s" % (ob.__module__, ob.__name__)
    return component.queryAdapter(ob, IModelDescriptor, name)

# Register queryModelDescriptor adaptor (to override their upstream ZCML reg)
# signature: factory, adapts:[iface], provides:iface, name, event=False
component.getGlobalSiteManager().registerAdapter(queryModelDescriptor, 
    [IAlchemistContent],
    IModelAnnotation # !+IModelDescriptor ?
)


# local utils

class interned(object):
    """Re-use of same immutable instances."""
    _tuples = {}
    @classmethod
    def tuple(cls, seq):
        key = intern("".join([ str(s) for s in seq ]))
        if not cls._tuples.has_key(key):
           cls._tuples[key] = tuple(seq)
        return cls._tuples[key]
Esempio n. 52
0
 def tearDown(self):
     clearSite()
     # Make sure our global utility is gone again
     gsm = getGlobalSiteManager()
     gsm.unregisterUtility(provided=IComponentsHandlerBlacklist,
                           name=u'dummy')
Esempio n. 53
0
 def end(self):
     gsm = component.getGlobalSiteManager()
     assert gsm.unregisterHandler(self, self._required)
 def tearDown(self):
     self.api_session.close()
     gsm = getGlobalSiteManager()
     gsm.unregisterUtility(provided=IVocabularyFactory,
                           name='plone.restapi.tests.test_vocabulary')
Esempio n. 55
0
 def getMailer(self):
     return getGlobalSiteManager().getUtility(IMailDelivery, 'Mail')
Esempio n. 56
0
    def tearDown(self):
        import wsgi_intercept
        wsgi_intercept.remove_wsgi_intercept('test', 80)

        gsm = getGlobalSiteManager()
        gsm.unregisterUtility(self.mail_delivery, IMailDelivery, "Mail")
Esempio n. 57
0
 def setUp(self):
     super(ZopeEventHandlerFixture, self).setUp()
     gsm = getGlobalSiteManager()
     provideHandler(self._handler)
     self.addCleanup(gsm.unregisterHandler, self._handler)
Esempio n. 58
0
 def setUpZope(self, app, configurationContext):
     newgrid = Bootstrap3()
     sm = getGlobalSiteManager()
     sm.registerUtility(newgrid, name='bootstrap3')
Esempio n. 59
0
from zope.component import getGlobalSiteManager, ComponentLookupError
from zope.interface import implementer
from interfaces import IEncrypter, IEncrypterClass

_gsm = getGlobalSiteManager()


@implementer(IEncrypter)
class CommonEncrypter(object):
    name = ""
    attributes = ()

    def __init__(self, **kw):
        kwargs = {}
        for i in self.attributes:
            if i in kw:
                kwargs[i] = kw[i]
        self._signature = ".e%s$" % self.name
        self._init_encryption(**kwargs)
        self.register()

    def _init_encryption(self, **kw):
        pass

    def encrypt(self, data):
        if not data.startswith(self._signature):
            encrypted = self._signature + self._encrypt(data)
            return encrypted
        else:
            return data
Esempio n. 60
0
 def tearDown(self):
     gsm = getGlobalSiteManager()
     gsm.unregisterAdapter(CORSTestPolicy, (Interface, IBrowserRequest),
                           ICORSPolicy)