def initConnections(site, event): # this is called on first Plone traverse portal_quickinstaller = getToolByName(site, 'portal_quickinstaller') if portal_quickinstaller.isProductInstalled('collective.behavior.sql'): if not getAllUtilitiesRegisteredFor(ISQLConnectionsUtility): ftis = [ a for a in getAllUtilitiesRegisteredFor(IDexterityFTI) if 'collective.behavior.sql.behavior.behaviors.ISQLContent' in a.behaviors and getattr(a, 'sql_table', None) ] if ftis: for fti in ftis: if not ISQLTypeSettings.providedBy(fti): fti = ISQLTypeSettings(fti) try: initConnectionForFTI(fti) except: LOG.error('Unable to init connection for %s' % (fti.id)) gsm = getGlobalSiteManager() gsm.registerUtility(SQLConnectionsUtility(), ISQLConnectionsUtility) else: gsm = getGlobalSiteManager() gsm.registerUtility(SQLConnectionsUtility(), ISQLConnectionsUtility)
def initConnections(site, event): # this is called on first Plone traverse portal_quickinstaller = getToolByName(site, 'portal_quickinstaller') if portal_quickinstaller.isProductInstalled('collective.behavior.sql'): if not getAllUtilitiesRegisteredFor(ISQLConnectionsUtility): ftis = [a for a in getAllUtilitiesRegisteredFor(IDexterityFTI) if 'collective.behavior.sql.behavior.behaviors.ISQLContent' in a.behaviors and getattr(a, 'sql_table', None)] if ftis: for fti in ftis: initConnectionForFTI(fti) else: gsm = getGlobalSiteManager() gsm.registerUtility(SQLConnectionsUtility(), ISQLConnectionsUtility)
def availableWorkflows(context): utilities = getAllUtilitiesRegisteredFor(IPossibleNotificationTemplates) terms = [] for utility in utilities: terms.extend([SimpleTerm(value, value, title) for value, title in utility.names(context)]) return SimpleVocabulary(terms)
def moveIntIdSubscriber(ob, event): """A subscriber to ObjectMovedEvent Updates the stored path for the object in all the unique id utilities. """ utilities = tuple(getAllUtilitiesRegisteredFor(IIntIds)) if not utilities: return try: key = IKeyReference(ob, None) except NotYet: key = None # Register only objects that adapt to key reference if key is None: return # Update objects that adapt to key reference for utility in utilities: try: uid = utility.getId(ob) utility.refs[uid] = key utility.ids[key] = uid except KeyError: pass
def removeIntIdSubscriber(ob, event): """A subscriber to ObjectRemovedEvent Removes the unique ids registered for the object in all the unique id utilities. """ utilities = tuple(getAllUtilitiesRegisteredFor(IIntIds)) if not utilities: return try: key = IKeyReference(ob, None) except NotYet: key = None # Register only objects that adapt to key reference if key is None: return # Notify the catalogs that this object is about to be removed. notify(IntIdRemovedEvent(ob, event)) for utility in utilities: try: utility.unregister(key) except KeyError: pass
def __call__(self, context): ftis = getAllUtilitiesRegisteredFor(IDexterityFTI) if ISQLTypeSchemaContext.providedBy(context): ftis = [context.fti] else: ftis = [fti for fti in ftis if 'collective.behavior.sql.behavior.behaviors.ISQLContent' in fti.behaviors] return SimpleVocabulary([SimpleTerm(fti.__name__,fti.__name__, fti) for fti in ftis])
def __call__(self): self.request.stdin.seek(0) msg = email.message_from_file(self.request.stdin) # Get all registered mail routers. Sort by priority, then # call them until it is handled routers = getAllUtilitiesRegisteredFor(IMailRouter) routers.sort(lambda x, y: cmp(x.priority(), y.priority())) for router in routers: try: if router(aq_inner(self.context), msg): try: from plone.protect.interfaces import \ IDisableCSRFProtection except ImportError: pass else: alsoProvides(self.request, IDisableCSRFProtection) return 'OK: Message accepted' except PermissionError, e: errmsg = get_exception_message(e) self.request.response.setStatus(e.status) logmsg = get_exception_log_entry(e) logger.info(logmsg) return 'Fail: %s' % errmsg except (PermanentError, TemporaryError), e: errmsg = get_exception_message(e) self.request.response.setStatus(e.status) logmsg = get_exception_log_entry(e) logger.warn(logmsg) self.dump_mail() return 'Fail: %s' % errmsg
def __call__(self, context): providers = component.getAllUtilitiesRegisteredFor(IAllcontentStyleProvider) terms = [] for provider in providers: for value, title in provider.classes(): terms.append(vocabulary.SimpleTerm(value, None, title)) return vocabulary.SimpleVocabulary(terms)
def run(self): processor = self instructions = component.getAllUtilitiesRegisteredFor(IARMInstruction) instructionLog = open('ilog', 'w') while self.__running: inst = processor.fetch() processor.step() executed = False if inst == 0: break try: for instruction in instructions: if testInstruction(instruction, inst): instructionLog.write(str(type(instruction)) + '\n') instructionLog.flush() instruction.execute(processor, inst) executed = True break except exceptions.ProcessorException as ex: ex.preprocess(self) executed = True if not executed: print "Instruction not recognized %x" % inst self.__running = False
def _execute(self, cmd, args): name = yield db.get(self.context, '__name__') parent = yield db.get(self.context, '__parent__') submitter = IVirtualizationContainerSubmitter(parent) yield submitter.submit(IUndeployVM, name) @db.transact def finalize_vm(): ippools = db.get_root()['oms_root']['ippools'] ip = netaddr.IPAddress(self.context.ipv4_address.split('/')[0]) if ippools.free(ip): ulog = UserLogger(principal=cmd.protocol.interaction.participations[0].principal, subject=self.context, owner=self.context.__owner__) ulog.log('Deallocated IP: %s', ip) vm = traverse1(canonical_path(self.context)) if vm is not None: noLongerProvides(vm, IDeployed) alsoProvides(vm, IUndeployed) yield finalize_vm() vm_parameters = yield self.get_parameters() utils = getAllUtilitiesRegisteredFor(IPostUndeployHook) for util in utils: yield defer.maybeDeferred(util.execute, self.context, cmd, vm_parameters)
def _execute(self, cmd, args): name = yield db.get(self.context, '__name__') parent = yield db.get(self.context, '__parent__') submitter = IVirtualizationContainerSubmitter(parent) yield submitter.submit(IUndeployVM, name) @db.transact def finalize_vm(): ippools = db.get_root()['oms_root']['ippools'] ip = netaddr.IPAddress(self.context.ipv4_address.split('/')[0]) log.msg('Attempting to deallocate IP %s from the pools' % ip, system='undeploy-action') if ippools.free(ip): ulog = UserLogger(principal=cmd.protocol.interaction. participations[0].principal, subject=self.context, owner=self.context.__owner__) ulog.log('Deallocated IP: %s', ip) log.msg('Deallocated IP %s' % ip, system='ippool') vm = traverse1(canonical_path(self.context)) if vm is not None: noLongerProvides(vm, IDeployed) alsoProvides(vm, IUndeployed) yield finalize_vm() vm_parameters = yield self.get_parameters() utils = getAllUtilitiesRegisteredFor(IPostUndeployHook) for util in utils: yield defer.maybeDeferred(util.execute, self.context, cmd, vm_parameters)
def clear(self): for fti in getAllUtilitiesRegisteredFor(IDexterityFTI): self.invalidate(fti) request = getRequest() fti_cache = getattr(request, FTI_CACHE_KEY, None) if fti_cache is not None: delattr(request, FTI_CACHE_KEY)
def profiles(self): base_profiles = [] extension_profiles = [] # profiles available for install/uninstall, but hidden at the time # the Plone site is created not_installable = ["Products.CMFPlacefulWorkflow:CMFPlacefulWorkflow"] utils = getAllUtilitiesRegisteredFor(INonInstallable) for util in utils: not_installable.extend(util.getNonInstallableProfiles()) for info in profile_registry.listProfileInfo(): if info.get("type") == EXTENSION and info.get("for") in (IPloneSiteRoot, None): profile_id = info.get("id") if profile_id not in not_installable: if profile_id in self.default_extension_profiles: info["selected"] = "selected" extension_profiles.append(info) def _key(v): # Make sure implicitly selected items come first selected = v.get("selected") and "automatic" or "manual" return "%s-%s" % (selected, v.get("title", "")) extension_profiles.sort(key=_key) for info in profile_registry.listProfileInfo(): if info.get("type") == BASE and info.get("for") in (IPloneSiteRoot, None): base_profiles.append(info) return dict(base=tuple(base_profiles), default=_DEFAULT_PROFILE, extensions=tuple(extension_profiles))
def test_getAllUtilitiesRegisteredFor(self): class I21(I2): pass class Comp21(Comp): implements(I21) compbob = Comp('bob') comp21 = Comp21('21') comp21bob = Comp21('21bob') getService('Utilities').provideUtility(I2, comp) getService('Utilities').provideUtility(I21, comp21) getService('Utilities').provideUtility(I2, compbob, 'bob') getService('Utilities').provideUtility(I21, comp21bob, 'bob') comps = [comp, compbob, comp21, comp21bob] comps.sort() uts = list(component.getUtilitiesFor(I2)) uts.sort() self.assertEqual(uts, [('', comp), ('bob', compbob)]) uts = list(component.getAllUtilitiesRegisteredFor(I2)) uts.sort() self.assertEqual(uts, comps)
def possiblePermissionIds(self): """Get a vocabulary of Zope 3 permission ids """ permission_names = set() for permission in getAllUtilitiesRegisteredFor(IPermission): permission_names.add(permission.id) return sorted(permission_names)
def get_items(self): """ Look up all Dexterity FTIs via the component registry. (These utilities are created via an IObjectCreated handler for the DexterityFTI class, configured in plone.dexterity.) """ ftis = getAllUtilitiesRegisteredFor(IDexterityFTI) return [(fti.__name__, fti) for fti in ftis]
def addIntIdSubscriber(ob, event): """A subscriber to ObjectAddedEvent Registers the object added in all unique id utilities and fires an event for the catalogs. """ factorytool = getToolByName(ob, 'portal_factory', None) if factorytool is not None and factorytool.isTemporary(ob): # Ignore objects marked as temporary in the CMFPlone portal_factory # tool return utilities = tuple(getAllUtilitiesRegisteredFor(IIntIds)) if utilities: # assert that there are any utilites key = None try: key = IKeyReference(ob, None) except NotYet: pass # Register only objects that adapt to key reference if key is not None: for utility in utilities: utility.register(key) # Notify the catalogs that this object was added. notify(IntIdAddedEvent(ob, event))
def __call__(self): self.request.stdin.seek(0) msg = email.message_from_file(self.request.stdin) # Get all registered mail routers. Sort by priority, then # call them until it is handled routers = getAllUtilitiesRegisteredFor(IMailRouter) routers.sort(lambda x, y: cmp(x.priority(), y.priority())) for router in routers: try: if router(aq_inner(self.context), msg): try: from plone.protect.interfaces import \ IDisableCSRFProtection except ImportError: pass else: alsoProvides(self.request, IDisableCSRFProtection) return 'OK: Message accepted' except (PermanentError, TemporaryError), e: errmsg = get_exception_message(e) self.request.response.setStatus(e.status) logmsg = get_exception_log_entry(e) logger.warn(logmsg) self.dump_mail() return 'Fail: %s' % errmsg except Exception, e: # raise errmsg = get_exception_message(e) self.request.response.setStatus(500, reason=errmsg) logmsg = get_exception_log_entry(e) logger.error(logmsg) self.dump_mail() return 'Fail: %s' % errmsg
def AvailableFragments(context): # need to move import here since vocab module is used in interfaces from castle.cms.interfaces import IDashboard if isinstance(context, AcquirableDictionary): context = aq_parent(context) is_dash = IDashboard.providedBy(context) utils = getAllUtilitiesRegisteredFor(IFragmentsDirectory) all_frags = [] request = getRequest() for util in utils: if util.layer is not None: if not util.layer.providedBy(request): continue all_frags.extend(util.list()) terms = [SimpleVocabulary.createTerm('', '', 'Select fragment')] frags = [] for frag in set(all_frags): if (frag in _blacklist or (not is_dash and frag in _dashboard_available)): continue if frag[0] == '_' or frag[-1] == '_': continue frags.append(frag) frags.sort() for frag in frags: terms.append( SimpleVocabulary.createTerm( frag, frag, frag.capitalize().replace('-', ' '))) return SimpleVocabulary(terms)
def test_hidden_uninstall_profile(self): """Test if uninstall profile is listed as hidden""" ignore_profiles = [] utils = getAllUtilitiesRegisteredFor(INonInstallable) for util in utils: ignore_profiles.extend(util.getNonInstallableProfiles()) self.assertIn(u'collective.ifttt:uninstall', ignore_profiles)
def getMenuItems(self, context, request): """Return menu item entries in a TAL-friendly form.""" types = [] for type_ in getAllUtilitiesRegisteredFor(ITileType): if checkPermission(type_.add_permission, context): try: if request.traverseName( context, "@@" + type_.__name__): types.append(type_) except NotFound: continue types.sort(lambda x, y: cmp(x.title, y.title)) normalizer = getUtility(IIDNormalizer) return [{ 'title': type_.title, 'description': type_.description, 'action': "%s/@@add-tile?form.button.Create=1&type=%s"\ % (context.absolute_url(), type_.__name__), 'selected': False, 'icon': None, 'extra': { 'id': "add-%s" % normalizer.normalize(type_.__name__), 'separator': None, 'class': '' }, 'submenu': None, } for type_ in types]
def getImportFormatNames(self, with_unavailables=False, with_disabled=False): """ returns a list with the names of the supported import formats """ parsers = component.getAllUtilitiesRegisteredFor(IBibliographyParser) return [parser.getFormatName() \ for parser in parsers if (parser.isAvailable() or with_unavailables) and (parser.isEnabled() or with_disabled) ]
def unindexDocSubscriber(event): """A subscriber to IntIdRemovedEvent""" ob = event.object for cat in component.getAllUtilitiesRegisteredFor(ICatalog, context=ob): id = component.getUtility(IIntIds, context=cat).queryId(ob) if id is not None: cat.unindex_doc(id)
def is_product_installable(self, product_id, allow_hidden=False): """Does a product have an installation profile? :param allow_hidden: Allow installing otherwise hidden products. In the UI this will be False, but you can set it to True in for example a call from plone.app.upgrade where you want to install a new core product, even though it is hidden for users. :type allow_hidden: boolean :returns: True when product is installable, False otherwise. :rtype: boolean """ if not allow_hidden: not_installable = [] utils = getAllUtilitiesRegisteredFor(INonInstallable) for util in utils: gnip = getattr(util, "getNonInstallableProducts", None) if gnip is None: continue not_installable.extend(gnip()) if product_id in not_installable: return False profile = self.get_install_profile(product_id, allow_hidden=allow_hidden) if profile is None: return try: self.ps.getProfileDependencyChain(profile["id"]) except KeyError as e: # Don't show twice the same error: old install and profile # oldinstall is test in first in other methods we may have an extra # 'Products.' in the namespace. # # TODO: # 1. Make sense of the previous comment. # 2. Possibly remove the special case for 'Products'. # 3. Make sense of the next five lines: they remove 'Products.' # when it is there, and add it when it is not??? checkname = product_id if checkname.startswith("Products."): checkname = checkname[9:] else: checkname = "Products." + checkname if checkname in self.errors: if self.errors[checkname]["value"] == e.args[0]: return False # A new error is found, register it self.errors[product_id] = dict( type=_("dependency_missing", default="Missing dependency"), value=e.args[0], product_id=product_id, ) else: self.errors[product_id] = dict( type=_("dependency_missing", default="Missing dependency"), value=e.args[0], product_id=product_id, ) return False return True
def moveIntIdSubscriber(ob, event): """A subscriber to ObjectMovedEvent Updates the stored path for the object in all the unique id utilities. """ if IObjectRemovedEvent.providedBy(event) or \ IObjectAddedEvent.providedBy(event): return utilities = tuple(getAllUtilitiesRegisteredFor(IIntIds)) if utilities: key = None try: key = IKeyReference(ob, None) except NotYet: # @@ temporary fix pass # Update objects that adapt to key reference if key is not None: for utility in utilities: try: uid = utility.getId(ob) utility.refs[uid] = key utility.ids[key] = uid except KeyError: pass
def execute(self, proc, inst): shifter_operand = 0 shifter_carry_out = 0 if not checkCondition(proc, inst): return S = utils.getBits(inst, 20) I = utils.getBits(inst, 25) rd = utils.getBits(inst, 12, 4) rd = 'r' + str(rd) rn = utils.getBits(inst, 16, 4) rn = 'r' + str(rn) rdVal = getattr(proc, rd) rnVal = getattr(proc, rn) modes = component.getAllUtilitiesRegisteredFor(IARMDPAddressingMode) for mode in modes: if testInstruction(mode, inst): shifter_operand, shifter_carry_out = mode.getVal(proc, inst) break setattr(proc, rd, rnVal ^ shifter_operand) if S == 1 and rd == 'r15': try: proc.cpsr = proc.spsr except: print "UNPREDICTABLE" elif S == 1: proc.setStatusFlag('N', utils.getBits(getattr(proc, rd), 31)) proc.setStatusFlag('Z', int(getattr(proc, rd) == 0)) proc.setStatusFlag('C', shifter_carry_out)
def execute(self, proc, inst): shifter_operand = 0 shifter_carry_out = 0 if not checkCondition(proc, inst): return rn = utils.getBits(inst, 16, 4) rn = 'r' + str(rn) rnVal = getattr(proc, rn) modes = component.getAllUtilitiesRegisteredFor(IARMDPAddressingMode) for mode in modes: if testInstruction(mode, inst): shifter_operand, shifter_carry_out = mode.getVal(proc, inst) break rnBitset = Bitset(rnVal, 32) shifterBitset = Bitset(shifter_operand, 32) alu_out, carry = rnBitset + shifter_operand if utils.getBits(rnVal, 31) == 0 and utils.getBits(int(result), 31) == 1: v = 1 else: v = 0 proc.setStatusFlag('N', utils.getBits(int(alu_out), 31)) proc.setStatusFlag('Z', int(int(alu_out) == 0)) proc.setStatusFlag('C', carry) proc.setStatusFlag('V', v)
def fields(self): terms = [] for reg in getAllUtilitiesRegisteredFor(IRecipientSourceRegistration): if not reg.enabled: continue terms.append(schema.vocabulary.SimpleTerm( value = reg, token = reg.name, title = reg.title, )) # if only one source, redirect to it if len(terms) <= 1: self._redirect_url = '%s/@@add-recipient?form.widgets.recipient_type=%s' % (self.context.absolute_url(), terms[0].value.name) return field.Fields() vocab = schema.vocabulary.SimpleVocabulary(terms) fields = field.Fields(schema.Choice( __name__ = 'recipient_type', title = _(u'Recipient type'), description = _(u'Select the type of recipient you want to add.'), vocabulary = vocab, default = vocab.by_token['standard'].value, )) fields['recipient_type'].widgetFactory = DescriptiveRadioWidget return fields
def execute(self, proc, inst): if not utils.checkCondition(proc, inst): return modes = component.getAllUtilitiesRegisteredFor(IARMLSMAddressingMode) for mode in modes: if utils.testInstruction(mode, inst): start_address, end_address = mode.getVal(proc, inst) break register_list = Bitset(utils.getBits(inst, 0, 16), 32) address = start_address for i in range(15): if register_list[i]: setattr(proc, 'r' + str(i), proc.readAddr(address, 4)) address += 4 if register_list[15]: value = proc.readAddr(address, 4) proc.pc = value & 0xFFFFFFFE address += 4 if end_address != address - 4: raise exceptions.DataAbort()
def initConnections(site, event): # this is called on first Plone traverse portal_quickinstaller = getToolByName(site, 'portal_quickinstaller') if portal_quickinstaller.isProductInstalled('collective.odoo.pas'): if not getAllUtilitiesRegisteredFor(interfaces.IOdooPasUtility): if getattr(interfaces.IOdooPasSettings(site, None), 'dbname'): registerOdooConnection(site)
def getAvailableConditions(context, eventType): conditions = getAllUtilitiesRegisteredFor(IRuleCondition) return [ c for c in conditions if (c.event is None or eventType.isOrExtends(c.event)) and ( c.for_ is None or c.for_.providedBy(context)) ]
def __call__(self, item=None): if item is not None: return self.serialize_item(item) json = super(DexterityTypesControlpanelSerializeToJson, self).__call__() json["items"] = [] portal = getSite() portal_url = portal.absolute_url() ftis = getAllUtilitiesRegisteredFor(IDexterityFTI) for fti in ftis: name = fti.__name__ json["items"].append({ "@id": "{}/@controlpanels/dexterity-types/{}".format( portal_url, name), "@type": name, "meta_type": fti.meta_type, "id": name, "title": fti.Title(), "description": fti.Description(), "count": self.count(name), }) return json
def js_libs(self): """ JS libs """ res = [] for util in getAllUtilitiesRegisteredFor(IVisualizationEditResources): res.extend(util.extjs) return res
def getAvailableActions(context, eventType): actions = getAllUtilitiesRegisteredFor(IRuleAction) return [ a for a in actions if (a.event is None or eventType.isOrExtends(a.event)) and ( a.for_ is None or a.for_.providedBy(context)) ]
def execute(self, proc, inst): if not utils.checkCondition(proc, inst): return modes = component.getAllUtilitiesRegisteredFor(IARMLSMAddressingMode) for mode in modes: if utils.testInstruction(mode, inst): start_address, end_address = mode.getVal(proc, inst) break register_list = Bitset(utils.getBits(inst, 0, 16), 32) address = start_address print "Entra" for i in range(16): if register_list[i]: print i, getattr(proc, 'r' + str(i)) proc.saveAddr(address, getattr(proc, 'r' + str(i))) address += 4 print "Sale" if end_address != address - 4: raise exceptions.DataAbort()
def css_libs(self): """ CSS libs """ res = [] for util in getAllUtilitiesRegisteredFor(IVisualizationViewResources): res.extend(util.css) return res
def addPloneSiteForm(dispatcher): """ Wrap the PTF in 'dispatcher'. """ wrapped = PageTemplateFile('addSite', WWW_DIR).__of__(dispatcher) base_profiles = [] extension_profiles = [] not_installable = [] utils = getAllUtilitiesRegisteredFor(INonInstallable) for util in utils: not_installable.extend(util.getNonInstallableProfiles()) for info in profile_registry.listProfileInfo(): if info.get('type') == EXTENSION and \ info.get('for') in (IPloneSiteRoot, None): if info.get('id') not in not_installable: extension_profiles.append(info) for info in profile_registry.listProfileInfo(): if info.get('type') == BASE and \ info.get('for') in (IPloneSiteRoot, None): if info.get('id') not in not_installable: base_profiles.append(info) return wrapped(base_profiles=tuple(base_profiles), extension_profiles=tuple(extension_profiles), default_profile=_DEFAULT_PROFILE)
def _get_profile(self, product_id, name, strict=True, allow_hidden=False): """Return profile with given name. Also return None when no profiles are found at all. :param product_id: id of product/package. For example CMFPlone or plone.app.registry. :type product_id: string :param name: name of profile. Usually 'default' or 'uninstall'. :type name: string :param strict: When True, return None when name is not found. Otherwise fall back to the first profile. :type strict: boolean :param allow_hidden: Allow getting hidden profile. A non hidden profile is always preferred. :type allow_hidden: boolean :returns: True on success, False otherwise. :rtype: boolean """ profiles = self._install_profile_info(product_id) if not profiles: return utils = getAllUtilitiesRegisteredFor(INonInstallable) hidden = [] for util in utils: gnip = getattr(util, 'getNonInstallableProfiles', None) if gnip is None: continue hidden.extend(gnip()) # We have prime candidates that we prefer, and have hidden candidates # in case allow_hidden is True. prime_candidates = [] hidden_candidates = [] for profile in profiles: profile_id = profile['id'] profile_id_parts = profile_id.split(':') if len(profile_id_parts) != 2: logger.error("Profile with id '%s' is invalid." % profile_id) continue if allow_hidden and profile_id in hidden: if profile_id_parts[1] == name: # This will especially be true for uninstall profiles, # which are usually hidden. return profile hidden_candidates.append(profile) continue if profile_id_parts[1] == name: return profile prime_candidates.append(profile) if strict: return if prime_candidates: # QI used to pick the first profile. # Return the first profile after all. return prime_candidates[0] if allow_hidden and hidden_candidates: # Return the first hidden profile. return hidden_candidates[0]
def createAccount(obj, event): # Transitioning from pending to created if event.new_state.id == 'created': # Look up utilities, call them to do actual registration handlers = getAllUtilitiesRegisteredFor(IRegistrationHandler) for handler in handlers: handler.register(obj)
def getExportFormatNames(self, with_unavailables=False, with_disabled=False): """ returns a list with the names of the supported export formats """ utils = component.getAllUtilitiesRegisteredFor(IBibliographyRenderer) return [ renderer.__name__ for renderer in utils if (renderer.available or with_unavailables) and (self.isRendererEnabled(renderer.__name__) or with_disabled) ]
def reply(self): result = {"types": {}, "behaviors": {}} for fti in getAllUtilitiesRegisteredFor(ITypeInformation): try: fields = self._fields(fti.lookupSchema()) except (AttributeError, ValueError): continue if fields: result["types"][fti.getId()] = fields for registration in getAllUtilitiesRegisteredFor(IBehavior): if registration.name in result["behaviors"]: continue fields = self._fields(registration.interface) if fields: result["behaviors"][registration.name] = fields return result
def indexDocSubscriber(event): """A subscriber to IntIdAddedEvent""" ob = event.object if INoAutoIndex.providedBy(ob): return for cat in component.getAllUtilitiesRegisteredFor(ICatalog, context=ob): id = component.getUtility(IIntIds, context=cat).getId(ob) cat.index_doc(id, ob)
def getShell(): print 'creating shell' shell = telnet.ShellFactory() shell.username = getUtility(IConfiguration).get('shell', 'username') shell.password = getUtility(IConfiguration).get('shell', 'password') for k, v in getAllUtilitiesRegisteredFor(IShellVar): shell.namespace[str(k)] = v return shell
def _getRenderer(self, format): utils = component.getAllUtilitiesRegisteredFor(IBibliographyRenderer) for renderer in utils: if renderer.available and renderer.enabled: if format.lower() == renderer.__name__.lower(): return renderer elif format.lower() == renderer.target_format.lower(): return renderer return None
def update(self, username): auth = getUtility(IAuthentication) p = auth.getPrincipal(username) if p is None: log.warning( 'User not found in authentication: %s. Possibly a stale profile record.', username) return if username is None: username = p.id billable_group = get_config().getstring('auth', 'billable_group', 'users') if billable_group not in p.groups: log.debug('User %s is not part of billable group: %s', username, billable_group) return if type(username) not in (str, unicode): username = username.id user_computes = self.get_computes(username) user_stats = { 'num_cores_total': 0, 'diskspace_total': 0, 'memory_total': 0, 'vm_count': len(user_computes) } for compute in user_computes: try: # only account for cores and RAM of the running VMs if compute.state == u'active': user_stats['num_cores_total'] += compute.num_cores user_stats['memory_total'] += compute.memory or 0 user_stats['diskspace_total'] += compute.diskspace.get( u'total') or 0 except Exception: log.error('Error collecting stats from %s', compute, exc_info=sys.exc_info()) user_stats['timestamp'] = datetime.now() user_stats['credit'] = self.get_credit(username) self.save_vm_stats(username, user_stats) loggers = getAllUtilitiesRegisteredFor(IUserStatisticsLogger) for logger in loggers: logger.log(username, user_stats) log.debug('Statistics update logged for %s', username) return user_stats
def render(self): _files = {} file_data = self.request.form['files[]'] file_name = file_data.filename file_name = file_name.split('/')[-1].split('\\')[-1] # bug in old IE file_name = clean_file_name(file_name) _file_name = file_name + '_chunk' logger.info('Staring chunk: ' + _file_name) content_range = self.request['HTTP_CONTENT_RANGE'] content_type = mimetypes.guess_type(file_name)[0] or "" for mutator in getAllUtilitiesRegisteredFor(IFileMutator): file_name, file_data, content_type = mutator( file_name, file_data, content_type) if content_range: """ don't do anything special if we only have one chunk """ max_size = int(content_range.split('/')[-1]) if file_data: if _file_name in self.context.objectIds(): cf = self.context[_file_name] cf.add_chunk(file_data, file_name, content_range, graceful=True) else: self.context.invokeFactory('ChunkedFile', _file_name) cf = self.context[_file_name] cf.title = file_name cf.add_chunk(file_data, file_name, content_range) size = cf.currsize() url = cf.absolute_url() _files[file_name] = { 'name': file_name, 'size': size, 'url': url } if size == max_size: if not QUIET_UPLOAD: logger.info('Starting chunk merger') nf_url = merge_chunks(self.context, cf, file_name) _files[file_name]['url'] = nf_url else: nf = make_file(file_name, self.context, file_data) primary_field = IPrimaryFieldInfo(nf) _files[file_name] = { 'name': file_name, 'size': human_readable_size(primary_field.value.size), 'url': nf.absolute_url() } self.request.response.setHeader('Content-Type', 'application/json') return json.dumps({'files': list(_files.values())})
def getLocalRegistrations(self): layers = getAllUtilitiesRegisteredFor(ILocalBrowserLayerType) components = getSiteManager(self.context) for reg in components.registeredAdapters(): if (len(reg.required) in (2, 4, 5) and (reg.required[1].isOrExtends(IBrowserRequest) or reg.required[1] in layers) and ITTWViewTemplate.providedBy(reg.factory)): yield reg
def isProductInstallable(self, productname): """Asks wether a product is installable by trying to get its install method or an installation profile. """ not_installable = [] utils = getAllUtilitiesRegisteredFor(INonInstallable) for util in utils: not_installable.extend(util.getNonInstallableProducts()) if productname in not_installable: return False try: self.getInstallMethod(productname) return True except AttributeError: # this means it has no install method, go on from here pass profiles = self.getInstallProfiles(productname) if not profiles: return False setup_tool = getToolByName(self, 'portal_setup') try: # XXX Currently QI always uses the first profile setup_tool.getProfileDependencyChain(profiles[0]) except KeyError, e: self._init_errors() # Don't show twice the same error: old install and profile # oldinstall is test in first in other methods we may have an # extra 'Products.' in the namespace checkname = productname if checkname.startswith('Products.'): checkname = checkname[9:] else: checkname = 'Products.' + checkname if checkname in self.errors: if self.errors[checkname]['value'] == e.args[0]: return False # A new error is found, register it self.errors[productname] = dict( type=_( u"dependency_missing", default=u"Missing dependency" ), value=e.args[0], productname=productname ) else: self.errors[productname] = dict( type=_( u"dependency_missing", default=u"Missing dependency" ), value=e.args[0], productname=productname ) return False
def objs(self): """List of Content objects""" objWithPermisson = [] allObj = getAllUtilitiesRegisteredFor(ISuperclass) for obj in allObj: myAdapter = zapi.queryMultiAdapter((obj, self.request), name='details.html') if myAdapter is not None and canAccess(myAdapter, 'render'): objWithPermisson.append(obj) return objWithPermisson
def get_menu_modifiers(self): results = [] utils = getAllUtilitiesRegisteredFor(IToolbarModifier) utils.sort(key=lambda u: u.order) for util in reversed(utils): if util.layer is not None: if not util.layer.providedBy(self.request): continue results.append(util(self.real_context, self.request)) return results