Example #1
0
 def appendSlave(self, msgHeader, nodename=None):
     """
     append oid to slave list
     """
     if nodename:
         if nodename in zapi.getRoot(self):
             newSlaveNode = zapi.getRoot(self)[nodename]
         else:
             #self.oidSlave = msgHeader['from_oid']
             newSlaveNode = createObject(\
                 u"org.ict_ok.slave.slave.Slave")
             ISlave['objectID'].readonly = False
             newSlaveNode.objectID = msgHeader['from_oid']
             ISlave['objectID'].readonly = True
             newSlaveNode.ikName = unicode(nodename)
             notify(ObjectCreatedEvent(newSlaveNode))
             zapi.getRoot(self)[nodename] = newSlaveNode
     slaveSupervisor = zapi.queryUtility(IAdmUtilSupervisor,
                                         context=newSlaveNode)
     if slaveSupervisor:
         #slaveSupervisor.ipv4Master = msgHeader['to_ip']
         #slaveSupervisor.oidMaster = msgHeader['to_oid']
         slaveSupervisor.status2Master = u"connected"
         slaveSupervisor.ipv4Slave = msgHeader['from_ip']
         slaveSupervisor.oidSlave = msgHeader['from_oid']
         slaveSupervisor.lastSeenSlave = datetime.now(berlinTZ)
     self._p_changed = True
     mq_utility = zapi.queryUtility(IAdmUtilObjMQ)
     if mq_utility:
         my_data = {'cmd': 'connected'}
         my_data['header'] = mq_utility.switchFromTo(msgHeader)
         mq_utility.sendPerMq(my_data)
Example #2
0
def queryInterface(id, default=None):
    """return interface or ``None``

    >>> from zope.app.testing import placelesssetup
    >>> placelesssetup.tearDown()
    >>> placelesssetup.setUp()

    >>> from zope.interface import Interface
    >>> from zope.interface.interfaces import IInterface
    >>> from zope.app.content.interfaces import IContentType

    >>> class I3(Interface):
    ...     pass
    >>> IInterface.providedBy(I3)
    True
    >>> IContentType.providedBy(I3)
    False
    >>> queryInterface('zope.app.component.interface.I3')
    
    >>> provideInterface('', I3, IContentType)
    >>> IContentType.providedBy(I3)
    True
    >>> iface = queryInterface('zope.app.component.interface.I3')
    >>> iface.__name__
    'I3'
    >>> placelesssetup.tearDown()
    """
    return zapi.queryUtility(IInterface, id, default)
Example #3
0
def checkPermission(permission, object, interaction=None):
    """Return whether security policy allows permission on object.

    Arguments:
    permission -- A permission name
    object -- The object being accessed according to the permission
    interaction -- This Zope 3 concept has no equivalent in Zope 2,
        and is ignored.

    checkPermission is guaranteed to return True if permission is
    CheckerPublic or None.
    """
    if (permission in ('zope.Public', 'zope2.Public') or
        permission is None or permission is CheckerPublic):
        return True

    if isinstance(permission, StringTypes):
        permission = zapi.queryUtility(IPermission, unicode(permission))
        if permission is None:
            return False

    if getSecurityManager().checkPermission(permission.title, object):
        return True

    return False
Example #4
0
 def getDDD(self):
     """TODO: must check"""
     from org.ict_ok.admin_utils.supervisor.interfaces import \
          IAdmUtilSupervisor
     slaveSupervisor = zapi.queryUtility(IAdmUtilSupervisor,
                                         context=self.context)
     return slaveSupervisor.objectID
Example #5
0
    def translate(self,
                  domain,
                  msgid,
                  mapping=None,
                  context=None,
                  target_language=None,
                  default=None):
        if isinstance(msgid, MessageID):
            domain = msgid.domain
            default = msgid.default
            mapping = msgid.mapping

        util = zapi.queryUtility(ITranslationDomain, domain)

        if util is None:
            # fallback to translation service that was registered,
            # DummyTranslationService the worst
            ts = _fallback_translation_service
            return ts.translate(domain,
                                msgid,
                                mapping=mapping,
                                context=context,
                                target_language=target_language,
                                default=default)

        # in Zope3, context is adapted to IUserPreferredLanguages,
        # which means context should be the request in this case.
        if context is not None:
            context = aq_acquire(context, 'REQUEST', None)
        return util.translate(msgid,
                              mapping=mapping,
                              context=context,
                              target_language=target_language,
                              default=default)
Example #6
0
 def sendPong(self, msgHeader, nodename=None):
     """
     revert message header and sends a pong as response to the ping
     """
     if nodename:
         if nodename in zapi.getRoot(self):
             newSlaveNode = zapi.getRoot(self)[nodename]
             slaveSupervisor = zapi.queryUtility(IAdmUtilSupervisor,
                                                 context=newSlaveNode)
             if slaveSupervisor:
                 slaveSupervisor.lastSeenMaster = datetime.now(berlinTZ)
     mq_utility = zapi.queryUtility(IAdmUtilObjMQ)
     if mq_utility:
         my_data = {'cmd': 'pong'}
         my_data['header'] = mq_utility.switchFromTo(msgHeader)
         mq_utility.sendPerMq(my_data)
Example #7
0
def checkPermission(permission, object, interaction=None):
    """Return whether security policy allows permission on object.

    Arguments:
    permission -- A permission name
    object -- The object being accessed according to the permission
    interaction -- This Zope 3 concept has no equivalent in Zope 2,
        and is ignored.

    checkPermission is guaranteed to return True if permission is
    CheckerPublic or None.
    """
    if (permission in ('zope.Public', 'zope2.Public') or permission is None
            or permission is CheckerPublic):
        return True

    if isinstance(permission, StringTypes):
        permission = zapi.queryUtility(IPermission, unicode(permission))
        if permission is None:
            return False

    if getSecurityManager().checkPermission(permission.title, object):
        return True

    return False
Example #8
0
    def createDirectDelivery():
        mailerObject = zapi.queryUtility(IMailer, mailer)
        if mailerObject is None:
            raise ConfigurationError("Mailer %r is not defined" %mailer)

        delivery = DirectMailDelivery(mailerObject)
        delivery = _assertPermission(permission, IMailDelivery, delivery)

        handler('provideUtility', IMailDelivery, delivery, name)
Example #9
0
 def shutdownHost(self):
     """
     trigger shutdownHost
     """
     print "HostVMwareEsx shutdownHost"
     esx_utility = zapi.queryUtility(IAdmUtilEsxVim)
     if esx_utility and len(self.esxUuid) > 0:
         self.appendHistoryEntry("shutdown Host")
         esx_utility.shutdownHostEsxHost(self.esxUuid)
Example #10
0
 def enterMaintenanceMode(self):
     """
     trigger enterMaintenanceMode
     """
     print "HostVMwareEsx enterMaintenanceMode"
     esx_utility = zapi.queryUtility(IAdmUtilEsxVim)
     if esx_utility and len(self.esxUuid) > 0:
         self.appendHistoryEntry("enter maintenance mode")
         esx_utility.enterMaintenanceModeEsxHost(self.esxUuid)
Example #11
0
 def queryLocalService(self, name, default=None):
     if name in _builtinServices:
         return self
     service = zapi.queryUtility(IService, name, self)
     if service is None:
         return default
     if zapi.getSiteManager(service) is not self:
         return default
     return service
    def testUtility_wo_provides(self):
        self.assertEqual(zapi.queryUtility(IV), None)

        xmlconfig(StringIO(template % (
            '''
            <utility
              component="zope.app.component.tests.components.comp"
              />
            '''
            )))

        self.assertEqual(zapi.getUtility(IApp), comp)
    def testUtilityFactory(self):
        self.assertEqual(zapi.queryUtility(IV), None)

        xmlconfig(StringIO(template % (
            '''
            <utility
              factory="zope.app.component.tests.components.Comp"
              provides="zope.app.component.tests.components.IApp"
              />
            '''
            )))

        self.assertEqual(zapi.getUtility(IApp).__class__, Comp)
    def testNamedUtility(self):
        self.testUtility()
        self.assertEqual(zapi.queryUtility(IV, 'test'), None)
        xmlconfig(StringIO(template % (
            '''
            <utility
              component="zope.app.component.tests.components.comp"
              provides="zope.app.component.tests.components.IApp"
              name="test"
              />
            '''
            )))

        self.assertEqual(zapi.getUtility(IApp, "test"), comp)
Example #15
0
 def testRegisterTranslations(self):
     eq = self.assertEqual
     eq(zapi.queryUtility(ITranslationDomain), None)
     xmlconfig.string(
         template % '''
         <configure package="zope.i18n.tests">
         <i18n:registerTranslations directory="./locale" />
         </configure>
         ''', self.context)
     path = os.path.join(os.path.dirname(zope.i18n.tests.__file__),
                         'locale', 'en',
                         'LC_MESSAGES', 'zope-i18n.mo')
     util = zapi.getUtility(ITranslationDomain, 'zope-i18n')
     eq(util._catalogs, {'test': ['test'], 'en': [unicode(path)]})
Example #16
0
    def createQueuedDelivery():
        delivery = QueuedMailDelivery(queuePath)
        delivery = _assertPermission(permission, IMailDelivery, delivery)

        handler('provideUtility', IMailDelivery, delivery, name)

        mailerObject = zapi.queryUtility(IMailer, mailer)
        if mailerObject is None:
            raise ConfigurationError("Mailer %r is not defined" %mailer)

        thread = QueueProcessorThread()
        thread.setMailer(mailerObject)
        thread.setQueuePath(queuePath)
        thread.start()
    def testProtectedUtility(self):
        self.assertEqual(zapi.queryUtility(IV), None)
        xmlconfig(StringIO(template % (
            '''
            <utility
              component="zope.app.component.tests.components.comp"
              provides="zope.app.component.tests.components.IApp"
              permission="zope.Public"
              />
            '''
            )))

        utility = ProxyFactory(zapi.getUtility(IApp))
        items = [item[0] for item in getTestProxyItems(utility)]
        self.assertEqual(items, ['a', 'f'])
        self.assertEqual(removeSecurityProxy(utility), comp)
Example #18
0
    def fromUnicode(self, u):
        name = str(u.strip())

        try:
            value = zapi.queryUtility(ILayer, name)
        except ComponentLookupError:
            # The component architecture is not up and running.
            pass
        else:
            if value is not None:
                return value

        try:
            value = self.context.resolve('zope.app.layers.'+name)
        except (ConfigurationError, ValueError), v:
            try:
                value = self.context.resolve(name)
            except ConfigurationError, v:
                raise zope.schema.ValidationError(v)
Example #19
0
def checkPermission(context, permission_id):
    """Check whether a given permission exists in the provided context.

    >>> from zope.app.testing.placelesssetup import setUp, tearDown
    >>> setUp()

    >>> from zope.app.testing.ztapi import provideUtility
    >>> provideUtility(IPermission, Permission('x'), 'x')

    >>> checkPermission(None, 'x')
    >>> checkPermission(None, 'y')
    Traceback (most recent call last):
    ...
    ValueError: ('Undefined permission id', 'y')

    >>> tearDown()
    """
    if permission_id is CheckerPublic:
        return
    if not zapi.queryUtility(IPermission, permission_id, context=context):
        raise ValueError("Undefined permission id", permission_id)
Example #20
0
 def eventInp_shutdown(self, eventMsg=None):
     """ start the shutdown of the host """
     eventProcessed = False
     if self.inEventMask(eventMsg):
         eventProcessed = True
         eventMsg.stopit(self, "Host.eventInp_shutdown")
         utilXbar = zapi.queryUtility(IAdmUtilEventCrossbar)
         utilEvent = utilXbar[eventMsg.oidEventObject]
         if utilEvent.dryRun:
             msgText = u"Shutdown (dry run)"
             print "Host.eventInp_shutdown (%s) (dry run)             ############## <-" % (
                 self.ikName)
         else:
             msgText = u"Shutdown"
             print "Host.eventnp_shutdown (%s)              ############## <-" % (
                 self.ikName)
             self.enterMaintenanceMode()
             time.sleep(60)
             self.shutdownHost()
         self.appendHistoryEntry(msgText)
     return eventProcessed
Example #21
0
    def __getattr__(self, key):
        # Try to find a sub-group of the given id
        group = self.get(key)
        if group is not None:
            return group

        # Try to find a preference of the given name
        if self.__schema__ and key in self.__schema__:
            marker = object()
            value = self.data.get(key, marker)
            if value is marker:
                # Try to find a default preference provider
                provider = zapi.queryUtility(IDefaultPreferenceProvider,
                                             context=self)
                if provider is None:
                    return self.__schema__[key].default
                defaultGroup = provider.getDefaultPreferenceGroup(self.__id__)
                return getattr(defaultGroup, key)
            return value

        # Nothing found, raise an attribute error
        raise AttributeError("'%s' is not a preference or sub-group." % key)
Example #22
0
File: i18n.py Project: goschtl/zope
    def translate(self, domain, msgid, mapping=None,
                  context=None, target_language=None, default=None):
        if isinstance(msgid, (Message, MessageID)):
            domain = msgid.domain
            default = msgid.default
            mapping = msgid.mapping

        util = zapi.queryUtility(ITranslationDomain, domain)

        if util is None:
            # fallback to translation service that was registered,
            # DummyTranslationService the worst
            ts = _fallback_translation_service
            return ts.translate(domain, msgid, mapping=mapping, context=context,
                                target_language=target_language, default=default)

        # in Zope3, context is adapted to IUserPreferredLanguages,
        # which means context should be the request in this case.
        if context is not None:
            context = aq_acquire(context, 'REQUEST', None)
        return util.translate(msgid, mapping=mapping, context=context,
                              target_language=target_language, default=default)
Example #23
0
    def publishTraverse(self, request, name):
        """See zope.app.container.interfaces.IAdding"""
        if '=' in name:
            view_name, content_name = name.split("=", 1)
            self.contentName = content_name

            if view_name.startswith('@@'):
                view_name = view_name[2:]
            return zapi.getView(self, view_name, request)

        if name.startswith('@@'):
            view_name = name[2:]
        else:
            view_name = name

        view = zapi.queryView(self, view_name, request)
        if view is not None:
            return view

        factory = zapi.queryUtility(IFactory, name)
        if factory is None:
            return super(BasicAdding, self).publishTraverse(request, name)

        return factory
Example #24
0
    def evaluateCode(self, lang, code):
        if not self.evaluateInlineCode:
            raise InlineCodeError(
                  _('Inline Code Evaluation is deactivated, which means that '
                    'you cannot have inline code snippets in your Page '
                    'Template. Activate Inline Code Evaluation and try again.'))

        # TODO This is only needed when self.evaluateInlineCode is true,
        # so should only be needed for zope.app.pythonpage.
        from zope.app.interpreter.interfaces import IInterpreter
        interpreter = zapi.queryUtility(IInterpreter, lang)
        if interpreter is None:
            error = _('No interpreter named "${lang_name}" was found.',
                      mapping={'lang_name': lang})
            raise InlineCodeError(error)

        globals = self.vars.copy()
        result = interpreter.evaluateRawCode(code, globals)
        # Add possibly new global variables.
        old_names = self.vars.keys()
        for name, value in globals.items():
            if name not in old_names:
                self.setGlobal(name, value)
        return result
Example #25
0
    def publishTraverse(self, request, name):
        """See zope.app.container.interfaces.IAdding"""
        if '=' in name:
            view_name, content_name = name.split("=", 1)
            self.contentName = content_name

            if view_name.startswith('@@'):
                view_name = view_name[2:]
            return zapi.getMultiAdapter((self, request), name=view_name)

        if name.startswith('@@'):
            view_name = name[2:]
        else:
            view_name = name

        view = zapi.queryView(self, view_name, request)
        if view is not None:
            return view

        factory = zapi.queryUtility(IFactory, name)
        if factory is None:
            return super(BasicAdding, self).publishTraverse(request, name)

        return factory
Example #26
0
 def get(self, key, default=None):
     """See zope.app.container.interfaces.IReadContainer"""
     utility = zapi.queryUtility(IDocumentationModule, key, default)
     if utility != default:
         locate(utility, self, key)
     return utility
Example #27
0
    def start(self, *arguments):
        #print "%%%%%%%%%%%% service_nagios1_app1WorkItem::start(1)"
        self.addStartedWorkitem()

    def addStartedWorkitem(self):
        #print "%%%%%%%%%%%% service_nagios1_app1WorkItem::addStartedWorkitem()"
        pass


integration.service_nagios1_app1WorkItem = service_nagios1_app1WorkItem

proc = pd()

#print "----------->"
#print dir(pd)

from zope.component import queryUtility
from org.ict_ok.admin_utils.wfmc.interfaces import \
     IAdmUtilWFMC

utilWFMC = queryUtility(IAdmUtilWFMC)
#print "utilWFMC: %s" % utilWFMC

from zope.app import zapi
from org.ict_ok.admin_utils.objmq.interfaces import IAdmUtilObjMQ
mq_utility = zapi.queryUtility(IAdmUtilObjMQ)
#print "mq_utility: %s" % mq_utility

proc.start()
Example #28
0
 def get(self, key, default=None):
     id = self.__id__ and self.__id__ + '.' + key or key
     group = zapi.queryUtility(IPreferenceGroup, id, default)
     if group is default:
         return default
     return group.__bind__(self)
Example #29
0
 def __contains__(self, value):
     return zapi.queryUtility(self.interface, value) is not None
Example #30
0
 def get(self, key, default=None):
     return TypeInterface(zapi.queryUtility(IInterface, key, default=default), self, key)
Example #31
0
 def get(self, key, default=None):
     """See zope.app.container.interfaces.IReadContainer"""
     return LocationProxy(zapi.queryUtility(self.interface, key, default=default), self, key)