def test_getNextUtility(self): # test local site vs. global site global_dummy = DummyUtility() provideUtility(global_dummy, IDummyUtility) local_dummy = DummyUtility() sm = zapi.getSiteManager() sm.registerUtility(IDummyUtility, local_dummy) self.assertEquals(zapi.getUtility(IDummyUtility), local_dummy) self.assertEquals(getNextUtility(self.folder.site, IDummyUtility), global_dummy) # test local site vs. nested local site manage_addDummySite(self.folder.site, 'subsite') enableLocalSiteHook(self.folder.site.subsite) setSite(self.folder.site.subsite) sublocal_dummy = DummyUtility() sm = zapi.getSiteManager() sm.registerUtility(IDummyUtility, sublocal_dummy) self.assertEquals(zapi.getUtility(IDummyUtility), sublocal_dummy) self.assertEquals( getNextUtility(self.folder.site.subsite, IDummyUtility), local_dummy) self.assertEquals(getNextUtility(self.folder.site, IDummyUtility), global_dummy)
def test_nestedSitesDontConflictButStillAcquire(self): # let's register a dummy utility in the dummy site dummy = DummyUtility() sm = zapi.getSiteManager() sm.registerUtility(IDummyUtility, dummy) # let's also create a subsite and make that our site manage_addDummySite(self.folder.site, 'subsite') enableLocalSiteHook(self.folder.site.subsite) setSite(self.folder.site.subsite) # we should still be able to lookup the original utility from # the site one level above self.assertEqual(zapi.getUtility(IDummyUtility), dummy) # now we register a dummy utility in the subsite and see that # its registration doesn't conflict subdummy = DummyUtility() sm = zapi.getSiteManager() sm.registerUtility(IDummyUtility, subdummy) # when we look it up we get the more local one now because the # more local one shadows the less local one self.assertEqual(zapi.getUtility(IDummyUtility), subdummy) # getAllUtilitiesFor gives us both the more local and the less # local utility (XXX not sure if this is the right semantics # for getAllUtilitiesFor) self.assertEqual(sets.Set(zapi.getAllUtilitiesRegisteredFor(IDummyUtility)), sets.Set([subdummy, dummy])) # getUtilitiesFor will only find one, because the more local # one shadows the less local one self.assertEqual(list(zapi.getUtilitiesFor(IDummyUtility)), [('', subdummy)])
def test_getNextUtility(self): # test local site vs. global site global_dummy = DummyUtility() provideUtility(global_dummy, IDummyUtility) local_dummy = DummyUtility() sm = getSiteManager() sm.registerUtility(IDummyUtility, local_dummy) self.assertEquals(zapi.getUtility(IDummyUtility), local_dummy) self.assertEquals(getNextUtility(self.folder.site, IDummyUtility), global_dummy) # test local site vs. nested local site manage_addDummySite(self.folder.site, 'subsite') import warnings showwarning = warnings.showwarning warnings.showwarning = lambda *a, **k: None enableLocalSiteHook(self.folder.site.subsite) warnings.showwarning = showwarning sublocal_dummy = DummyUtility() sm = getSiteManager() sm.registerUtility(IDummyUtility, sublocal_dummy) self.assertEquals(zapi.getUtility(IDummyUtility), sublocal_dummy) self.assertEquals(getNextUtility(self.folder.site.subsite, IDummyUtility), local_dummy) self.assertEquals(getNextUtility(self.folder.site, IDummyUtility), global_dummy)
def cities(self, context): root = zapi.getUtility(Products.CMFPlone.interfaces.IPloneSiteRoot) cat = root.portal_catalog results = [] keys = [] ## All cities allcities_util = zapi.getUtility(ISwissCities) allcities = allcities_util.cities() #print allcities allcities_dict = dict(allcities) # Contextualize the list brains = cat({'portal_type': ['JubinStationPartner','JubinRestaurantPartner','JubinCommercialPartner',], 'path': '/'.join(context.getPhysicalPath()) }) for brain in brains: obj = brain.getObject() city_key = obj.city if city_key in keys: continue keys.append(city_key) # Now build the list of key/value pairs for k in keys: v = allcities_dict.get(k, '') if v: results.append((k, v)) results = sorted(results,key=operator.itemgetter(0)) return results
def test_getNextUtility(self): # test local site vs. global site global_dummy = DummyUtility() provideUtility(global_dummy, IDummyUtility) local_dummy = DummyUtility() sm = zapi.getSiteManager() sm.registerUtility(IDummyUtility, local_dummy) self.assertEquals(zapi.getUtility(IDummyUtility), local_dummy) self.assertEquals(getNextUtility(self.folder.site, IDummyUtility), global_dummy) # test local site vs. nested local site manage_addDummySite(self.folder.site, 'subsite') enableLocalSiteHook(self.folder.site.subsite) setSite(self.folder.site.subsite) sublocal_dummy = DummyUtility() sm = zapi.getSiteManager() sm.registerUtility(IDummyUtility, sublocal_dummy) self.assertEquals(zapi.getUtility(IDummyUtility), sublocal_dummy) self.assertEquals(getNextUtility(self.folder.site.subsite, IDummyUtility), local_dummy) self.assertEquals(getNextUtility(self.folder.site, IDummyUtility), global_dummy)
def test_getNextUtility(self): # test local site vs. global site global_dummy = DummyUtility() provideUtility(global_dummy, IDummyUtility) local_dummy = DummyUtility() sm = getSiteManager() sm.registerUtility(IDummyUtility, local_dummy) self.assertEquals(zapi.getUtility(IDummyUtility), local_dummy) self.assertEquals(getNextUtility(self.folder.site, IDummyUtility), global_dummy) # test local site vs. nested local site manage_addDummySite(self.folder.site, 'subsite') import warnings showwarning = warnings.showwarning warnings.showwarning = lambda *a, **k: None enableLocalSiteHook(self.folder.site.subsite) warnings.showwarning = showwarning sublocal_dummy = DummyUtility() sm = getSiteManager() sm.registerUtility(IDummyUtility, sublocal_dummy) self.assertEquals(zapi.getUtility(IDummyUtility), sublocal_dummy) self.assertEquals( getNextUtility(self.folder.site.subsite, IDummyUtility), local_dummy) self.assertEquals(getNextUtility(self.folder.site, IDummyUtility), global_dummy)
def cmd(self): """ commnds for objmq """ #obj = removeAllProxies(self.context) obj = self.context print "cmd/objmq" print "path: %s" % (zapi.getPath(obj)) action = self.request.get('cmd', default=None) if action: if action == 'start': obj.status2Master = u"connecting" #print "start" #print "obj.oidSlave: %s" % (obj.oidSlave) #obj.appendSlaveUid(u"bc6ae87821e43509dc3a5152a030951b0") #print "dir(obj.oidSlave): %s" % dir(obj.oidSlave) #print "obj.oidSlave: %s" % (obj.oidSlave) mq_utility = zapi.getUtility(IAdmUtilObjMQ) my_data = { 'cmd': 'connect', 'nodename': unicode(obj.getNodeName()) } my_data['header'] = {'from_oid': obj.objectID, 'from_ip': obj.ipv4My, 'from_path': getPath(obj), 'to_oid': obj.oidMaster, 'to_ip': obj.ipv4Master, 'to_path': u"/++etc++site/default"+\ "/AdmUtilSupervisor" } mq_utility.sendPerMq(my_data) #python_pickle = pickle.dumps(my_data) ##print "toxml: %s" % toxml(python_pickle) #mq_utility.sendPerMq(toxml(python_pickle)) #mq_utility = zapi.getUtility(IMailDelivery, 'ikObjTransportQueue') #from_adr = u"http://%s@%s:8080%s" % \ #(obj.objectID, obj.ipv4My, zapi.getPath(obj)) #to_adr = u"http://%s@%s:8080/++etc++site/default/AdmUtilSupervisor" % \ #(str(obj.oidMaster), str(obj.ipv4Master)) #mq_utility.send(from_adr, [to_adr], "msg_start") elif action == 'stop': print "stop" mq_utility = zapi.getUtility(IMailDelivery, 'ikObjTransportQueue') from_adr = u"http://%s@%s:8080%s" % \ (obj.objectID, obj.ipv4My, zapi.getPath(obj)) to_adr = u"http://%s@%s:8080/++etc++site/"+\ "default/AdmUtilSupervisor" % \ (str(obj.oidMaster), str(obj.ipv4Master)) mq_utility.send(from_adr, [to_adr], "msg_stop") elif action == 'ping': obj.sendPing() else: pass return self.request.response.redirect('./@@objmq')
def reindex_db(self): """ will reindex the catalogs of all tables in database """ iid = zapi.getUtility(IIntIds, '') my_catalog = zapi.getUtility(ICatalog) my_catalog.updateIndexes() self.appendEventHistory(\ u"reindex the catalogs of all tables in database")
def __init__(self, context, request): super(SiteManagementView, self).__init__(context, request) if 'activeTool' in request: request.response.setCookie('SetActiveTool', request['activeTool'], path="/") self.activeTool = zapi.getUtility(IToolConfiguration, request['activeTool']) elif 'SetActiveTool' in request: self.activeTool = zapi.getUtility(IToolConfiguration, request['SetActiveTool'])
def applyChanges(self, data): content = self.getContent() changes = applyChanges(self, content, data) # ``changes`` is a dictionary; if empty, there were no changes if changes: #import pdb;pdb.set_trace() # Construct change-descriptions for the object-modified event descriptions = [] for interface, attrs in changes.items(): if interface == IAdmUtilEvent: print "##### Event 2 #######" elif IEventIfSuperclass.isEqualOrExtendedBy(interface): print "##### Superclass 2 #######" names = attrs.keys() for attr in attrs: if attr.find("eventInpObjs_" ) == 0: # attribute name starts with ... functionName = attr[len('eventInpObjs_'):] print "attr: %s (I:%s)" % (attr, interface) print " old: ", attrs[attr]['oldval'] print " new: ", attrs[attr]['newval'] newSet = attrs[attr]['newval'] oldSet = attrs[attr]['oldval'] if type(newSet) == type(set()) and \ type(oldSet) == type(set()): newEntries = newSet.difference(oldSet) oldEntries = oldSet.difference(newSet) for oldOid in oldEntries: my_catalog = zapi.getUtility(ICatalog) for resObj in my_catalog.searchResults( oid_index=oldOid): if IAdmUtilEvent.providedBy(resObj): resObj.removeOidFromOutObjects( content.objectID + "." + functionName) resObj.removeInvalidOidFromInpOutObjects( ) resObj._p_changed = True for newOid in newEntries: my_catalog = zapi.getUtility(ICatalog) for resObj in my_catalog.searchResults( oid_index=newOid): if IAdmUtilEvent.providedBy(resObj): resObj.addOidToOutObjects( content.objectID + "." + functionName) resObj.removeInvalidOidFromInpOutObjects( ) resObj._p_changed = True descriptions.append(Attributes(interface, *names)) # Send out a detailed object-modified event zope.event.notify(ObjectModifiedEvent(content, *descriptions)) return changes
def test_registerTwoUtilitiesWithSameNameDifferentInterface(self): sm = zapi.getSiteManager() self.failUnless(IRegisterUtilitySimply.providedBy(sm)) dummy = DummyUtility() superdummy = DummyUtility() directlyProvides(superdummy, ISuperDummyUtility) sm.registerUtility(IDummyUtility, dummy, 'dummy') sm.registerUtility(ISuperDummyUtility, superdummy, 'dummy') self.assertEquals(zapi.getUtility(IDummyUtility, 'dummy'), dummy) self.assertEquals(zapi.getUtility(ISuperDummyUtility, 'dummy'), superdummy)
def testRegister(self): context = xmlconfig.file("perm.zcml", zope.app.security.tests) perm = zapi.getUtility(IPermission, "Can.Do.It") self.failUnless(perm.id.endswith('Can.Do.It')) self.assertEqual(perm.title, 'A Permissive Permission') self.assertEqual(perm.description, 'This permission lets you do anything')
def translate(self, msgid, mapping=None, context=None, target_language=None, default=None): """See interface `ITranslationDomain`""" if target_language is None and context is not None: avail_langs = self.getAvailableLanguages() # Let's negotiate the language to translate to. :) negotiator = zapi.getUtility(INegotiator, context=self) target_language = negotiator.getLanguage(avail_langs, context) # Get the translation. Default is the source text itself. catalog_names = self._catalogs.get(target_language, []) for name in catalog_names: catalog = super(TranslationDomain, self).__getitem__(name) text = catalog.queryMessage(msgid) if text is not None: break else: # If nothing found, delegate to a translation server higher up the # tree. domain = queryNextUtility(ITranslationDomain, self.domain) if domain is not None: return domain.translate(msgid, mapping, context, target_language, default=default) if default is None: default = msgid text = default # Now we need to do the interpolation return interpolate(text, mapping)
def testAbortTransactionWithErrorReportingUtility(self): # provide our fake error reporting utility sm = zapi.getGlobalSiteManager() sm.provideUtility(IErrorReportingUtility, ErrorReportingUtility()) class FooError(Exception): pass last_txn_info = self.db.undoInfo()[0] try: raise FooError except FooError: pass self.publication.handleException( self.object, self.request, sys.exc_info(), retry_allowed=False) # assert that the last transaction is NOT our transaction new_txn_info = self.db.undoInfo()[0] self.assertEqual(last_txn_info, new_txn_info) # instead, we expect a message in our logging utility error_log = zapi.getUtility(IErrorReportingUtility) self.assertEqual(len(error_log.exceptions), 1) error_info, request = error_log.exceptions[0] self.assertEqual(error_info[0], FooError) self.assert_(isinstance(error_info[1], FooError)) self.assert_(request is self.request)
def _logErrorWithErrorReportingUtility(self, object, request, exc_info): # Record the error with the ErrorReportingUtility self.beginErrorHandlingTransaction(request, object, 'error reporting utility') try: errUtility = zapi.getUtility(IErrorReportingUtility) # It is important that an error in errUtility.raising # does not propagate outside of here. Otherwise, nothing # meaningful will be returned to the user. # # The error reporting utility should not be doing database # stuff, so we shouldn't get a conflict error. # Even if we do, it is more important that we log this # error, and proceed with the normal course of events. # We should probably (somehow!) append to the standard # error handling that this error occurred while using # the ErrorReportingUtility, and that it will be in # the zope log. errUtility.raising(exc_info, request) transaction.commit() except: tryToLogException( 'Error while reporting an error to the Error Reporting utility' ) transaction.abort()
def execute_query(context, query): from zope.app import zapi from zope.app.rdb import queryForResults from zope.app.rdb.interfaces import IZopeDatabaseAdapter conn = zapi.getUtility(IZopeDatabaseAdapter, config.db_connection, context=context)() return queryForResults(conn, query)
def getEvaluationsTodo(context): """List of Content objects""" retSet = set([]) my_catalog = zapi.getUtility(ICatalog) if hasattr(context, "requirements"): requirements = removeAllProxies(context.requirements) if requirements is not None: for requirement in requirements: if type(requirement) is unicode: res = my_catalog.searchResults(oid_index=requirement) else: res = my_catalog.searchResults( oid_index=requirement.objectID) if len(res) > 0: startReq = iter(res).next() allObjReqs = [] allTmpObjReqs = getRequirementList(startReq) for req in allTmpObjReqs: # if req.validAsFirst and len(req) > 0: if len(req) > 0: pass else: allObjReqs.append(req) allObjEvaluations = getEvaluationsDone(context) alreadyCheckedReqs = [ ev[0] for ev in allObjEvaluations.items() ] retSet = retSet.union( set(allObjReqs).difference(alreadyCheckedReqs)) retList = list(retSet) retList.sort() return retList
def getDefaultPreferenceGroup(self, id=''): group = zapi.getUtility(interfaces.IPreferenceGroup, name=id) group = group.__bind__(self) default = DefaultPreferenceGroup(group, self) zope.interface.alsoProvides(default, IContainmentRoot) locate(default, self, 'preferences') return default
def getFlatDicts(self, maxdepth=0, row_state=None): """See zope.app.tree.interfaces.INode""" nodes = [] if row_state is None: row_state = [] encoder = zapi.getUtility(ITreeStateEncoder) if self.hasChildren() and len(row_state) > maxdepth: maxdepth = len(row_state) childNodes = self.getChildNodes() for node in childNodes: id = node.getId() expanded_nodes = self._expanded_nodes[:] if id in self._expanded_nodes: # if the node is already expanded, the toggle would # collapse it expanded_nodes.remove(id) row_state.append(not node is childNodes[-1]) else: # if it isn't expanded, the toggle would expand it expanded_nodes += [id] row_state.append(False) flatdict = { 'node': node, 'tree-state': encoder.encodeTreeState(expanded_nodes), 'row-state': row_state[:-1], 'last-level-node': node is childNodes[-1], } nodes.append(flatdict) child_nodes, maxdepth = node.getFlatDicts(maxdepth, row_state) nodes += child_nodes row_state.pop() return nodes, maxdepth
def addingInfo(self): """Return menu data. This is sorted by title. """ container = self.context menu_service = zapi.getService("BrowserMenu") result = [] for menu_id in (self.menu_id, 'zope.app.container.add'): if not menu_id: continue for item in menu_service.getMenu(menu_id, self, self.request): extra = item.get('extra') if extra: factory = extra.get('factory') if factory: factory = zapi.getUtility(IFactory, factory) if not checkFactory(container, None, factory): continue elif item['extra']['factory'] != item['action']: item['has_custom_add_view']=True result.append(item) result.sort(lambda a, b: cmp(a['title'], b['title'])) return result
def ensureMyIpNotAlreadyUsed(intfc): if intfc.netType == 'ethernet' and \ intfc.__context__ is not None and \ intfc.ipv4List is not None: my_catalog = zapi.getUtility(ICatalog) alreadyFound = [] # new Object if IHost.providedBy(intfc.__context__): for obj in my_catalog.searchResults(\ interface_ip_index=convertIpV4(intfc.ipv4List)): ifHost = obj.__parent__ ifString = u"%s/%s" % (ifHost.ikName, obj.ikName) alreadyFound.append(ifString) # edit Object if IInterface.providedBy(intfc.__context__): for obj in my_catalog.searchResults(\ interface_ip_index=convertIpV4(intfc.ipv4List)): # don't check object itself if obj.objectID != intfc.__context__.objectID: ifHost = obj.__parent__ ifString = u"%s/%s" % (ifHost.ikName, obj.ikName) alreadyFound.append(ifString) if len(alreadyFound) > 0: raise Invalid("The IP address already used in interface %s" % \ " ".join(alreadyFound))
def install(self): tool_names = self.request['selected'] for tool_name in tool_names: self.activeTool = zapi.getUtility(IToolConfiguration, tool_name) type_name = list(self.addingInfo())[0]['extra']['factory'] self.action(type_name) self.activeTool = None
def fileOpen(self): """will open a filehandle to the specific object """ objId = self.context.getObjectId() utilSmokePing = zapi.getUtility(IAdmUtilGeneratorSmokePing, '') self.fileName = utilSmokePing.pathConfigData + u'/Hosts/%s.cfg' % objId ParentGenSmokePing.fileOpen(self)
def processInpEQueues(self): my_catalog = zapi.getUtility(ICatalog) for senderOid in self.inpEQueues: inpQueue = self.inpEQueues[senderOid] while len(inpQueue) > 0: inpEvent = inpQueue.pull() processed = False for eventObj in self.values(): if IAdmUtilEvent.providedBy(eventObj): if (senderOid in eventObj.inpObjects) and \ (eventObj.objectID == inpEvent.oidEventObject): for receiverOid in eventObj.outObjects: for receiverObj in my_catalog.searchResults(\ oid_index=receiverOid): processed = True receiverObj.injectInpEQueue(inpEvent) if not processed: for oid in self.outEQueues: for receiverObj in my_catalog.searchResults(\ oid_index=oid): if (inpEvent.oidEventObject in \ receiverObj.getAllInpEventObjs()): processed = True receiverObj.injectInpEQueue(inpEvent) if not processed: inpEvent.stopit(self)
def testSkinPage(self): self.assertEqual(zapi.queryMultiAdapter((ob, request), name='test'), None) xmlconfig(StringIO(template % ( ''' <browser:layer name="zmi" /> <browser:skin name="zmi" layers="zmi" /> <browser:page name="test" class="zope.app.component.tests.views.VZMI" layer="zmi" for="zope.app.component.tests.views.IC" permission="zope.Public" attribute="index" /> <browser:page name="test" class="zope.app.component.tests.views.V1" for="zope.app.component.tests.views.IC" permission="zope.Public" attribute="index" /> ''' ))) v = zapi.queryMultiAdapter((ob, request), name='test') self.assert_(issubclass(v.__class__, V1)) zmi = zapi.getUtility(ISkin, 'zmi') v = zapi.queryMultiAdapter((ob, TestRequest(skin=zmi)), name='test') self.assert_(issubclass(v.__class__, VZMI))
def getPrincipalTransactions(self, first=0, last=-20, showall=False): context = None if not showall: context = self.context undo = zapi.getUtility(IUndoManager) return undo.getPrincipalTransactions(self.request.principal, context, first, last)
def allRequirementVocab(dummy_context): """Which locations are there """ terms = [] my_catalog = zapi.getUtility(ICatalog) try: reqOidList = [] complianceUtil = getUtility(IAdmUtilCompliance, name='AdmUtilCompliance') for (oid, oobj) in complianceUtil.items(): for req in getRequirementList(oobj): reqOidList.append(req.objectID) reqOidSet = set(reqOidList) for reqOid in reqOidSet: resultList = my_catalog.searchResults(oid_index=reqOid) if len(resultList) > 0: req = iter(resultList).next() if IRequirement.providedBy(req): parentReq = req.getParent() if parentReq is not None and \ IRequirement.providedBy(parentReq): newString = u"%s (%s)" % \ (req.ikName, parentReq.ikName) else: newString = req.ikName terms.append(\ SimpleTerm(req.objectID, str(req.objectID), newString)) return SimpleVocabulary(terms) except ComponentLookupError: return SimpleVocabulary([])
def change_eval_no(self): """ trigger an evaluation process """ requirementId = self.request.get('req_id', default=None) objectId = self.request.get('obj_id', default=None) my_catalog = zapi.getUtility(ICatalog) if objectId != None: obj = my_catalog.searchResults(oid_index=objectId) obj = iter(obj).next() else: obj = self.context evaluations = getEvaluationsDone(obj) if requirementId is not None \ and evaluations is not None: res = my_catalog.searchResults(oid_index=requirementId) if len(res) > 0: requirementObj = iter(res).next() principalId = self.request.principal.id.split('.')[1] pau_utility = queryUtility(IAuthentication) internalPrincipal = pau_utility['principals'][principalId] pfSystem = queryUtility(IScoreSystem, name="Comp_Pass/Fail") inpVal = 'Fail' evaluation = Evaluation(requirementObj, pfSystem, inpVal, internalPrincipal) evaluations.addEvaluation(evaluation) nextURL = self.request.get('nextURL', default=None) if nextURL is not None: return self.request.response.redirect(nextURL) else: return self.request.response.redirect('./@@details.html')
def sendPing(self): """ send ping request """ mq_utility = zapi.getUtility(IAdmUtilObjMQ) my_data = {'cmd': 'ping', 'nodename': unicode(self.getNodeName())} if self.isMaster() and not self.isSlave(): my_data['header'] = {'from_oid': self.objectID, 'from_ip': self.ipv4My, 'from_path': getPath(self), 'to_oid': self.oidSlave, 'to_ip': self.ipv4Slave, 'to_path': u"/++etc++site/default"+\ "/AdmUtilSupervisor" } print "sendPing: %s" % my_data mq_utility.sendPerMq(my_data) if self.isSlave() and not self.isMaster(): my_data['header'] = {'from_oid': self.objectID, 'from_ip': self.ipv4My, 'from_path': getPath(self), 'to_oid': self.oidMaster, 'to_ip': self.ipv4Master, 'to_path': u"/++etc++site/default"+\ "/AdmUtilSupervisor" } print "sendPing: %s" % my_data mq_utility.sendPerMq(my_data)
def action(self, type_name='', id=''): if not type_name: raise UserError("You must select the type of object to add.") if type_name.startswith('@@'): type_name = type_name[2:] if '/' in type_name: view_name = type_name.split('/', 1)[0] else: view_name = type_name if zapi.queryView(self, view_name, self.request) is not None: url = "%s/%s=%s" % (zapi.getView(self, "absolute_url", self.request), type_name, id) self.request.response.redirect(url) return if not self.contentName: self.contentName = id factory = zapi.getUtility(IFactory, type_name) content = factory() notify(ObjectCreatedEvent(content)) self.add(content) self.request.response.redirect(self.nextURL())
def addingInfo(self): """Return menu data. This is sorted by title. """ container = self.context menu_service = zapi.getService("BrowserMenu") result = [] for menu_id in (self.menu_id, 'zope.app.container.add'): if not menu_id: continue for item in menu_service.getMenu(menu_id, self, self.request): extra = item.get('extra') if extra: factory = extra.get('factory') if factory: factory = zapi.getUtility(IFactory, factory) if not checkFactory(container, None, factory): continue elif item['extra']['factory'] != item['action']: item['has_custom_add_view'] = True result.append(item) result.sort(lambda a, b: cmp(a['title'], b['title'])) return result
def action(self, type_name='', id=''): if not type_name: raise UserError("You must select the type of object to add.") if type_name.startswith('@@'): type_name = type_name[2:] if '/' in type_name: view_name = type_name.split('/', 1)[0] else: view_name = type_name if zapi.queryView(self, view_name, self.request) is not None: url = "%s/%s=%s" % ( zapi.getMultiAdapter((self, self.request), name=u"absolute_url"), type_name, id) self.request.response.redirect(url) return if not self.contentName: self.contentName = id factory = zapi.getUtility(IFactory, type_name) content = factory() notify(ObjectCreatedEvent(content)) self.add(content) self.request.response.redirect(self.nextURL())
def _registerClass(class_, meta_type, permission, addview, icon, global_): setattr(class_, 'meta_type', meta_type) permission_obj = zapi.getUtility(IPermission, permission) if icon: setattr(class_, 'icon', '++resource++%s' % icon) interfaces = tuple(implementedBy(class_)) info = { 'name': meta_type, 'action': addview and ('+/%s' % addview) or '', 'product': 'Five', 'permission': str(permission_obj.title), 'visibility': global_ and 'Global' or None, 'interfaces': interfaces, 'instance': class_, 'container_filter': None } Products.meta_types += (info, ) _register_monkies.append(class_) _meta_type_regs.append(meta_type)
def AllObjectInstances(dummy_context): """Which objects are there """ iid = zapi.getUtility(IIntIds, '') terms = [] for (oid, oobj) in iid.items(): if ISite.providedBy(oobj.object) or \ IIpNet.providedBy(oobj.object) or \ IHost.providedBy(oobj.object) or \ IInterface.providedBy(oobj.object) or \ IService.providedBy(oobj.object) or \ ISnmpValue.providedBy(oobj.object) or \ IEventLogic.providedBy(oobj.object): terms.append(\ SimpleTerm(oobj.object.objectID, str(oobj.object.objectID), oobj.object.getDcTitle())) for iface in [INotifierEmail]: my_util = queryUtility(iface) if my_util is not None: terms.append(\ SimpleTerm(my_util.objectID, str(my_util.objectID), my_util.getDcTitle())) return SimpleVocabulary(terms)
def AllObjectInstancesWithEventInputs(dummy_context): """Which objects are there """ iid = zapi.getUtility(IIntIds, '') terms = [] for (oid, oobj) in iid.items(): if ISite.providedBy(oobj.object) or \ IIpNet.providedBy(oobj.object) or \ IHost.providedBy(oobj.object) or \ IInterface.providedBy(oobj.object) or \ IService.providedBy(oobj.object) or \ ISnmpValue.providedBy(oobj.object) or \ IEventLogic.providedBy(oobj.object): inpEventNames = oobj.object.getAllInpEventNames().keys() if len(inpEventNames) > 0: for inpEventName in inpEventNames: myId = oobj.object.objectID + u'.' + inpEventName terms.append(\ SimpleTerm(myId, str(myId), oobj.object.getDcTitle() + \ u'->' + inpEventName)) for iface in [INotifierEmail]: my_util = queryUtility(iface) if my_util is not None: inpEventNames = my_util.getAllInpEventNames().keys() if len(inpEventNames) > 0: for inpEventName in inpEventNames: myId = my_util.objectID + u'.' + inpEventName terms.append(\ SimpleTerm(myId, str(myId), my_util.getDcTitle()+ u'->' + inpEventName)) return SimpleVocabulary(terms)
def testSkinnedPageView(self): self.assertEqual(zapi.queryMultiAdapter((ob, request), name='test'), None) xmlconfig(StringIO(template % ''' <browser:layer name="layer" /> <browser:skin name="skinny" layers="layer" /> <browser:pages for="*" class="zope.app.component.tests.views.V1" permission="zope.Public" > <browser:page name="index.html" attribute="index" /> </browser:pages> <browser:pages for="*" class="zope.app.component.tests.views.V1" layer="layer" permission="zope.Public" > <browser:page name="index.html" attribute="action" /> </browser:pages> ''' )) v = zapi.getMultiAdapter((ob, request), name='index.html') self.assertEqual(v(), 'V1 here') skinny = zapi.getUtility(ISkin, 'skinny') v = zapi.getMultiAdapter((ob, TestRequest(skin=skinny)), name='index.html') self.assertEqual(v(), 'done')
def moveObject(self, msgHeader, msgOldparent, msgNewparent, msgObjectOid): """ an object should be moved """ print "moveObject" print "msgHeader: %s" % msgHeader print "msgOldparent: %s" % msgOldparent print "msgNewparent: %s" % msgNewparent print "msgObjectOid: %s" % msgObjectOid my_catalog = zapi.getUtility(ICatalog) newParentObj = None if not msgNewparent: # in root-folder of slave res = my_catalog.searchResults(oid_index=msgHeader['from_oid']) if len(res) > 0: newParentObj = iter(res).next() else: res = my_catalog.searchResults(oid_index=msgNewparent) if len(res) > 0: newParentObj = iter(res).next() objToMove = None res = my_catalog.searchResults(oid_index=msgObjectOid) if len(res) > 0: objToMove = iter(res).next() if objToMove and newParentObj: mover = IObjectMover(objToMove) if mover.moveableTo(newParentObj): mover.moveTo(newParentObj) else: raise Exception, "object not movable to new parent"
def isOidInCatalog(arg_oid): """can arg_oid be found in Catalog""" if oidIsValid(arg_oid): my_catalog = zapi.getUtility(ICatalog) if len(my_catalog.searchResults(oid_index=arg_oid)) > 0: return True return False
def cbFun(self, transportDispatcher, transportDomain, transportAddress, wholeMsg): """ this callback function which will handle the snmptrap message from pysnmp stack """ while wholeMsg: msgVer = int(api.decodeMessageVersion(wholeMsg)) if api.protoModules.has_key(msgVer): pMod = api.protoModules[msgVer] else: print 'Unsupported SNMP version %s' % msgVer return reqMsg, wholeMsg = decoder.decode( wholeMsg, asn1Spec=pMod.Message(), ) print 'Notification message from %s:%s: ' % ( transportDomain, transportAddress ) reqPDU = pMod.apiMessage.getPDU(reqMsg) if reqPDU.isSameTypeWith(pMod.TrapPDU()): if SnmpdThread.database: conn = SnmpdThread.database.open() root = conn.root() root_folder = root['Application'] old_site = getSite() setSite(root_folder) my_catalog = zapi.getUtility(ICatalog) search_ip = pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint() search_ip_conv = convertIpV4(search_ip) for result in my_catalog.searchResults(\ interface_ip_index=search_ip_conv): parentObj = result.__parent__ snmpAdapter = ISnmptrapd(parentObj) snmpAdapter.triggered(reqPDU, msgVer, pMod) setSite(old_site) transaction.commit() conn.close() return wholeMsg
def testClearContents(self): user = PrincipalStub('srichter') annotationutil = zapi.getUtility(IPrincipalAnnotationUtility) annotations = annotationutil.getAnnotations(user) clipboard = IPrincipalClipboard(annotations) clipboard.clearContents() self.failUnless(clipboard.getContents() == ())
def _getFactory(self): # get factory or factory id factory = self.__dict__.get('_factory_or_id', self._factory_or_id) if type(factory) is str: # factory id return zapi.getUtility(IFactory, factory, self.context) else: return factory
def setCacheId(self, id): # Remove object from old cache old_cache_id = self.getCacheId() if old_cache_id and old_cache_id != id: cache = zapi.getUtility(ICache, old_cache_id) cache.invalidate(self._context) annotations = IAnnotations(removeAllProxies(self._context)) annotations[annotation_key] = id
def fileOpen(self): """will open a filehandle to the specific object """ #import pdb;pdb.set_trace() objId = self.context.getObjectId() utilNagios = zapi.getUtility(IAdmUtilGeneratorNagios, '') self.fileName = utilNagios.pathConfigData + u'/Hosts/%s.cfg' % objId ParentGenNagios.fileOpen(self)
def notifyAddedEvent(instance, event): logger.info(u"superclass.objcollect.notifyAddedEvent: event: %s" % event) raw_instance = removeSecurityProxy(instance) iid = zapi.getUtility(IIntIds, '') iid.register(raw_instance) connection = IConnection(raw_instance) oc = connection.root()['_oq_collection'] oc.index(raw_instance)
def eventInp_inward_relaying_shutdown(self, eventMsg=None): """ forward the event to all objects in this container through the signal filter """ if self.inEventMask(eventMsg, testHostGroup=False): print "HostVMwareEsx.eventInp_inward_relaying_shutdown() [%s]" % self.ikName esx_utility = zapi.getUtility(IAdmUtilEsxVim) if esx_utility and len(self.esxUuid) > 0: self.appendHistoryEntry("inward relaying shutdown") #esx_utility.getFilteredList(self.esxUuid) myParams = {\ 'cmd': 'find_entity_views', 'view_type': 'HostSystem', 'admUtilEsxVim': esx_utility, 'filter': {'name':self.esxUuid}, } myEsxDict = esx_utility.get_EsxVimObject_Dict(myParams, None) if not myEsxDict.has_key(self.esxUuid): print "dont find" return None myEsxObj = myEsxDict[self.esxUuid] myParams = {\ 'cmd': 'find_entity_views', 'view_type': 'VirtualMachine', 'admUtilEsxVim': esx_utility, 'begin_entity': myEsxObj.perlEsxObjRef, 'filter': {'runtime.powerState':'poweredOn'}, } myVmDict = esx_utility.get_EsxVimObject_Dict(myParams, None) my_catalog = zapi.getUtility(ICatalog) if myVmDict is not None and len(myVmDict) > 0: for vmName, vmObj in myVmDict.items(): #print "----->", vmObj.uuid res = my_catalog.searchResults( host_vmuuid_index=str(vmObj.uuid)) #import pdb #pdb.set_trace() if len(res) > 0: internalVmObj = list(res)[0] #print "ref-->", internalVmObj inst_event = MsgEvent(senderObj = self, oidEventObject = eventMsg.oidEventObject, logText = u"inward relaying by esx host '%s'"\ % self.ikName, targetFunctionName = 'shutdown') internalVmObj.injectInpEQueue(inst_event)
def getQueriables(self): """Returns an iteratable of queriables. Queriables are responsible for providing interfaces to search for principals by a set of given parameters (can be different for the various queriables). This method will walk up through all of the authentication utilities to look for queriables. >>> class DummyUtility1: ... implements(IAuthentication) ... __parent__ = None ... def __repr__(self): return 'dummy1' >>> dummy1 = DummyUtility1() >>> class DummyUtility2: ... implements(ISourceQueriables, IAuthentication) ... __parent__ = None ... def getQueriables(self): ... return ('1', 1), ('2', 2), ('3', 3) >>> dummy2 = DummyUtility2() >>> class DummyUtility3(DummyUtility2): ... implements(IAuthentication) ... def getQueriables(self): ... return ('4', 4), >>> dummy3 = DummyUtility3() >>> from zope.app.component.testing import testingNextUtility >>> testingNextUtility(dummy1, dummy2, IAuthentication) >>> testingNextUtility(dummy2, dummy3, IAuthentication) >>> temp = zapi.getUtility >>> zapi.getUtility = lambda iface: dummy1 >>> source = PrincipalSource() >>> list(source.getQueriables()) [(u'0', dummy1), (u'1.1', 1), (u'1.2', 2), (u'1.3', 3), (u'2.4', 4)] >>> zapi.getUtility = temp """ i = 0 auth = zapi.getUtility(IAuthentication) yielded = [] while True: queriables = ISourceQueriables(auth, None) if queriables is None: yield unicode(i), auth else: for qid, queriable in queriables.getQueriables(): # ensure that we dont return same yielded utility more # then once if queriable not in yielded: yield unicode(i)+'.'+unicode(qid), queriable yielded.append(queriable) auth = queryNextUtility(auth, IAuthentication) if auth is None: break i += 1
def __init__(self, context, interface, nameOnly=False): if nameOnly is not False: nameOnly = True if isinstance(interface, (str, unicode)): interface = zapi.getUtility(IInterface, interface) self.interface = interface utils = zapi.getUtilitiesFor(interface, context) self._terms = dict([(name, UtilityTerm(nameOnly and name or util, name)) for name, util in utils])
def add(self, obj, arg_request=None): """ add a dashboard item to the dashboard set """ if hasattr(obj, 'objectID'): my_catalog = zapi.getUtility(ICatalog) if len(my_catalog.searchResults(oid_index=obj.objectID)): return set.add(self, AdmUtilUserDashboardItem(obj, 'oid')) else: # object not in Catalog return set.add(self, AdmUtilUserDashboardItem(obj, 'path')) raise Exception, "wrong type for AdmUtilUserDashboardSet"
def get_thesaurus(self): """ return the content for a particular thesurus """ from zopyx.txng3.core.interfaces import IThesaurus try: from zope.app import zapi return zapi.getUtility(IThesaurus, self.request['id']) except ImportError: from zope.component import getUtility return getUtility(IThesaurus, self.request['id'])
def UserPreferences(context=None): """Adapts an ``ILocation`` object to the ``IUserPreferences`` interface.""" if context is None: context = zapi.getSiteManager() rootGroup = zapi.getUtility(IPreferenceGroup) rootGroup = rootGroup.__bind__(context) rootGroup.__name__ = '++preferences++' zope.interface.alsoProvides(rootGroup, IContainmentRoot) return rootGroup
def testLayer(self): self.assertEqual(zapi.queryMultiAdapter((ob, request), name='test'), None) xmlconfig(StringIO( template % '<browser:layer name="testlayer" />' )) testlayer = zapi.getUtility(ILayer, "testlayer") import zope.app.layers self.assert_(zope.app.layers.testlayer is testlayer)
def getCacheForObject(obj): """Returns the cache associated with `obj` or ``None``.""" adapter = ICacheable(obj, None) if adapter is None: return None cache_id = adapter.getCacheId() if not cache_id: return None return zapi.getUtility(ICache, cache_id)
def debugEventHistory(self, eventObject=None): if eventObject is not None: my_catalog = zapi.getUtility(ICatalog) print "debugEventHistory:" print "-" * 40 for entry in eventObject.transmissionHistory: for obj in my_catalog.searchResults(oid_index=entry): print " -> ", obj.getDcTitle() print "-" * 40
def __call__(self, *args): site = getObject(self.context) #sm = site.getSiteManager() setSite(site) # blogger product blogger = getUtility(IBloggerProduct) if not blogger.__installed__: blogger.install() # set wysiwyg editor configlet = getUtility(IContentEditorConfiglet) configlet.default_editor = 'tinymce' notify(ObjectModifiedEvent(configlet)) # set skin skintool = getUtility(ISkinTool) skintool.skin = 'quick.theme.sample' notify(ObjectModifiedEvent(skintool))
def test_registerUtilityOnUtilityRegistry(self): utils = zapi.getSiteManager().utilities dummy = DummyUtility() utils.registerUtility(IDummyUtility, dummy, 'dummy') self.assertEquals(zapi.getUtility(IDummyUtility, name='dummy'), dummy) self.assertEquals(list(zapi.getUtilitiesFor(IDummyUtility)), [('dummy', dummy)]) self.assertEquals(list(zapi.getAllUtilitiesRegisteredFor( IDummyUtility)), [dummy])
def test_bootstrapSusbcriber(self): bootStrapSubscriber(EventStub(self.db)) sessionBootstrapSubscriber(EventStub(self.db)) from zope.app.publication.zopepublication import ZopePublication from zope.app.component.hooks import setSite from zope.app import zapi cx = self.db.open() root = cx.root() root_folder = root[ZopePublication.root_name] setSite(root_folder) zapi.getUtility(IClientIdManager) zapi.getUtility(ISessionDataContainer) cx.close()
def test_registerUtilityOnUtilityRegistry(self): utils = zapi.getSiteManager().utilities dummy = DummyUtility() utils.registerUtility(IDummyUtility, dummy, 'dummy') self.assertEquals(zapi.getUtility(IDummyUtility, name='dummy'), dummy) self.assertEquals(list(zapi.getUtilitiesFor(IDummyUtility)), [('dummy', dummy)]) self.assertEquals( list(zapi.getAllUtilitiesRegisteredFor(IDummyUtility)), [dummy])