class Adapts(object): implements(IA) adapts(INoA) def __init__(self, context): self.context = context def show(self, name = 'shane'): self.context.say(name)
class UniquelyIdentified(object): implements(IUniquelyIdentified) adapts(Interface) def get_identifier(obj, default=None, create=False): uuid = MetaDataProvider.get_subject_meta(obj, 'identifier', default) if uuid is None and create: uuid = UniquelyIdentified(obj).identifier return uuid get_identifier = staticmethod(get_identifier) def get_identified(uuid, default=None): return identifier_registry.get(uuid, default) get_identified = staticmethod(get_identified) def __new__(klass, context): adapter = super(UniquelyIdentified, klass).__new__(klass) meta_context = IMetaDataProvider(context) uuid = meta_context.setdefault_meta('identifier', UUID()) identifier_registry.setdefault(uuid, context) adapter.initialize(meta_context) return adapter def initialize(self, context): self.context = context def __get_id(self): return self.context['identifier'] def __set_id(self, id): self.context['identifier'] = id identifier = property(__get_id, __set_id)
class RSS2AlarmEventItem(object): implements(IRSS2ItemElement) adapts(IAlarmEvent) def __init__(self, alarmevent): self.alarmevent = alarmevent super(RSS2AlarmEventItem, self).__init__() def as_item(self): event = self.alarmevent item = rss.Item() alarm = event.source priority = alarm.priority if not priority: priority = 'Normal' title = "%s (%s): %s" % (alarm.name, priority, event.state.upper()) link = "http://%s/syndication?guid=%s" % (event.origin, event.GUID) item.title = rss.Title(title) item.link = rss.Link(link) item.guid = rss.Guid(event.GUID) item.pub_date = rss.PubDate(event.created()) description = alarm.description for change in event.get_audit(): description += '<br />\n%s. ' % change.tostring() item.description = rss.Description(tools.escape_html(description)) item.source = rss.Source(event.origin, "http://%s/syndication" % event.origin) eventcategory = rss.Category('Event') alarmcategory = rss.Category('Alarm') item.categories.append(eventcategory) item.categories.append(alarmcategory) return item def render(self): return str(self.as_item())
class FaultEvent(Event): implements(IFaultEvent) TYPE = 'Fault' def __init__(self, source, title, faulttype, timestamp, description, origin = None, guid = None): super(FaultEvent, self).__init__(source, origin, guid, timestamp) self.lifetime = None self.closetime = None self.title = title self.faulttype = faulttype self.description = description def tostring(self): message = '%s Fault Event "%s" at %s: %s' return message % (self.faulttype.upper(), self.title, time.ctime(self.timestamp), self.description) def is_states(self, state): if state.lower() == 'closed' and self.timeout is not None: if time.time() > (self.timestamp + self.timeout): print 'Fault %s returning closed.' % self.title return True else: return False return False def set_timeout(self, timeout): self.lifetime = timeout self.closetime = time.time() + timeout
class PickleTransformationWriter(object): implements(ITransformationWriter) def __init__(self, instance=None): self.manager = None self._instances = [] if instance is not None: self._instances.append(instance) self._sio = cStringIO.StringIO() self._pickler = cPickle.Pickler(self._sio, 1) self._pickler.persistent_id = self._persistent_id def set_manager(self, manager): self.manager = manager def _persistent_id(self, instance): if self._writing is instance: return None oid = self.manager.get_oid(instance) if oid is not None: self._instances.append(instance) return oid def write(self, instance): pickleable = IPickleable(instance) print 'IPickles(%s) -> %s' % (instance.name, pickleable) self._writing = pickleable self._sio.seek(0) self._pickler.clear_memo() self._pickler.dump(pickleable.write_object()) self._sio.truncate() return self._sio.getvalue() def __iter__(self): return CollectionIterator(self._instances, 1)
class MessageQueue(MessageChannel): implements(IMessageQueue) def __init__(self, *args, **kw): self.iterindex = 0 self.listeners = list() super(MessageQueue, self).__init__(*args, **kw) def attach(self, listener): self.listeners.append(listener) self.notify() def detach(self, listener): self.listeners.remove(listener) def subscribe(self, channel): listener = IMessageListener(channel) self.attach(listener) def unsubscribe(self, channel): # Adapters provide __eq__ so comparison will work. listener = IMessageListener(channel) self.detach(listener) def iterlisteners(self): while self.listeners: try: listener = self.listeners[self.iterindex] except IndexError: self.iterindex = 0 else: yield listener self.iterindex += 1 def notify(self): for listener in self.iterlisteners(): message = self.receive(False) if not message: break listener.handle_message(message)
class TransformationWriterChain(list): implements(ITransformationWriter) def write(self, transformation): for writer in self: transformation = writer.write(transformation) return transformation
class TransformationReaderChain(list): implements(ITransformationReader) def read(self, transformation): for reader in self: transformation = reader.read(transformation) return transformation
class HTTPPostTransporter(CompositeNode, http_post_transporter.HTTPPostTransporter): implements(ITransporter) def __init__(self, *args): CompositeNode.__init__(self, *args) http_post_transporter.HTTPPostTransporter.__init__(self) def configure(self, config): http_post_transporter.HTTPPostTransporter.configure(self, config) self.setattr('transport_type', 'http-post') CompositeNode.configure(self, config) def configuration(self): config = http_post_transporter.HTTPPostTransporter.configuration(self) config.update(CompositeNode.configuration(self)) for attrname in [ 'post_url', 'chunked_data', 'debug', 'content_type', 'timeout', 'user', 'password' ]: config.setdefault(attrname, '') config['transport_type'] = self.getattr('transport_type') return config def is_setup(self): return hasattr(self, 'post_url')
class PeriodicDriverManager(CompositeNode): implements(IPeriodicDriverManager) ## # Needed because children may end up being hybrids between # old-style nodes and neode-style nodes. def _add_child(self, child): pass
class LeafNodeDOM(object): implements(IDOMish) adapts(ILeafNode) def __init__(self, tag): self.tag = tag return def getAttribute(self, name): if hasattr(self.tag,name): return getattr(self.tag,name) elif hasattr(self.tag,'attr_dict'): if self.tag.attr_dict.has_key(name): ugh = self.tag.attr_dict[name].split('"') if len(ugh) == 3: return ugh[1] return None def setAttribute(self, name, value): if hasattr(self.tag,name): return setattr(self.tag,name,value) elif hasattr(self.tag,'attr_dict'): self.tag.attr_dict[name] = ' %s="%s"' % (name, value) return None def getTagById(self, id): my_id = self.getAttribute('id') if my_id == id: return self.tag return None
class Storage(object): implements(IStorage) def set_manager(self, manager): self.manager = manager def load_records(self, oids): return map(self.load_record, oids) def store_records(self, recordmap): for oid, record in recordmap.items(): self.store_record(oid, record) def generate_oid(self): return str(UUID()) def has_oid(self, oid): try: self.load_record(oid) except: return False else: return True def load_record(self, oid): raise Exception('Not implemented') def store_record(self, oid, record): raise Exception('Not implemented') def close(self): raise Exception('Not implemented') def commit(self): pass
class ExtendedInspectableAdapter(object): implements(IExtendedInspectable) adapts(IInspectable) def __init__(self, inspectable): self.context = inspectable def getattr(self, name): return self.context.getattr(name) def hasattr(self, name): return self.context.has_attr(name) def has_method(self, name): return self.context.has_method(name) def get_method(self, name): return self.context.get_method(name) def getattrs(self, names, conversions=[]): if not conversions: conversions = [None] * len(names) return map(self.getattr, names, conversions) def hasattrs(self, names): return map(self.hasattr, names) def has_methods(self, names): return map(self.has_method, names) def get_methods(self, names): return map(self.get_method, names)
class FileChild(NodeLike): implements(IConfigurableNode) security = SecurityInformation.from_default() security.protect_get('openread', 'View') security.protect_get('openwrite', 'Configure') security.disallow_set('name') security.disallow_set('parent_path') security.disallow_set('url') secured_by(security) def __init__(self, manager, path, name): self.manager = manager self.parent_path = path self.name = name self._path = self.manager.makepath(self.parent_path, self.name) def openread(self, mode='rb'): if '+' in mode or 'w' in mode: raise ValueError('Cannot pass "w" or "+" to openread.') return self.manager._filesystem.open(self._path, mode) def openwrite(self, mode='wb'): return self.manager._filesystem.open(self._path, mode) def prune(self): return self.manager._filesystem.unlink(self._path)
class OGCompositeNeodeAdapter(OGConfigurableNeodeAdapter): implements(ICompositeNode) adapts(IOGCompositeNode) def add_child(self, child): self.node._add_child(child) return path.join(self.url, child.name) def remove_child(self, childname): if not isinstance(childname, str): childname = childname.name del (self.node._children[childname]) def children_nodes(self, *args, **kw): nodes = self.node.children_nodes(*args, **kw) nodes = map(IConfigurableNode, nodes) return nodes def get_child(self, name, *args, **kw): node = self.node.get_child(name, *args, **kw) return IConfigurableNode(node) def as_node(self, *args): node = self.node.as_node(*args) return IConfigurableNode(node)
class OGConfigurableNeodeAdapter(object): implements(IConfigurableNode) adapts(IOGConfigurableNode) nodespace = None def __init__(self, node): directly_provides(self, *tuple(provided_by(node))) self.__dict__['node'] = node def get_nodespace(self): return OGConfigurableNeodeAdapter.nodespace def get_url(self): return as_node_url(self.node) url = property(get_url) absolute_url = url def __get_parent(self): parent = self.node.parent if parent is not None: parent = IConfigurableNode(parent) return parent parent = property(__get_parent) def __getattr__(self, name): return getattr(self.node, name) def __setattr__(self, name, value): if name == '__provides__': return super(OGConfigurableNeodeAdapter, self).__setattr__(name, value) return setattr(self.node, name, value)
class SMTPTransporter(CompositeNode, smtp_transporter.SMTPTransporter): implements(ITransporter) def __init__(self, *args): CompositeNode.__init__(self, *args) smtp_transporter.SMTPTransporter.__init__(self) def configure(self, config): config.setdefault('subtype', 'html') smtp_transporter.SMTPTransporter.configure(self, config) self.setattr('transport_type', 'smtp') CompositeNode.configure(self, config) def configuration(self): config = smtp_transporter.SMTPTransporter.configuration(self) config.update(CompositeNode.configuration(self)) for attrname in [ 'debug', 'host', 'port', 'authenticate', 'username', 'password', 'sender', 'recipients', 'subject', 'timeout', 'custom_domain', 'subtype', 'as_attachment' ]: config.setdefault(attrname, '') config['transport_type'] = self.getattr('transport_type') return config def is_setup(self): return (hasattr(self, 'host') and hasattr(self, 'recipients') and len(self.host.strip()) and len(self.recipients))
class UserEvent(Event): implements(IUserEvent) description = 'Generic User Event' def __init__(self, user, origin=None, guid=None): self.user = user super(UserEvent, self).__init__(user, origin, guid)
class RSS2FaultEventItem(object): implements(IRSS2ItemElement) adapts(IFaultEvent) def __init__(self, faultevent): self.faultevent = faultevent def as_item(self): event = self.faultevent item = rss.Item() title = event.title faulttype = event.faulttype #item.title = rss.Title('%s: %s' % (title, faulttype)) item.title = rss.Title('%s (%s): %s' % (title, 'P1', event.state.upper())) item.link = rss.Link('http://%s/syndication?guid=%s' % (event.origin, event.GUID)) item.pub_date = rss.PubDate(event.timestamp) description = event.description event_history = event.history + [event.current_event] for change in event_history: description += '<br />\n%s. ' % change.detail item.description = rss.Description(tools.escape_html(description)) item.guid = rss.Guid(event.GUID) item.source = rss.Source(event.LOCALORIGIN, 'http://%s/syndication' % event.LOCALORIGIN) for category in event.types: item.categories.append(rss.Category(category)) return item def render(self): return str(self.as_item())
class MultiAdapts(object): implements(IB) adapts(INoA, INoB) def __init__(self, a, b): self.contexts = [a, b] def show(self, name = 'shane'): for context in self.contexts: context.say(name)
class PeriodicLogTrendAdapter(TrendBase): implements(ITrend) def __init__(self, *args): super(PeriodicLogTrendAdapter, self).__init__(*args) self.klass = 'log' self.__running = False return def configure(self, config): super(PeriodicLogTrendAdapter, self).configure(config) return def configuration(self): config = super(PeriodicLogTrendAdapter, self).configuration() return config def start(self): if self.__running: return super(PeriodicLogTrendAdapter, self).start() self.periodic_log = as_internal_node('/services/logger').get_child( self.name) self.log_url = self.periodic_log.as_node_url() self.__running = True return def stop(self): super(PeriodicLogTrendAdapter, self).stop() self.__running = False return def get_points(self): points = [] columns = [] for column in self.periodic_log.get_child('columns').children_nodes(): if hasattr(column, 'position') and int(column.position) != 0: columns.append(column) columns.sort(lambda a, b: cmp(int(a.position), int(b.position))) for column in columns: # Scary voodoo to determine the Node asscoiated with the get. import mpx.lib.node func = column.configuration()['function'] function = eval(func) try: node_url = function.im_self.as_node_url() except AttributeError: # could be RNA - try to parse from configuration info. and check # if it's really a node node_url = func[func.find('(') + 2:func.rfind(')') - 1] node_url = as_node(node_url).as_node_url() points.append({'name': column.name, 'node': node_url}) return points def destroy(self): # @fixme Raise a better exception... raise 'Trend Manager will not delete logs.'
class HTMLScheduleForm(object): implements(IWebContent) adapts(ISchedule) def __init__(self, schedule): self.schedule = schedule def render(self, request_path): attrs = KeyWordAssist() document = HTMLgen.Div(**attrs("class", "content")) encoded_schedule = urllib.quote_plus(self.schedule.url) config_form = HTMLgen.Form(request_path) nodeinput = HTMLgen.Input(name='node', value=encoded_schedule, type='hidden') actioninput = HTMLgen.Input(name="actionName", value="configure", type="hidden") config_form.append(nodeinput) config_form.append(actioninput) config_form.submit.value = 'save' config_form.submit.onClick = ('return utils.schedule.' 'validate_configuration(this.form);') config_section = HTMLgen.Div(**attrs('class', 'section')) config_table = HTMLgen.TableLite( **attrs('class', 'configuration-table')) config_header = HTMLgen.TR(**attrs('class', 'table-header')) for header in ['Attribute', 'Value']: headcell = HTMLgen.TH(header, scope="col", abbr=header, id="%sheader" % header) if header == "Action": setattr(headcell, "class", "control") config_header.append(headcell) config_table.append(config_header) configrows = [] classes = itertools.cycle(['light', 'dark']) config = Dictionary(self.schedule.configuration()) namerow = HTMLgen.TR(**attrs('class', classes.next())) namerow.append(HTMLgen.TH('Schedule Name')) sched_name = config.pop('name').split("RZSched_") namefield = HTMLgen.Input(value=sched_name[1], name='configure.name') namerow.append(HTMLgen.TD(namefield, **attrs('class', 'configuration'))) configrows.append(namerow) config_table.append(*configrows) config_form.append(config_table) config_section.append(config_form) config_section.append( navigation(request_path, "reload", self.schedule.url)) config_section.append( navigation(request_path, "back", self.schedule.parent.url)) document.append(config_section) return str(document)
class AnyAdapts(object): implements(IB) adapts(None, INoB) def __init__(self, a, b): self.contexts = [a, b] def show(self, name = 'shane'): for context in self.contexts: try: context.say(name) except AttributeError: print 'Context %s has no say!' % context
class C(object): implements(Interface) def __init__(self, name='test', value='test value', nstest='Namespace conflict test'): self.name = name self.value = value self.__predicate = nstest
class ProxyMixin(object): implements(IAliasNode) def __init__(self): self.__subject_url = None self.__subject = None self.__mount_point = None def set_mount_point(self, mount_point): self.__mount_point = mount_point def get_mount_point(self): if self.__mount_point is None: if hasattr(self.parent, 'get_mount_point'): self.set_mount_point(self.parent.get_mount_point()) return self.__mount_point def is_remote(self): mp = None if isinstance(self, MountPoint): mp = self.get_mount_point() elif hasattr(self.parent, 'get_mount_point'): mp = self.parent.get_mount_point() if mp is None: return False self.set_mount_point(mp) return True def get_subject(self): if self.__subject is None: if self.is_remote(): self.set_subject(as_node(self.as_remote_url())) else: self.set_subject(self) return self.__subject def dereference(self, recursive=True): return self.get_subject() def set_subject(self, subject): self.__subject = subject def set_remote_url(self, url): self.__subject_url = url def as_remote_url(self): if self.__subject_url is None: mp = self.parent.get_mount_point() if mp is not None: self.set_mount_point(mp) self.set_remote_url(self.parent.as_remote_url() + '/' + self.name) else: self.set_remote_url(self.as_node_url()) return self.__subject_url
class FieldStorageCollection(OrderedCollection): implements(IFieldStorageCollection) def __init__(self, objects, *args, **keywords): self.fields = None for obj in objects: assert IFieldStorage.providedBy(obj), ( 'Object %s does not implement IFieldStorage.' % obj) names = obj.get_field_names() if self.fields is not None: assert names == self.fields, ( 'Object %s does not have the same fields.' % obj) else: self.fields = names super(FieldStorageCollection, self).__init__(objects, *args, **keywords) def invoke(self, name, *args, **keywords): if name == 'get_field_names': results = self.fields[:] else: invoke = super(FieldStorageCollection, self).invoke if name == 'get_field_dictionary': # values = list of lists of values, where each # list is all items from one object. [[1,2,3],[1,2,3],...] values = invoke('get_field_values', self.fields) # values = list of tuples of values, where each # tuple is a particular filed from each object. # [(1,1,...), (2,2,...), (3,3,...), ...] values = zip(*values) # values = list of tuples, where each # tuple is a label and a tuple of values # with corresponding values. # [('l1',(1,1,...), ('l2',(2,2,...)), ...] values = zip(self.fields, values) results = Dictionary(values) else: results = invoke(name, *args, **keywords) return results def get_field_names(self): return self.invoke('get_field_names') def get_field_dictionary(self): return self.invoke('get_field_dictionary') def get_field_values(self, names): return self.invoke('get_field_values', names) def return_type(self): # If returned collections were instances of # this.__class__, rather than of OrderedCollection, # all attributes would have to provide # IFieldStorage as well. return OrderedCollection
class BroadwayConfigurableGenerator(object): implements(IBroadways) adapts(IConfigurableNode) nodeopen = "<node name='%s' node_id='%s' module='%s.%s' config_builder='' inherant='false' description=''>" nodeclose = "</node>" configopen = "\t<config>" configclose = "\t</config>" propertyopenclose = "\t\t<property name='%s' value='%s'/>" def __init__(self, node): self.node = node def _xml_lines(self, levels=None): realnode = self.node while isinstance(realnode, OGConfigurableNeodeAdapter): realnode = realnode.node classname = realnode.__class__.__name__ module = realnode.__class__.__module__ xmllines = [self.nodeopen % (self.node.name, 0, module, classname)] xmllines.append(self.configopen) configuration = self.node.configuration() if configuration.has_key('parent'): del (configuration['parent']) if configuration.has_key('name'): del (configuration['name']) for name, value in configuration.items(): if not isinstance(value, str): value = str(value) value = encode_xml(value) xmllines.append(self.propertyopenclose % (name, value)) xmllines.append(self.configclose) xmllines.append(self.nodeclose) return xmllines def dumps(self, levels=None): return string.join(self._xml_lines(levels), '\n') def loads(self, data): datastream = StringIO.StringIO(data) xmlroot = parse_xml(datastream) xmlroot.parent = self.node.url crawler = Iterator(xmlroot) nodecount = 0 while crawler.has_more(): xmlnode = crawler.get_next_node() config = xmlnode.get_config() print 'Loading node %d: %s' % (nodecount, config) node = load_node(config) node.configure(config) nodecount += 1 return nodecount def dump(self, datastream, levels=None): return datastream.write(self.dumps(levels))
class DomDocument(DomElement): __doc__ = IDomDocument.__doc__ implements(IDomDocument) adapts(IRootNode) def __init__(self, node): super(DomDocument, self).__init__(node) self._type = dom.Node.DOCUMENT_NODE # See mpx.www.w3c.dom.interfaces.IDomDocument def __get_document_element(self): # Root is this object's node. return IDomNode(self.node) documentElement = property(__get_document_element) def __get_nodespace(self): return self.node.get_nodespace() nodespace = property(__get_nodespace) def getElementById(self, id): """ ID is the node URL. """ return IDomNode(self.nodespace.as_node(id)) def createElement(self, tagName): "See mpx.www.w3c.dom.interfaces.IDomDocument" raise Exception("Not implemented") def createElementNS(self, namespaceURI, tagName): "See mpx.www.w3c.dom.interfaces.IDomDocument" raise Exception("Not implemented") def createTextNode(self, data): "See mpx.www.w3c.dom.interfaces.IDomDocument" raise Exception("Not implemented") def createComment(self, data): "See mpx.www.w3c.dom.interfaces.IDomDocument" raise Exception("Not implemented") def createProcessingInstruction(self, target, data): "See mpx.www.w3c.dom.interfaces.IDomDocument" raise Exception("Not implemented") def createAttribute(self, name): "See mpx.www.w3c.dom.interfaces.IDomDocument" raise Exception("Not implemented") def createAttributeNS(self, namespaceURI, qualifiedName): "See mpx.www.w3c.dom.interfaces.IDomDocument" raise Exception("Not implemented")
class DataContainterDOM(LeafNodeDOM): implements(IDOMish) adapts(IDataContainer) def getTagById(self, id): result = super(DataContainterDOM,self).getTagById(id) if result is None: for tag in self.tag.data: result = domish(tag).getTagById(id) if result is not None: return result return result
class PickleAdapter(object): implements(IPickles) adapts(Interface) def __init__(self, context): self.context = context def __getinitargs__(self): return self.context def __call__(self): return self.context