def new_graph(cls, account): """new_graph constructs a new OPMGraph with default account.""" graph = cls() # Create doc and query context. graph.doc = libxml2.newDoc("1.0") graph.ctxt = graph.doc.xpathNewContext() graph.ctxt.xpathRegisterNs('opm', NAMESPACE) # Create root and namespace. graph.root = graph.doc.newChild(None, "opmGraph", None) graph.ns = graph.root.newNs(NAMESPACE, None) graph.root.setNs(graph.ns) # opmGraph id is set at write-time; see save_to, below. # Create account. graph.account = str(account) graph.root.newChild(graph.ns, "accounts", None).newChild( graph.ns, "account", None).setProp("id", graph.account) # Create standard branches. graph.artifacts = None graph.dependencies = None return graph
def __init__(self, filename, plural, singular): self.conf = pcmkconfig.Config() self.plural = plural self.singular = singular self.xml_file = '%s/%s' % (self.conf.dbdir, filename) it_exists = os.access(self.xml_file, os.R_OK) libxml2.keepBlanksDefault(False) try: if it_exists: self.doc = libxml2.parseFile(self.xml_file) except: it_exists = False if not it_exists: self.doc = libxml2.newDoc("1.0") self.root_node = self.doc.newChild(None, plural, None) self.root_node.setProp('pcmkc-version', self.conf.version) else: self.root_node = self.doc.getRootElement() _ver = self.root_node.prop('pcmkc-version') if not _ver == self.conf.version: _msg = '*** warning xml and program version mismatch' print '%s \"%s\" != \"%s\"' % (_msg, _ver, self.conf.version) self.all = {} self.load()
def __init__(self, username, password): self.username = username self.password = password self.url = "http://www.fxcorporate.com/Hosts.jsp" self.connection = "Demo" self.xml = libxml2.newDoc('1.0') self.login()
def unit_test(rootdir): """ unit_test for dmi.py, looks a little crufty! """ class UnittestConfigDummy: def __init__(self, rootdir): self.config = {'installdir': '/usr/share/rteval'} self.__update_vars() def __update_vars(self): for k in list(self.config.keys()): self.__dict__[k] = self.config[k] try: ProcessWarnings() if os.getuid() != 0: print("** ERROR ** Must be root to run this unit_test()") return 1 log = Log() log.SetLogVerbosity(Log.DEBUG | Log.INFO) cfg = UnittestConfigDummy(rootdir) d = DMIinfo(cfg, log) dx = d.MakeReport() x = libxml2.newDoc("1.0") x.setRootElement(dx) x.saveFormatFileEnc("-", "UTF-8", 1) return 0 except Exception as e: print("** EXCEPTION: %s" % str(e)) return 1
def publish(self, filename=None): """Saves the current state of the `CheckList` into a savefile. Attributes: filename -- File to save the checklist in. (default self.filename) Saves the CheckList information into the filename. """ self.filename = filename or self.filename if not self.filename: raise error.CannotAccessFile("No filename given to save to.") # Create the xml DOM conforming to our save DTD doc = libxml2.newDoc("1.0") doc.createIntSubset("checklist", self.publicID, self.canonicalURL) # Output root node root = doc.newChild(None, "checklist", None) root.setProp("version", self.formatVersion) root.setProp("name", self.name) self.revision += 1 root.setProp("revision", str(self.revision)) # Output summary node root.newChild(None, "summary", self.summary) # Output base checklist information node = root.newTextChild(None, "base", self.baseFilename) node.setProp("name", self.baseName) node.setProp("revision", self.baseRevision) # Output properties we're concerned with properties = root.newChild(None, "properties", None) for propName in self.properties.keys(): prop = self.properties[propName] node = properties.newChild(None, "property", None) node.setProp("name", propName) node.setProp("type", prop.type) require = node.newChild(None, "require", None) require.setProp("type", prop.require) for arg in prop.args: require.newTextChild(None, "arg", arg) if prop.function: function = require.newTextChild(None, "function", prop.function) function.setProp("type", prop.functionType) if prop.value: node.newTextChild(None, "value", prop.value) # Output functions functions = root.newChild(None, "functions", None) for func in self.functions: node = functions.newTextChild(None, "function", func[0]) node.setProp("type", func[1]) # Output entries self.foreach(self.__create_entry, root) # Write the file doc.saveFormatFileEnc(self.filename, "UTF-8", True) doc.freeDoc()
def skeleton(self, parent=None): if parent is None: parent = libxml2.newDoc("1.0") this = parent.newChild(None, self.__class__.__name__, None) for prop, value in self.skelargs().items(): this.setProp(prop, repr(value)) return this
def generate_config(self, name): fac = assembly.AssemblyFactory() doc = libxml2.newDoc("1.0") dep = doc.newChild(None, "deployable", None) dep.setProp("name", name) dep.setProp("uuid", name) # TODO n_asses = dep.newChild(None, "assemblies", None) constraints = dep.newChild(None, 'constraints', None) a_list = self.doc.xpathEval("/deployables/deployable[@name='%s']/assembly" % name) for a_data in a_list: a = fac.get(a_data.prop('name')) n_ass = n_asses.newChild(None, 'assembly', None) n_ass.setProp("name", a.name) n_ass.setProp("uuid", a.uuid) n_servs = n_ass.newChild(None, "services", None) for r in a.resources_get(): n_srv = n_servs.newChild(None, 'service', None) n_srv.setProp("name", r.type) n_srv.setProp("monitor_interval", r.monitor_interval) filename = '/var/run/%s.xml' % name open(filename, 'w').write(doc.serialize(None, 1)) doc.freeDoc()
def __criarXml(self): #Criar o xml doc = libxml2.newDoc("1.0") dominio = doc.newChild(None,"domain",None) dominio.newProp("type","notificador") programa = dominio.newChild(None,"programa",None) programa.addChild(doc.newDocText(self.programa)) parametros = dominio.newChild(None,"parametros",None) parametros.addChild(doc.newDocText(self.parametros)) icone = dominio.newChild(None,"icone",None) icone.addChild(doc.newDocText(self.icone)) titulo = dominio.newChild(None,"titulo",None) titulo.addChild(doc.newDocText(self.titulo)) mensagem = dominio.newChild(None,"mensagem",None) mensagem.addChild(doc.newDocText(self.mensagem)) arquivoInibidor = dominio.newChild(None,"arquivoInibidor",None) arquivoInibidor.addChild(doc.newDocText(self.inibidor)) tempoEspera = dominio.newChild(None,"tempoEspera",None) tempoEspera.addChild(doc.newDocText(self.espera)) tempoExibicao = dominio.newChild(None,"tempoExibicao",None) tempoExibicao.addChild(doc.newDocText(self.exibicao)) #Salva o xml no arquivo arquivo = open(self.nomeXml,"w") arquivo.write(doc.serialize(None, 1)) arquivo.close() print "Arquivo gerado com sucesso!"
def create_dom(self, sDoc_name): """ DOM creation. """ domDoc = libxml2.newDoc("1.0") domDoc.newChild(None, sDoc_name, None) return domDoc
def __init__(self,username,password): self.username = username self.password = password self.url="http://www.fxcorporate.com/Hosts.jsp" self.connection="Demo" self.xml=libxml2.newDoc('1.0') self.login()
def __init__(self,login_res,instrument,time_frame,size): self.instrument = instrument self.time_frame = time_frame self.id = login_res.id self.size = size self.xml=libxml2.newDoc('1.0') self.getHistoricalData()
def _CreateWBXMLDoc(self, root_node_name, namespace): doc = libxml2.newDoc("1.0") doc.createIntSubset(AIRSYNC_DOC_NAME, AIRSYNC_PUBLIC_ID, AIRSYNC_SYSTEM_ID) root=doc.newChild(None,root_node_name,None) root.setProp("xmlns", namespace) return doc
def writeTree(self, root, fpath): fp = open(fpath, 'w') doc = libxml2.newDoc('1.0') doc.setRootElement(root) fp.write(doc.serialize("UTF-8", 1)) doc.freeDoc() fp.close()
def write_foaf(self, rawdog, config): doc = libxml2.newDoc("1.0") xml = doc.newChild(None, 'rdf:RDF', None) xml.setProp('xmlns:rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#") xml.setProp('xmlns:rdfs', "http://www.w3.org/2000/01/rdf-schema#") xml.setProp('xmlns:foaf', "http://xmlns.com/foaf/0.1/") xml.setProp('xmlns:rss', "http://purl.org/rss/1.0/") xml.setProp('xmlns:dc', "http://purl.org/dc/elements/1.1/") group = xml.newChild(None, 'foaf:Group', None) group.newChild(None, 'foaf:name', escape(self.options["xmltitle"])) group.newChild(None, 'foaf:homepage', escape(self.options["xmllink"])) for url in sorted(rawdog.feeds.keys()): member = group.newChild(None, 'foaf:member', None) agent = member.newChild(None, 'foaf:Agent', None) agent.newChild(None, 'foaf:name', escape(self.feed_name(rawdog.feeds[url], config))) weblog = agent.newChild(None, 'foaf:weblog', None) document = weblog.newChild(None, 'foaf:Document', None) if rawdog.feeds[url].feed_info.get('link', ''): document.setProp('rdf:about', rawdog.feeds[url].feed_info['link']) seealso = document.newChild(None, 'rdfs:seeAlso', None) channel = seealso.newChild(None, 'rss:channel', None) channel.setProp('rdf:about', url) doc.saveFormatFile(self.options["outputfoaf"], 1) doc.freeDoc()
def generate_config(self, name): fac = assembly.AssemblyFactory() doc = libxml2.newDoc("1.0") dep = doc.newChild(None, "deployable", None) dep.setProp("name", name) dep.setProp("uuid", name) # TODO n_asses = dep.newChild(None, "assemblies", None) constraints = dep.newChild(None, 'constraints', None) a_list = self.doc.xpathEval( "/deployables/deployable[@name='%s']/assembly" % name) for a_data in a_list: a = fac.get(a_data.prop('name')) n_ass = n_asses.newChild(None, 'assembly', None) n_ass.setProp("name", a.name) n_ass.setProp("uuid", a.uuid) n_servs = n_ass.newChild(None, "services", None) for r in a.resources_get(): n_srv = n_servs.newChild(None, 'service', None) n_srv.setProp("name", r.type) n_srv.setProp("monitor_interval", r.monitor_interval) filename = '/var/run/%s.xml' % name open(filename, 'w').write(doc.serialize(None, 1)) doc.freeDoc()
def xpathQuery(self, ctx, sysConfig, xpath): # Get the database configuration try: db = self._getDatabase(sysConfig) if (not isinstance(xpath, str)): node = libxml2.xmlNode(_obj=xpath[0]) xpath = node.content content = db.xpathQuery(None, xpath) # See if this looks like an XML result if (content.startswith("<?xml")): doc = XMLFragment(content) # Extract the expected result set now that we've converted into libxml format. result = doc.xpathEval("/results/*") self.cleanupList.append(doc) else: doc = XMLFragment(libxml2.newDoc("1.0")) result = [doc.newDocText(content)] self.cleanupList.append(doc) return result except Exception, err: db.log.exception("DbXslExtension: Error searching")
def test_replace_null_ns(self): doc = libxml2.newDoc("1.0") root = doc.newChild(None, "root", None) common_ns = root.newNs(xmlextra.COMMON_NS, None) root.setNs(common_ns) doc.setRootElement(root) n = input_doc2.getRootElement() try: input_ns = n.ns() except libxml2.treeError: input_ns = None n = n.children while n: n1 = n.docCopyNode(doc, 1) root.addChild(n1) if n1.type == "element": try: n1_ns = n1.ns() except libxml2.treeError: n1_ns = None if n1_ns is None: xmlextra.replace_ns(n1, n1_ns, common_ns) n = n.next self.failUnless(xml_elements_equal(root, output_root))
def __create_empty_metadata_doc (self): metadata = libxml2.newDoc ("1.0") root = metadata.newChild (None, "metadata", None) root.newChild (None, "directories", None) root.newChild (None, "links", None) root.newChild (None, "files", None) return metadata
def new_graph(cls, account): """new_graph constructs a new OPMGraph with default account.""" graph = cls() # Create doc and query context. graph.doc = libxml2.newDoc("1.0") graph.ctxt = graph.doc.xpathNewContext() graph.ctxt.xpathRegisterNs('opm', NAMESPACE) # Create root and namespace. graph.root = graph.doc.newChild(None, "opmGraph", None) graph.ns = graph.root.newNs(NAMESPACE, None) graph.root.setNs(graph.ns) # opmGraph id is set at write-time; see save_to, below. # Create account. graph.account = str(account) graph.root.newChild(graph.ns, "accounts", None).newChild(graph.ns, "account", None).setProp("id", graph.account) # Create standard branches. graph.artifacts = None graph.dependencies = None return graph
def unit_test(rootdir): import sys try: log = Log() log.SetLogVerbosity(Log.DEBUG | Log.INFO) osi = OSInfo(logger=log) print("Base OS: %s" % osi.get_base_os()) print("Testing OSInfo::copy_dmesg('/tmp'): ", end=' ') osi.copy_dmesg('/tmp') if os.path.isfile("/tmp/dmesg"): md5orig = subprocess.check_output(("md5sum", "/var/log/dmesg")) md5copy = subprocess.check_output(("md5sum", "/tmp/dmesg")) if md5orig.split(" ")[0] == md5copy.split(" ")[0]: print("PASS") else: print("FAIL (md5sum)") os.unlink("/tmp/dmesg") else: print("FAIL (copy failed)") print("Running sysreport/sosreport with output to current dir") osi.run_sysreport(".") osinfo_xml = osi.MakeReport() xml_d = libxml2.newDoc("1.0") xml_d.setRootElement(osinfo_xml) xml_d.saveFormatFileEnc("-", "UTF-8", 1) except Exception as e: import traceback traceback.print_exc(file=sys.stdout) print("** EXCEPTION %s", str(e)) return 1
def test_replace_null_ns(self): doc = libxml2.newDoc("1.0") root = doc.newChild(None, "root", None) common_ns = root.newNs(xmlextra.COMMON_NS, None) root.setNs(common_ns) doc.setRootElement(root) n = input_doc2.getRootElement() try: input_ns = n.ns() except libxml2.treeError: input_ns = None n = n.children while n: n1 = n.docCopyNode(doc, 1) root.addChild(n1) if n1.type == 'element': try: n1_ns = n1.ns() except libxml2.treeError: n1_ns = None if n1_ns is None: xmlextra.replace_ns(n1, n1_ns, common_ns) n = n.next self.failUnless(xml_elements_equal(root, output_root))
def __init__(self, login_res, instrument, time_frame, size): self.instrument = instrument self.time_frame = time_frame self.id = login_res.id self.size = size self.xml = libxml2.newDoc('1.0') self.getHistoricalData()
def unit_test(rootdir): from pprint import pprint class unittest_ConfigDummy(object): def __init__(self, rootdir): self.config = {'installdir': '/usr/share/rteval'} self.__update_vars() def __update_vars(self): for k in self.config.keys(): self.__dict__[k] = self.config[k] try: ProcessWarnings() if os.getuid() != 0: print "** ERROR ** Must be root to run this unit_test()" return 1 log = Log() log.SetLogVerbosity(Log.DEBUG | Log.INFO) cfg = unittest_ConfigDummy(rootdir) d = DMIinfo(cfg, log) dx = d.MakeReport() x = libxml2.newDoc("1.0") x.setRootElement(dx) x.saveFormatFileEnc("-", "UTF-8", 1) return 0 except Exception, e: print "** EXCEPTION: %s" % str(e) return 1
def unit_test(rootdir): from pprint import pprint class unittest_ConfigDummy(object): def __init__(self, rootdir): self.config = {'installdir': '/usr/share/rteval'} self.__update_vars() def __update_vars(self): for k in self.config.keys(): self.__dict__[k] = self.config[k] try: ProcessWarnings() if os.getuid() != 0: print "** ERROR ** Must be root to run this unit_test()" return 1 log = Log() log.SetLogVerbosity(Log.DEBUG|Log.INFO) cfg = unittest_ConfigDummy(rootdir) d = DMIinfo(cfg, log) dx = d.MakeReport() x = libxml2.newDoc("1.0") x.setRootElement(dx) x.saveFormatFileEnc("-", "UTF-8", 1) return 0 except Exception, e: print "** EXCEPTION: %s" % str(e) return 1
def write_rss(self, rawdog, config, articles): doc = libxml2.newDoc("1.0") rss = doc.newChild(None, 'rss', None) rss.setProp('version', "2.0") rss.setProp('xmlns:dc', "http://purl.org/dc/elements/1.1/") rss.setProp('xmlns:atom', 'http://www.w3.org/2005/Atom') channel = rss.newChild(None, 'channel', None) channel.newChild(None, 'title', self.options["xmltitle"]) channel.newChild(None, 'link', self.options["xmllink"]) channel.newChild(None, 'language', self.options["xmllanguage"]) channel.newChild(None, 'description', self.options["xmldescription"]) atom_link = channel.newChild(None, 'atom:link', None) atom_link.setProp('href', self.options["xmlurl"]) atom_link.setProp('rel', 'self') atom_link.setProp('type', 'application/rss+xml') try: maxarticles = int(self.options["xmlmaxarticles"]) except ValueError: maxarticles = len(articles) for article in articles[:maxarticles]: xml_article = channel.newChild(None, 'item', None) self.article_to_xml(xml_article, rawdog, config, article) doc.saveFormatFile(self.options["outputxml"], 1) doc.freeDoc()
def write_opml(self, rawdog, config): doc = libxml2.newDoc("1.0") xml = doc.newChild(None, 'opml', None) xml.setProp('version', "1.1") xml.setProp('encoding', "utf-8") head = xml.newChild(None, 'head', None) head.newChild(None, 'title', self.options["xmltitle"]) now = rfc822_date(gmtime()) head.newChild(None, 'dateCreated', now) head.newChild(None, 'dateModified', now) head.newChild(None, 'ownerName', self.options["xmlownername"]) head.newChild(None, 'ownerEmail', self.options["xmlowneremail"]) body = xml.newChild(None, 'body', None) for url in sorted(rawdog.feeds.keys()): if not self.feeds.has_key(url): continue outline = body.newChild(None, 'outline', None) outline.setProp('text', self.feed_name(rawdog.feeds[url], config)) outline.setProp('type', 'rss') outline.setProp('xmlUrl', url) outline.setProp('htmlUrl',rawdog.feeds[url].feed_info.get("link")) outline.setProp('title',rawdog.feeds[url].get_html_name(config)) doc.saveFormatFile(self.options["outputopml"], 1) doc.freeDoc()
def unit_test(rootdir): import sys try: log = Log() log.SetLogVerbosity(Log.DEBUG|Log.INFO) osi = OSInfo(logger=log) print "Base OS: %s" % osi.get_base_os() print "Testing OSInfo::copy_dmesg('/tmp'): ", osi.copy_dmesg('/tmp') if os.path.isfile("/tmp/dmesg"): md5orig = subprocess.check_output(("md5sum","/var/log/dmesg")) md5copy = subprocess.check_output(("md5sum","/tmp/dmesg")) if md5orig.split(" ")[0] == md5copy.split(" ")[0]: print "PASS" else: print "FAIL (md5sum)" os.unlink("/tmp/dmesg") else: print "FAIL (copy failed)" print "Running sysreport/sosreport with output to current dir" osi.run_sysreport(".") osinfo_xml = osi.MakeReport() xml_d = libxml2.newDoc("1.0") xml_d.setRootElement(osinfo_xml) xml_d.saveFormatFileEnc("-", "UTF-8", 1) except Exception, e: import traceback traceback.print_exc(file=sys.stdout) print "** EXCEPTION %s", str(e) return 1
def get_series_xml(): """ This function returns an XML structure that contains all the series that are currently in airs, with all properties needed for XSLT -> HTML """ dom = libxml2.newDoc("1.0") root = libxml2.newNode("airs") dom.addChild(root) options = _createOptionsNode() root.addChild(options) items = libxml2.newNode("series") root.addChild(items) todaystr = series_list.date_to_str(datetime.datetime.now()) wdelta = series_list.idx_to_weekdelta(appcfg.options[appcfg.CFG_EPISODE_DELTA]) bottomstr = series_list.date_to_str(datetime.date.today() - datetime.timedelta(weeks = wdelta)) c = db.store.execute("select count(*) from episode where aired != '' and aired <= '%s'" "and aired > '%s' and new != 0" % (todaystr, bottomstr) ) items.setProp("airedcount", str(c.get_one()[0])) result = db.store.find(series_list.Series).order_by(series_list.Series.name) series = [serie for serie in result] for item in series: serie = libxml2.newNode("item") serie.setProp("name", item.name) serie.setProp("id", str(item.id)) serie.setProp("cancelled", str(item.postponed)) serie.setProp("folder", item.folder) seriespath = series_list.get_series_path(item) serie.setProp("mediacount", str(_getMediaCount(seriespath))) # report total number of episodes and the # episodes already seen c = db.store.execute("select count(*) from episode where series_id = %i and aired != '' and aired < '%s'" % \ (item.id, todaystr) ) totalcount = str(c.get_one()[0]) c = db.store.execute("select count(*) from episode where series_id = %i and status = %i" % \ (item.id, series_list.EP_SEEN)) seencount = str(c.get_one()[0]) #c = db.store.execute("select count(*) from episode where series_id = %i and status = 4" % item.id) #seencount = str(c.get_one()[0]) serie.setProp("seencount", seencount) serie.setProp("count", totalcount) items.addChild(serie) return dom
def _CreateWBXMLDoc(self, root_node_name, namespace): doc = libxml2.newDoc("1.0") doc.createIntSubset(AIRSYNC_DOC_NAME, AIRSYNC_PUBLIC_ID, AIRSYNC_SYSTEM_ID) root = doc.newChild(None, root_node_name, None) root.setProp("xmlns", namespace) return doc
def xml(self): if self._xml == None: self._xml = xml.newDoc("") elem = xml.newNode("file") elem.newProp("filename", self._translation_unit.spelling) self._xml.addChild(elem) self._create_xml(elem, self._translation_unit.cursor) return self._xml
def doDoc(self): """sets up our doc and rssnode attribute initially, rssnode will be redfined as we move along""" self.doc = libxml2.newDoc('1.0') self.xmlescape = self.doc.encodeEntitiesReentrant rss = self.doc.newChild(None, 'rss', None) rss.setProp('version', '2.0') self.rssnode = rss.newChild(None, 'channel', None)
def setUp(self): self.expected_events = list(expected_events) self.handler = StreamHandler(self) self.reader = xmlextra.StreamReader(self.handler) self.file = file("data/stream.xml") self.chunk_start = 0 self.chunk_end = 0 self.whole_stream = libxml2.newDoc("1.0")
def __prepare_data(self): d = libxml2.newDoc("1.0") n = libxml2.newNode('TestNode1') d.setRootElement(n) n2 = n.newTextChild(None, 'TestNode2', 'Just a little test') n2.newProp('test', 'true') for i in range(1, 5): n2 = n.newTextChild(None, 'TestNode3', 'Test line %i' % i) self.testdoc = d
def __init__(self): self.xml_file = '/var/lib/pacemaker-cloud/db_jeos.xml' try: self.doc = libxml2.parseFile(self.xml_file) self.doc_images = self.doc.getRootElement() except: self.doc = libxml2.newDoc("1.0") self.doc.newChild(None, "images", None); self.doc_images = self.doc.getRootElement()
def __prepare_data(self): d = libxml2.newDoc("1.0") n = libxml2.newNode("TestNode1") d.setRootElement(n) n2 = n.newTextChild(None, "TestNode2", "Just a little test") n2.newProp("test", "true") for i in range(1, 5): n2 = n.newTextChild(None, "TestNode3", "Test line %i" % i) self.testdoc = d
def __init__(self, node = None): self.node = node if (isinstance(node, str) or isinstance(node, unicode)): self.node = libxml2.parseDoc(node) elif (node == None): self.node = libxml2.newDoc("1.0") self.base = "" self._registerNamespaces()
def stanza_to_xml(self, stanza): d = libxml2.newDoc("1.0") r = d.newChild(None, "root", None) ns = r.newNs("jabber:server", None) r.setNs(ns) d.setRootElement(r) xml = stanza.xmlnode.docCopyNode(d, 1) r.addChild(xml) return xml,d
def __init__(self): self.xml_file = '/var/lib/pacemaker-cloud/db_jeos.xml' try: self.doc = libxml2.parseFile(self.xml_file) self.doc_images = self.doc.getRootElement() except: self.doc = libxml2.newDoc("1.0") self.doc.newChild(None, "images", None) self.doc_images = self.doc.getRootElement()
def stanza_to_xml(self, stanza): d = libxml2.newDoc("1.0") r = d.newChild(None, "root", None) ns = r.newNs("jabber:server", None) r.setNs(ns) d.setRootElement(r) xml = stanza.xmlnode.docCopyNode(d, 1) r.addChild(xml) return xml, d
def doc_open(self): self.doc = libxml2.newDoc("1.0") self.xml = self.doc.newChild(None, 'rss', None) self.xml.setProp('version', "2.0") self.xml.setProp('xmlns:dc', "http://purl.org/dc/elements/1.1/") self.xml.setProp('xmlns:atom', 'http://www.w3.org/2005/Atom') self.xml.newChild(None, 'channel', None)
def process_bibcodes_to_delete(extraction_directory, upload_mode): """method that creates the MarcXML for the bibcodes to delete""" logger.info("In function %s" % (inspect.stack()[0][3],)) #I create an unique file for all the bibcodes to delete: #I don't think it's necessary to split the content in groups, since the XML is really simple #I create the base object for the tree doc = libxml2.newDoc("1.0") root = doc.newChild(None, "collection", None) #then for each bibcode to delete I create the proper record for bibcode in BIBCODES_TO_DELETE_LIST: record = root.newChild(None, 'record', None) #I add to the record the 2 necessary datafields d970 = record.newChild(None, 'datafield', None) d970.setProp('tag', '970') d970.setProp('ind1', '') d970.setProp('ind2', '') #I create the subfield tag sub = d970.newChild(None, 'subfield', bibcode.replace('&', '&')) sub.setProp("code", "a") d980 = record.newChild(None, 'datafield', None) d980.setProp('tag', '980') d980.setProp('ind1', '') d980.setProp('ind2', '') #I create the subfield tag sub = d980.newChild(None, 'subfield', "DELETED") sub.setProp("code", "c") #I extract the node marcxml_string = doc.serialize('UTF-8', 1) #I remove the data doc.freeDoc() del doc #I write the bibcodes in the done bibcodes file w2f = write_files.WriteFile(extraction_directory, logger) w2f.write_done_bibcodes_to_file(BIBCODES_TO_DELETE_LIST) del w2f if upload_mode == 'concurrent': #I transform the xml in bibrecords bibrecord_object = [elem[0] for elem in bibrecord.create_records(marcxml_string)] #I upload the result with option append logger.warning('Upload of records to delete started.') bibupload_merger(bibrecord_object, logger, 'append') logger.warning('Upload of records to delete ended.') elif upload_mode == 'bibupload': filepath = os.path.join(settings.BASE_OUTPUT_PATH, extraction_directory, settings.BASE_BIBRECORD_FILES_DIR, settings.BIBCODE_TO_DELETE_OUT_NAME) with open(filepath, 'w') as marcxml_to_del_file: marcxml_to_del_file.write(marcxml_string) task_low_level_submission('bibupload', 'admin', '-a', filepath) logger.warning('File "%s" submitted to bibupload.' % filepath) else: logger.error('Upload mode "%s" not supported! File not uploaded' % upload_mode) return True
def run(self): # Clear the end-of-sync event self.evtSyncRunFinished.clear() # Temporarily uninstall the previous handler for the beginning of the # synchronization. The previous handler was for the auto-syncs, which # we disable temporarily while we are syncing here self.device.airsync.handler_block(self.device.sync_begin_handler_id) # Set up our own handler so we can catch the end of the Airsync phase self.sync_end_handler_id = self.device.airsync.connect("sync-end", self._sync_end_cb) if not self.auto_sync: # If the sync wasn't automatically started, we must manually request it doc = libxml2.newDoc("1.0") doc_node=doc.newChild(None,"sync",None) doc_node.setProp("xmlns", "http://schemas.microsoft.com/as/2004/core") doc_node.setProp("type", "Interactive") partnernode = doc_node.newChild(None,"partner",None) partnernode.setProp("id",self.device.PshipManager.GetCurrentPartnership().info.guid) self.logger.debug("run: sending request to device \n%s", doc_node.serialize("utf-8",1)) self.device.rapi_session.sync_start(doc_node.serialize("utf-8",0)) self.logger.debug("run: performing synchronization") self.evtSyncRunFinished.wait() if self.stopped: self.logger.warning("run: Synchronization stopped prematurely!") # TODO - we need to check if device has been pulled here, before doing # this, otherwise we get RAPI timeouts. self.logger.debug("run: calling RAPI sync_pause and sync_resume") self.device.rapi_session.sync_pause() self.device.rapi_session.sync_resume() if not self.stopped: self.logger.debug("run: saving itemDB") self.device.PshipManager.GetCurrentPartnership().SaveItemDB() self.logger.info("run: finished synchronization") self.device.syncing.unlock() self.device.airsync.handler_unblock(self.device.sync_begin_handler_id) if not self.stopped: self.device.Synchronized()
def skeleton(self, parent=None): """ Returns the XML representation of the L{Widget}. """ if parent is None: parent = libxml2.newDoc("1.0") this = parent.newChild(None, self.__class__.__name__, None) for prop, value in self.skelargs().items(): this.setProp(prop, repr(value)) return this
def create(self): """ Create an empty Metadata element from scratch """ self.doc = libxml2.newDoc("1.0") self.root = self.doc.newChild(None, "md", None) self.nsarc = self.root.newNs(ARC_NAMESPACE, None) self.nsgml = self.root.newNs(GML_NAMESPACE, "gml") self.doc.setNs(self.nsarc) self.doc.setNs(self.nsgml)
def _ConfigQuery(self, query_type, path, leaf=None, recursive=False, ctic=None): doc = libxml2.newDoc("1.0") doc_node = doc.newChild(None, "wap-provisioningdoc", None) parent = doc_node if path is not None: tokens = path.split(".") for token in tokens: node = parent.newChild(None, "characteristic", None) node.setProp("type", token) parent = node else: tokens = [] if query_type == QUERY_TYPE_GET: node = libxml2.newNode("characteristic-query") if not recursive: node.setProp("recursive", "false") node.setProp("type", leaf) elif query_type == QUERY_TYPE_REMOVE: node = libxml2.newNode("nocharacteristic") node.setProp("type", leaf) elif query_type == QUERY_TYPE_SET: node = characteristics.characteristic_tree_to_xml(ctic, doc) parent.addChild(node) logger.debug("_config_query: CeProcessConfig request is \n%s", doc_node.serialize("utf-8", 1)) reply = self.process_config(doc_node.serialize("utf-8", 0), 1) reply_doc = libxml2.parseDoc(reply) logger.debug("_config_query: CeProcessConfig response is \n%s", reply_doc.serialize("utf-8", 1)) reply_node = xml2util.GetNodeOnLevel(reply_doc, 2 + len(tokens)) if query_type != QUERY_TYPE_SET: return characteristics.characteristic_tree_from_xml(reply_node) else: return None
def __init__(self): self.xml_file = '/var/lib/pacemaker-cloud/db_deployable.xml' try: self.doc = libxml2.parseFile(self.xml_file) self.doc_images = self.doc.getRootElement() except: self.doc = libxml2.newDoc("1.0") self.doc.newChild(None, "deployables", None) self.doc_images = self.doc.getRootElement() self.cpe = cpe.Cpe() self.libvirt_conn = None
def encode(self, template): (tag, attr) = template doc = libxml2.newDoc("1.0") root = self._encode(doc, tag, attr.get('children'), attr.get('attributes', {}), attr.get('value', ''), attr.get('cdata', False), attr.get('ns')) doc.setRootElement(root) encoding = self.getProperty('encoding', 'utf-8') ret = '' if self.getProperty('write_prolog', True): ret = '<?xml version="1.0" encoding="%s"?>\n' % encoding ret += root.serialize(encoding = encoding, format = (self.getProperty('prettyprint', False) and 1 or 0)) return (ret, "XML data")
def __init__(self, pipe): chirp_common.FileBackedRadio.__init__(self, None) self._filename = pipe if self._filename and os.path.exists(self._filename): self.doc = libxml2.parseFile(self._filename) validate_doc(self.doc) else: self.doc = libxml2.newDoc("1.0") radio = self.doc.newChild(None, "radio", None) radio.newChild(None, "memories", None) radio.newChild(None, "banks", None) radio.newProp("version", "0.1.1")
def save(self): import libxml2Util import libxml2 outputDoc = libxml2.newDoc("1.0") self.serialise(outputDoc) result = outputDoc.serialize("ascii", 1) outputDoc.freeDoc() file = open(self.filename, "w") file.write(result) file.close() print "..Updated", self.filename self.changed = False
def __init__(self): try: import libxml2 except ImportError: self.enabled = False return else: self.enabled = False return self.doc = libxml2.newDoc("1.0") self.root = self.doc.newChild(None, "sos", None) self.commands = self.root.newChild(None, "commands", None) self.files = self.root.newChild(None, "files", None)
def foafdoc_open(self): self.foafdoc = libxml2.newDoc("1.0") self.foafxml = self.foafdoc.newChild(None, 'rdf:RDF', None) self.foafxml.setProp('xmlns:rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#") self.foafxml.setProp('xmlns:rdfs', "http://www.w3.org/2000/01/rdf-schema#") self.foafxml.setProp('xmlns:foaf', "http://xmlns.com/foaf/0.1/") self.foafxml.setProp('xmlns:rss', "http://purl.org/rss/1.0/") self.foafxml.setProp('xmlns:dc', "http://purl.org/dc/elements/1.1/") return self.foafxml.newChild(None, 'foaf:Group', None)