def find_subscribed_machines_for_module(self,module_id): machine_name_list = [] xpath = 'machine_list/machine/distribute_module/module_name[@id=\'' + module_id + '\']' for t in Evaluate(xpath, self.dom.documentElement): m = Evaluate('parent::*/parent::*', t) machine_name_list.append(str(Evaluate('@machine_name', m[0])[0].nodeValue).strip()) return machine_name_list
def __init__(self, devnode=None, devprovider=None): if devnode == None: self.devnode = None self.name = None self.id = None self.console = None self.can_be_eth_conf = None self.can_be_tty_conf = None self.support = None self.device_type = None self.tty_conf = None self.provider = provider() else: self.devnode = devnode self.name = devnode.getAttribute("name") self.id = devnode.getAttribute("id") self.image = devnode.getAttribute("image") self.console = Evaluate("console/text( )", devnode)[0].nodeValue self.support = Evaluate("support/text( )", devnode)[0].nodeValue self.can_be_eth_conf = int( Evaluate("can_be_eth_conf/text( )", devnode)[0].nodeValue) self.can_be_tty_conf = int( Evaluate("can_be_tty_conf/text( )", devnode)[0].nodeValue) self.device_type = devicetype( Evaluate("device_type", devnode)[0].getAttribute("id")) if self.device_type.dt_id == '0001': #DSL USB self.tty_conf = None self.linux_driver = Evaluate("usb_conf/linux_driver/text( )", devnode)[0].nodeValue devidnodes = Evaluate("usb_conf/deviceid_list/deviceid", devnode) self.devids = [] for devidnode in devidnodes: vendor = devidnode.getAttribute("vendor") model = devidnode.getAttribute("model") self.devids += [(vendor, model)] else: #DSL Router self.tty_conf = tty_conf( Evaluate("tty_conf", devnode)[0].getAttribute("id")) self.eth_conf_port = Evaluate("eth_conf_port/text( )", devnode)[0].nodeValue if devprovider != None: self.provider = devprovider defpass_node = Evaluate( "provider_list/provider[@id=" + devprovider.prov_id + "]/default_passwd_list/" + "default_passwd[@id='0001']", devnode) if len(defpass_node) > 0: self.default_passwd = defpass_node[0].getAttribute( "passwd") else: self.default_passwd = None else: self.provider = provider() self.default_passwd = None
def evaluateXPath(path, element): try: import xml.dom from xml.xpath import Evaluate result=Evaluate(path, element) if hasattr(result,'__iter__'): for i in range(len(result)): if isinstance(result[i], xml.dom.Node) and result[i].nodeType == xml.dom.Node.ATTRIBUTE_NODE: result[i]=result[i].value elif type(result)==bool: return result else: result=[result] return result except ImportError: # Implementation for etree from lxml.etree import XPath, fromstring, tounicode # returns a list of _ElementStringResult buf=toPrettyXML(element) elist=XPath(path).evaluate(fromstring(buf)) nodelist=list() # if is iterable if hasattr(elist,'__iter__'): for eelement in elist: # either the returnlist is a stringlist or a element list if isinstance(eelement, basestring): nodelist.append(eelement) else: nodelist.append(parseXMLString(tounicode(eelement)).documentElement) elif type(elist)==bool: return elist else: nodelist.append(elist) return nodelist
def _parse_node(self, node): for field in self._fields: try: avail_fields = Evaluate("%s" % (field), node) if len(avail_fields) == 0: # No fields skip this one continue # Get the first field field_node = avail_fields[0] val = Evaluate("string()", field_node).strip() convert = self._fields[field].convert if convert: val = convert(val) self._fields[field].data = val except ValueError: pass
def FetchMetaData(self): """ Fetches the sample's meta data from the Freesound service. """ req = Request( "http://www.freesound.org/samplesViewSingleXML.php?id=%s" % self.sid) try: handle = urlopen(req) except: # TODO: handle URL problems return data = handle.read() for attribute, xpath in SAMPLE_ATTRIBUTES.items(): if useXpath: try: dom = minidom.parseString(data) xpathResult = Evaluate(xpath, dom)[0].firstChild.nodeValue except: xpathResult = None elif useElementTree: try: doc = ElementTree.fromstring(data) # Needs relative path since "freesound" is the root element xpathResult = doc.findall(xpath.replace("/freesound/", ""))[0].text except: xpathResult = None setattr(self, attribute, xpathResult)
def get_num_elements(self, name): ''' An API function to get the number of elements for a variable. Do not use this function to build loops, Use iterator instead. ''' context = Context(self.current_node, processorNss=self.namespaces) results_list = Evaluate(name, context=context) return len(results_list)
def func_parse(dom, child, func, default_timeout=-1, sdelay=0): """ Parse a func in the xml and process every cmd in the function. """ path_cmd = "cmd_func[@id='" + func + "']/cmd" cmds = Evaluate(path_cmd, dom.documentElement) if (len(cmds) < 1): raise SyntaxError, _("en modulo de expect. Función call") + \ " '" + func + "' " + _("desconocida") return (cmd_parse(dom, child, cmds, default_timeout, sdelay))
def getXPathFromXMLFile(xpath, filename): try: from comoonics import XmlTools document = XmlTools.parseXMLFile(filename) return XmlTools.evaluateXPath(xpath, document.documentElement) except ImportError: import xml.dom.minidom from xml.xpath import Evaluate import os filep = os.fdopen(os.open(filename, os.O_RDONLY)) doc = xml.dom.minidom.parse(filep) return Evaluate(xpath, doc.documentElement)
def __init__(self, opernode=None): if opernode == None: self.opernode = None self.id = None self.bb_device = None self.supported = 0 self.ui_public = 0 self.opername = None self.firmware = None self.initial_func = None self.default_timeout = None self.send_delay = None self.druid_page_list = [] else: self.opernode = opernode self.id = opernode.getAttribute("id") self.bb_device = opernode.getAttribute("bb_device") self.supported = opernode.getAttribute("supported") self.ui_public = opernode.getAttribute("ui_public") self.opername = {} for opername_node in Evaluate("opername_list/opername", opernode): self.opername[opername_node.getAttribute( "lang")] = opername_node.getAttribute("name") self.firmware = Evaluate("firmware/text( )", opernode)[0].nodeValue self.initial_func = Evaluate("initial_func/text( )", opernode)[0].nodeValue self.default_timeout = Evaluate("default_timeout/text( )", opernode)[0].nodeValue self.send_delay = Evaluate("send_delay/text( )", opernode)[0].nodeValue self.druid_page_list = [] for druid_page_node in Evaluate( "druid_page_list/druid_page/text( )", opernode): self.druid_page_list += [druid_page_node.nodeValue]
def iterator(self, name): ''' An iterator over the values of a certain name. The iterator changes state of interenal variables and objects. When calling get_value in a loop, this will result each time in a different value. ''' saved_node = self.current_node context = Context(self.current_node, processorNss=self.namespaces) results_list = Evaluate(name, context=context) for node in results_list: self.current_node = node yield node self.current_node = saved_node
def filter_location(self, location): url = urlutil.UrlParse(location) if not url.is_local: fd = gnomevfs.open(url.unparse()) def read_all(): buff = "" try: while 1: buff += fd.read(1024) except gnomevfs.EOFError: pass return buff fd.read = read_all else: fd = open(url.path) try: zfile = zipfile.ZipFile(fd) except zipfile.BadZipfile: return except IOError: # it's not a file return try: buff = zfile.read("maindata.xml") except KeyError: # zip file does not contain the file return try: root = minidom.parseString(buff) except ExpatError: # Malformed xml return # Iterate over tracks hints_list = [] for node in Evaluate("/k3b_audio_project/contents/track", root): try: hints_list.append({"location": node.attributes["url"].value}) except KeyError: # skip elements with not 'url' attribute set pass return hints_list
def get_value(self, name, display_type='value'): ''' The API function for quering the translator for values of a certain variable. Called in a loop will result in a different value each time. @param name: the name of the variable you want the value of @param display_type: an optional value for the type of the desired output, one of: value, tag, ind1, ind2, code, fulltag; These can be easily added in the proper place of the code (display_value) ''' context = Context(self.current_node, processorNss=self.namespaces) results_list = Evaluate(name, context=context) if len(results_list) == 0: return '' # Select text node value of selected nodes # and concatenate return ' '.join([node.childNodes[0].nodeValue.encode( "utf-8" ) for node in results_list])
def parse(self, file_or_filename): root = minidom.parse(file_or_filename) # Iterate over tracks for track_node in Evaluate("/playlist/trackList/track", root): t = Track() # Get each field #for field in t._fields: # try: # val = Evaluate ("string(%s)" % (field), track_node).strip() # convert = t._fields[field].convert # if convert: # val = convert (val) # setattr (t, field, val) # except ValueError: # pass t._parse_node(track_node) self.tracks.append(t)
def __init__(self, xpath_devnode=None): if xpath_devnode == None: self.prov_id = "" self.prov_name = "" self.shortname = "" self.dns1 = "" self.dns2 = "" self.vpi = "" self.vci = "" self.pppoe = "" self.pppoa = "" self.encap = "" else: self.prov_id = xpath_devnode.getAttribute("id") self.prov_name = xpath_devnode.getAttribute("name") self.shortname = xpath_devnode.getAttribute("shortname") self.dns1 = Evaluate("dns1/text( )", xpath_devnode)[0].nodeValue self.dns2 = Evaluate("dns2/text( )", xpath_devnode)[0].nodeValue self.vpi = Evaluate("vpi/text( )", xpath_devnode)[0].nodeValue self.vci = Evaluate("vci/text( )", xpath_devnode)[0].nodeValue self.pppoe = Evaluate("pppoe/text( )", xpath_devnode)[0].nodeValue self.pppoa = Evaluate("pppoa/text( )", xpath_devnode)[0].nodeValue self.encap = Evaluate("encap/text( )", xpath_devnode)[0].nodeValue
def rhythmbox_get_playlist(playlist_name): root = minidom.parse(PLAYLISTS) path = "/rhythmdb-playlists/playlist[@name = '%s']/location/text()" % playlist_name getvalue = lambda node: node.nodeValue return map(getvalue, Evaluate(path, root))
def rhythmbox_list_names(): root = minidom.parse(PLAYLISTS) getvalue = lambda node: node.attributes["name"].value return map(getvalue, Evaluate("/rhythmdb-playlists/playlist", root))
def find_location_for_module(self, module_id, location): xpath = 'module_list/module[@id=\'' + module_id + '\']'+'/'+location+'/text()' return (Evaluate(xpath, self.dom.documentElement)[0].nodeValue).strip()
# create Reader object reader = Sax2.Reader(validate=1) filename = "./testmetadata.xml" if len(sys.argv) > 1: filename = sys.argv[1] file = os.fdopen(os.open(filename, os.O_RDONLY)) doc = reader.fromStream(file) line("XML Document") PrettyPrint(doc) line("sets of copyset@lvm") sets = Evaluate('enterprisecopy/copyset[@type="lvm"]', doc) print sets try: for i in range(len(sets)): line("set[%u]" % i) cs = ComCopyset.getCopyset(sets[i], doc) print "Copyset: ", cs print "XML: " PrettyPrint(cs.getElement()) line("write to dest: %s" % cs) ComSystem.__EXEC_REALLY_DO = "ask" cs.doCopy() except Exception, e: ComLog.getLogger("testMetadataCopyset").warn( "Exception %s caught during copy. Undoing." % e) import traceback
def find_ftp_info_for_module(self, module_id,info_tag): xpath = 'module_list/module[@id=\'' + module_id + '\']'+'/ftp_info/' + info_tag + '/text()' return (Evaluate(xpath, self.dom.documentElement)[0].nodeValue).strip()
def find_location_on_remote_machine(self, module_id, machine_name): xpath = 'machine_list/machine[@machine_name=\"' + machine_name + '\"]'+'/distribute_module/module_name[@id=\"' \ + module_id +'\"]' m = Evaluate(xpath, self.dom.documentElement) return (Evaluate('parent::*/local_location/text()', m[0])[0].nodeValue).strip()
def find_all_modules(self): module_id_list = [] for t in Evaluate('module_list/module[@id]', self.dom.documentElement): module_id_list.append(str(Evaluate('@id', t)[0].nodeValue).strip()) return module_id_list
def rhythmbox_list_names (): root = minidom.parse (PLAYLISTS) return [node.attributes["name"].value for node in Evaluate ("/rhythmdb-playlists/playlist", root)]
def find_config(self, config_id): xpath = 'config_list/config_item[@id=\"' + config_id + '\"]/text()' m = Evaluate(xpath, self.dom.documentElement) return (m[0].nodeValue).strip()
import sys from xml.dom.ext.reader import PyExpat from xml.xpath import Evaluate subtype = "//conclusion/assigned/name" subtype_file = open(sys.argv[2],'w'); dom = PyExpat.Reader().fromUri(sys.argv[1]) elements = Evaluate(subtype, dom.documentElement) for element in elements: subtype_file.write(element.childNodes[0].data) subtype_file.close()
def filter_location(self, location): url = urlutil.UrlParse(location) if not url.is_local: fd = gnomevfs.open(url.unparse()) def read_all(): buff = "" try: while 1: buff += fd.read(1024) except gnomevfs.EOFError: pass return buff fd.read = read_all else: try: fd = open(url.path) except IOError: # Could not open the filename return try: zfile = zipfile.ZipFile(fd) except zipfile.BadZipfile: return except IOError: # it's not a file return try: buff = zfile.read("maindata.xml") except KeyError: # zip file does not contain the file fd.close() return fd.close() try: root = minidom.parseString(buff) except ExpatError: # Malformed xml return # Iterate over tracks hints_list = [] for node in Evaluate("/k3b_audio_project/contents/track", root): try: hints_list.append({"location": node.attributes["url"].value}) except KeyError: # skip elements with not 'url' attribute set pass # New versions of K3B changed the internal structure # since there's no version present for the file format we'll just # try both for node in Evaluate("/k3b_audio_project/contents/track/sources/file", root): try: hints_list.append({"location": node.attributes["url"].value}) except KeyError: # skip elements with not 'url' attribute set pass return hints_list
def find_ftp_info_machine_name_for_module(self, module_id): xpath = 'module_list/module[@id=\'' + module_id + '\']'+'/ftp_info' m = Evaluate(xpath, self.dom.documentElement)[0] return (Evaluate('@machine_name', m)[0].nodeValue).strip()
def find_keep_original(self, module_id): module_id_list = [] t = Evaluate('module_list/module[@id=\''+module_id+'\']', self.dom.documentElement) return (str(Evaluate('@keep_original', t[0])[0].nodeValue).strip())
def searchPathXml(search_path, xmlfile): reader = PyExpat.Reader() xml_file = open(os.path.join(PATH, xmlfile), "r") dom = reader.fromStream(xml_file) return Evaluate(search_path, dom.documentElement)
def rhythmbox_get_playlist (playlist_name): root = minidom.parse (PLAYLISTS) path = "/rhythmdb-playlists/playlist[@name = '%s']/location/text()" % playlist_name return [node.nodeValue for node in Evaluate (path, root)]
def bb_enable_iface_with_config(devcf): """ Configuration of eth interfaces via system-tools-backends. * Example of static interface configuration via system-tools-backends Function call: (sysret, xmlcfg, xmlcfgout) = bb_enable_iface_with_config('eth1', 'none', '10.0.0.6', '10.255.255.255', '10.0.0.1', '255.255.255.0', '10.0.0.0') xml passed to system-tools-backends: <?xml version='1.0' encoding='UTF-8' standalone='yes'?> <interface type='ethernet'> <configuration> <address>10.0.0.8</address> <auto>1</auto> <bootproto>none</bootproto> <broadcast>10.0.0.255</broadcast> <file>eth1</file> <gateway>10.0.0.1</gateway> <netmask>255.255.255.0</netmask> <network>10.0.0.0</network> </configuration> <dev>eth1</dev> <enabled>1</enabled> </interface> <!-- GST: end of request --> * Example of dhcp interface configuration via system-tools-backend Function call: (sysret, xmlcfg, xmlcfgout) = bb_enable_iface_with_config('eth1', 'dhcp') xml passed to system-tools-backends: <interface type='ethernet'> <configuration> <auto>1</auto> <bootproto>dhcp</bootproto> <file>eth0</file> </configuration> <dev>eth0</dev> <enabled>1</enabled> </interface> <!-- GST: end of request --> """ netcfg_xmlfile = tempfile.NamedTemporaryFile() netcfgout_xmlfile = tempfile.NamedTemporaryFile() writer = MarkupWriter(netcfg_xmlfile, encoding='UTF-8', indent=u"yes", standalone="yes") writer.startDocument() writer.startElement(u'interface') writer.attribute(u'type', u'ethernet') writer.startElement(u'configuration') if devcf.param['dhcp'] == 'True': conf = { 'auto' : '1', \ 'bootproto' : 'dhcp', \ 'file': devcf.param['eth_to_conf'] } else: broadcast = ipBroadcast(devcf.param['ip_computer'], devcf.param['mask_computer']) conf = { 'address' : devcf.param['ip_computer'], \ 'auto' : '1', \ 'bootproto' :'none', \ 'broadcast' : broadcast, \ 'file': devcf.param['eth_to_conf'], \ 'gateway' : devcf.param['gw_computer'], \ 'netmask' : devcf.param['mask_computer'], \ 'network' : devcf.param['net_computer']} for confparam in conf.keys(): writer.startElement(unicode(confparam)) writer.text(unicode(conf[confparam])) writer.endElement(unicode(confparam)) writer.endElement(u'configuration') writer.startElement(u'dev') writer.text(unicode(devcf.param['eth_to_conf'])) writer.endElement(u'dev') writer.startElement(u'enabled') writer.text(u'1') writer.endElement(u'enable') writer.endElement(u'interface') writer.text(u'\n') writer.comment(u' GST: end of request ') writer.endDocument() netcfg_xmlfile.flush() xmlcfg = open(netcfg_xmlfile.name).read( ) net_cfg_cmd = "cat " + netcfg_xmlfile.name + " | /usr/share/setup-tool-backends/scripts/network-conf -d enable_iface_with_config | grep -vE \"^$\" > " + netcfgout_xmlfile.name os.system(net_cfg_cmd) xmlcfgout = open(netcfgout_xmlfile.name).read( ) reader = PyExpat.Reader( ) dom = reader.fromStream(open(netcfgout_xmlfile.name, "r")) successCfg = Evaluate("success/text( )", dom.documentElement)[0].nodeValue if successCfg == '0': sysret = BBERRCFGDEV # Error configuration dev else: sysret = BBNOERR # Ok return (sysret, xmlcfg, xmlcfgout)