def _serialize_to_xml(obj, xmlnode): """Create XML representation of a Python object (list, tuple, dist, or basic number and string types).""" if type(obj) in (list, tuple): listnode = libxml2.newNode('list') for li in obj: itemnode = libxml2.newNode('li') _serialize_to_xml(li, itemnode) listnode.addChild(itemnode) xmlnode.addChild(listnode) elif type(obj) == dict: dictnode = libxml2.newNode('dict') for key, val in obj.iteritems(): itemnode = libxml2.newNode(key.encode('utf-8')) _serialize_to_xml(val, itemnode) dictnode.addChild(itemnode) xmlnode.addChild(dictnode) elif type(obj) in (str, unicode, int, long, float, complex, bool): content = libxml2.newText(unicode(obj).encode('utf-8')) xmlnode.addChild(content) elif type(obj) == type(None): pass else: raise TypeError('Unsupported type %s while serializing to xml' % type(obj))
def _add_type_info(self, parent, type, line_number): elem = xml.newNode("type") elem.newProp("line_number", str(line_number)) parent.addChild(elem) canonical_type = type.get_canonical() elem.newProp("canonical_kind", canonical_type.kind.name) elem.newProp("kind", type.kind.name) decl_name = canonical_type.get_declaration().displayname if decl_name: elem.newProp("declaration", decl_name) qualifiers = [] if type.is_const_qualified(): qualifiers.append("const") if type.is_restrict_qualified(): qualifiers.append("restrict") if type.is_volatile_qualified(): qualifiers.append("volatile") if len(qualifiers) > 0: elem.newProp("qualifiers", str(qualifiers)) if canonical_type.kind == ci.TypeKind.POINTER: self._add_type_info(elem, canonical_type.get_pointee(), line_number) if canonical_type.kind in [ci.TypeKind.FUNCTIONPROTO, ci.TypeKind.FUNCTIONNOPROTO]: result = xml.newNode("result") elem.addChild(result) self._add_type_info(result, type.get_result(), line_number)
def genxml(self, x): if self.type == 'system': x.openblock(self.type, {'description': self.description}) else: x.openblock(self.type, {'id': self.id, 'priority': self.priority}) x.openblock('statistics') x.taggedvalue('samples', str(self.numsamples)) x.taggedvalue('minimum', str(self.min), {"unit": "us"}) x.taggedvalue('maximum', str(self.max), {"unit": "us"}) x.taggedvalue('median', str(self.median), {"unit": "us"}) x.taggedvalue('mode', str(self.mode), {"unit": "us"}) x.taggedvalue('range', str(self.range), {"unit": "us"}) x.taggedvalue('mean', str(self.mean), {"unit": "us"}) x.taggedvalue('mean_absolute_deviation', str(self.mad), {"unit": "us"}) x.taggedvalue('variance', str(self.variance), {"unit": "us"}) x.taggedvalue('standard_deviation', str(self.stddev), {"unit": "us"}) x.closeblock() h = libxml2.newNode('histogram') h.newProp('nbuckets', str(len(self.samples))) keys = self.samples.keys() keys.sort() for k in keys: b = libxml2.newNode('bucket') b.newProp('index', str(k)) b.newProp('value', str(self.samples[k])) h.addChild(b) x.AppendXMLnodes(h) x.closeblock()
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
def __parseToXML(self, node, data): # All supported variable types needs to be set up # here. TypeError exception will be raised on # unknown types. t = type(data) if t is unicode or t is str or t is int or t is float: n = libxml2.newText(self.__encode(data)) node.addChild(n) elif t is bool: v = data and "1" or "0" n = libxml2.newText(self.__encode(v)) node.addChild(n) elif t is dict: for (key, val) in data.iteritems(): node2 = libxml2.newNode(self.__encode(self.parsedata_prefix + key, True)) self.__parseToXML(node2, val) node.addChild(node2) elif t is tuple: for v in data: if type(v) is dict: self.__parseToXML(node, v) else: n = libxml2.newNode(self.tuple_tagname) self.__parseToXML(n, v) node.addChild(n) else: raise TypeError, "unhandled type (%s) for value '%s'" % (type(data), unicode(data))
def MakeReport(self): rep_n = libxml2.newNode('cyclictest') rep_n.newProp('command_line', ' '.join(self.__cmd)) # If it was detected cyclictest was aborted somehow, # report the reason abrt_n = libxml2.newNode('abort_report') abrt = False if self.__breaktraceval: abrt_n.newProp('reason', 'breaktrace') btv_n = abrt_n.newChild(None, 'breaktrace', None) btv_n.newProp('latency_threshold', str(self.__cfg.breaktrace)) btv_n.newProp('measured_latency', str(self.__breaktraceval)) abrt = True # Only add the <abort_report/> node if an abortion happened if abrt: rep_n.addChild(abrt_n) rep_n.addChild(self.__cyclicdata["system"].MakeReport()) for thr in self.__cpus: if str(thr) not in self.__cyclicdata: continue rep_n.addChild(self.__cyclicdata[str(thr)].MakeReport()) return rep_n
def genxml(self, x): if self.type == 'system': x.openblock(self.type, {'description':self.description}) else: x.openblock(self.type, {'id': self.id, 'priority': self.priority}) x.openblock('statistics') x.taggedvalue('samples', str(self.numsamples)) x.taggedvalue('minimum', str(self.min), {"unit": "us"}) x.taggedvalue('maximum', str(self.max), {"unit": "us"}) x.taggedvalue('median', str(self.median), {"unit": "us"}) x.taggedvalue('mode', str(self.mode), {"unit": "us"}) x.taggedvalue('range', str(self.range), {"unit": "us"}) x.taggedvalue('mean', str(self.mean), {"unit": "us"}) x.taggedvalue('mean_absolute_deviation', str(self.mad), {"unit": "us"}) x.taggedvalue('variance', str(self.variance), {"unit": "us"}) x.taggedvalue('standard_deviation', str(self.stddev), {"unit": "us"}) x.closeblock() h = libxml2.newNode('histogram') h.newProp('nbuckets', str(len(self.samples))) keys = self.samples.keys() keys.sort() for k in keys: b = libxml2.newNode('bucket') b.newProp('index', str(k)) b.newProp('value', str(self.samples[k])) h.addChild(b) x.AppendXMLnodes(h) x.closeblock()
def add_xml_font(parent_node, name, face_name): fontset = libxml2.newNode('FontSet') fontset.setProp('name', name) font = libxml2.newNode('Font') font.setProp('face-name', face_name) fontset.addChild(font) parent_node.addChild(fontset)
def get_html(self, root = True): assert (self.edit_mode == "html") html_node = libxml2.newNode(DOCBOOK_TO_HTML_NODES[self._xml_root.name]) html_node.newProp("data-docbook-type", self._xml_root.name) self._docbook_to_html_process_properties(self._xml_root, html_node) if root: last_child = None for i in self._children: if i.get_xml_node().name != "text": last_child = i if (i.element_type in ["chapter"] or i.element_type.startswith("sect")): child_node = i.get_html(False) else: child_node = self._docbook_to_html_node(i.get_xml_node()) if type(child_node) != list: child_node = [child_node] for j in child_node: html_node.addChild(j) if last_child and (last_child.get_xml_node().name == "chapter" or last_child.get_xml_node().name.startswith("sect")): html_node.addChild(libxml2.newNode("br")) else: html_node.newProp("class", "subsection %s mceNonEditable" % self._xml_root.name) html_node.addChild(libxml2.newText("Subsection (%s) \"%s\"" % (self._xml_root.name, self.title))) return html_node
def MakeReport(self): rep_n = libxml2.newNode("uname") baseos_n = libxml2.newNode("baseos") baseos_n.addContent(self.get_base_os()) rep_n.addChild(baseos_n) (sys, node, release, ver, machine) = os.uname() isrt = 1 if ver.find(' RT ') == -1: isrt = 0 node_n = libxml2.newNode("node") node_n.addContent(node) rep_n.addChild(node_n) arch_n = libxml2.newNode("arch") arch_n.addContent(machine) rep_n.addChild(arch_n) kernel_n = libxml2.newNode("kernel") kernel_n.newProp("is_RT", str(isrt)) kernel_n.addContent(release) rep_n.addChild(kernel_n) return rep_n
def _docbook_to_html(self, xml_node, is_root = False): if xml_node.name == "title" and xml_node.parent.name == "figure": html_node = libxml2.newNode("figcaption") elif xml_node.name == "emphasis": if xml_node.prop("role") == "bold": html_node = libxml2.newNode("strong") else: html_node = libxml2.newNode("em") else: if xml_node.name in DOCBOOK_TO_HTML_NODES: html_node = libxml2.newNode(DOCBOOK_TO_HTML_NODES[xml_node.name]) else: html_node = libxml2.newNode("span") html_node.newProp("data-docbook-type", xml_node.name) self._docbook_to_html_process_properties(xml_node, html_node) if xml_node.name in DOCBOOK_ELEMENT_TYPE_TO_CLASS: html_node.newProp("class", xml_node.name) html_node.newProp("data-docbook-type", xml_node.name) child = xml_node.children while child: html_child = self._docbook_to_html_node(child) if type(html_child) == list: for i in html_child: html_node.addChild(i) elif html_child != None: html_node.addChild(html_child) child = child.next return html_node
def MakeReport(self): rep_n = libxml2.newNode('cyclictest') rep_n.newProp('command_line', ' '.join(self.__cmd)) # If it was detected cyclictest was aborted somehow, # report the reason abrt_n = libxml2.newNode('abort_report') abrt = False if self.__breaktraceval: abrt_n.newProp('reason', 'breaktrace') btv_n = abrt_n.newChild(None, 'breaktrace', None) btv_n.newProp('latency_threshold', str(self.__cfg.breaktrace)) btv_n.newProp('measured_latency', str(self.__breaktraceval)) abrt = True # Only add the <abort_report/> node if an abortion happened if abrt: rep_n.addChild(abrt_n) rep_n.addChild(self.__cyclicdata["system"].MakeReport()) for thr in range(0, self.__numcores): if str(thr) not in self.__cyclicdata: continue rep_n.addChild(self.__cyclicdata[str(thr)].MakeReport()) return rep_n
def genrate_xml_tree(csv_files, out_data, folder): for csv_name in csv_files: print ' ---- generating the xml of %s file' % (csv_name, ) lines = csv.DictReader(open(folder + '/' + csv_name)) line = lines.next() line.pop('model') line.pop('id') fields_type = line field_names = fields_type.keys() for line in lines: out_record = libxml2.newNode('record') out_record.setProp('id', line.pop('id')) out_record.setProp('model', line.pop('model')) out_data.addChild(out_record) for field_name in field_names: if line[field_name]: out_field = libxml2.newNode('field') out_field.setProp('name', field_name) type_field = fields_type[field_name] if not set_property(type_field, line[field_name], out_field, folder): out_field.setContent(line[field_name]) out_record.addChild(out_field)
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 _build_node(self): ciphers = ",".join([ "SSL_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA", "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA", "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA", "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", ]) # Setup our node configuration connector = libxml2.newNode("Connector") self._add_attributes(connector, [ ("port", self.port), ("protocol", "HTTP/1.1"), ("SSLEnabled", "true"), ("maxThreads", "150"), ("scheme", "https"), ("secure", "true"), ]) sslconfig = libxml2.newNode("SSLHostConfig") self._add_attributes( sslconfig, [ ("certificateVerification", "optional"), # Note SSLv3 is not included, to avoid poodle # For the time being, TLSv1 needs to stay enabled in Satellite deployments to support # existing python-rhsm based clients (RHEL5). ("protocols", "+TLSv1,+TLSv1.1,+TLSv1.2"), ("sslProtocol", "TLS"), ("truststoreFile", "conf/keystore"), ("truststorePassword", "password"), ("truststoreType", "JKS"), ("ciphers", ciphers), ]) certificate = libxml2.newNode("Certificate") self._add_attributes(certificate, [ ("certificateKeystoreFile", "conf/keystore"), ("certificateKeystorePassword", "password"), ("certificateKeystoreType", "JKS"), ]) # Put it all together # The libxml2 bindings don't provide an obvious way to output indented XML, so we fake # it here to make it mostly human-readable. connector.addChild(libxml2.newText("\n ")) connector.addChild(sslconfig) connector.addChild(libxml2.newText("\n")) sslconfig.addChild(libxml2.newText("\n ")) sslconfig.addChild(certificate) sslconfig.addChild(libxml2.newText("\n ")) # Return our top-level node return connector
def MakeReport(self): rep_n = libxml2.newNode("cmdlineInfo") cmdline_n = libxml2.newNode("cmdline") cmdlineStr = self.read_cmdline() cmdline_n.addContent(cmdlineStr) self.__log(Log.DEBUG, cmdlineStr) rep_n.addChild(cmdline_n) return rep_n
def journal_parser(out_data, folder, args): """ This method generate the account journals xml records taking in base the account account records in the account account csv of type liquidity. @param acc_data_list: list of account data information. """ # TODO: # - change the jorunal code to upper case everytime (this is helps for # thouse personal accounts (no numbers). # - try to use more account numbers in the journal code. # - manage the uniqueness of the journal code before write the xml. my_model = 'account.journal' bank_data = get_bank_data(folder) pattern = re.compile(r'(cta|cuenta|cc|cte|ca|no)(\.|-)*(\s)*', re.DOTALL) pattern2 = re.compile(r'(\s|\.)', re.DOTALL) field_type = { 'name': 'str', 'code': 'str', 'type': 'str', 'default_credit_account_id': 'ref', 'default_debit_account_id': 'ref', 'company_id': 'ref', 'currency': 'ref', } for (index, line) in enumerate(bank_data, 1): value = dict( company_id='base.main_company', type='bank') value['name'] = unicode(line['aa_name'], 'utf-8') value['name'] = unidecode.unidecode(value['name']) value['default_credit_account_id'] = line['aa_xml_id'] value['default_debit_account_id'] = line['aa_xml_id'] xml_id = pattern.sub('', value['name'].lower()) xml_id = pattern2.sub('_', xml_id) out_record = libxml2.newNode('record') out_record.setProp('id', 'aj_{}_{}'.format( args['company_name'], line['aa_xml_id'])) out_record.setProp('model', my_model) value['code'] = 'BJ{0:03d}'.format(index) if line['acc_currency']: value['currency'] = line['acc_currency'] for aj_field in value.keys(): out_field = libxml2.newNode('field') out_field.setProp('name', aj_field) if field_type[aj_field] == 'str': out_field.setContent(value[aj_field]) elif field_type[aj_field] == 'ref': out_field.setProp('ref', value[aj_field]) else: assert False, ('Error. This field type is not defined yet.' 'define Field %s' % (aj_field,)) out_record.addChild(out_field) out_data.addChild(out_record) return True
def _build_node(self): ciphers = ",".join([ "SSL_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA", "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA", "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA", "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", ]) # Setup our node configuration connector = libxml2.newNode("Connector") self._add_attributes(connector, [ ("port", self.port), ("protocol", "HTTP/1.1"), ("SSLEnabled", "true"), ("maxThreads", "150"), ("scheme", "https"), ("secure", "true"), ]) sslconfig = libxml2.newNode("SSLHostConfig") self._add_attributes(sslconfig, [ ("certificateVerification", "optional"), # Note SSLv3 is not included, to avoid poodle # For the time being, TLSv1 needs to stay enabled in Satellite deployments to support # existing python-rhsm based clients (RHEL5). ("protocols", "+TLSv1,+TLSv1.1,+TLSv1.2"), ("sslProtocol", "TLS"), ("truststoreFile", "conf/keystore"), ("truststorePassword", "password"), ("truststoreType", "JKS"), ("ciphers", ciphers), ]) certificate = libxml2.newNode("Certificate") self._add_attributes(certificate, [ ("certificateKeystoreFile", "conf/keystore"), ("certificateKeystorePassword", "password"), ("certificateKeystoreType", "JKS"), ]) # Put it all together # The libxml2 bindings don't provide an obvious way to output indented XML, so we fake # it here to make it mostly human-readable. connector.addChild(libxml2.newText("\n ")) connector.addChild(sslconfig) connector.addChild(libxml2.newText("\n")) sslconfig.addChild(libxml2.newText("\n ")) sslconfig.addChild(certificate) sslconfig.addChild(libxml2.newText("\n ")) # Return our top-level node return connector
def journal_parser(out_data, folder, args): """ This method generate the account journals xml records taking in base the account account records in the account account csv of type liquidity. @param acc_data_list: list of account data information. """ # TODO: # - change the jorunal code to upper case everytime (this is helps for # thouse personal accounts (no numbers). # - try to use more account numbers in the journal code. # - manage the uniqueness of the journal code before write the xml. my_model = 'account.journal' bank_data = get_bank_data(folder) pattern = re.compile(r'(cta|cuenta|cc|cte|ca|no)(\.|-)*(\s)*', re.DOTALL) pattern2 = re.compile(r'(\s|\.)', re.DOTALL) field_type = { 'name': 'str', 'code': 'str', 'type': 'str', 'default_credit_account_id': 'ref', 'default_debit_account_id': 'ref', 'company_id': 'ref', 'currency': 'ref', } for (index, line) in enumerate(bank_data, 1): value = dict(company_id='base.main_company', type='bank') value['name'] = unicode(line['aa_name'], 'utf-8') value['name'] = unidecode.unidecode(value['name']) value['default_credit_account_id'] = line['aa_xml_id'] value['default_debit_account_id'] = line['aa_xml_id'] xml_id = pattern.sub('', value['name'].lower()) xml_id = pattern2.sub('_', xml_id) out_record = libxml2.newNode('record') out_record.setProp( 'id', 'aj_{}_{}'.format(args['company_name'], line['aa_xml_id'])) out_record.setProp('model', my_model) value['code'] = 'BJ{0:03d}'.format(index) if line['acc_currency']: value['currency'] = line['acc_currency'] for aj_field in value.keys(): out_field = libxml2.newNode('field') out_field.setProp('name', aj_field) if field_type[aj_field] == 'str': out_field.setContent(value[aj_field]) elif field_type[aj_field] == 'ref': out_field.setProp('ref', value[aj_field]) else: assert False, ('Error. This field type is not defined yet.' 'define Field %s' % (aj_field, )) out_record.addChild(out_field) out_data.addChild(out_record) return True
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 get_xml_nodes(self, doc, obj_name=None): elements, attributes = self.get_elements_and_attributes() if obj_name is None: obj_name = self.__class__.__name__ root = libxml2.newNode(obj_name) for name in attributes: name_info = self._xml_info[name] typecast = name_info.get('export_typecast', str) value = getattr(self, name) if value is not None: root.setProp(name, typecast(value)) for name in elements: try: if self._xml_info == 'unstructured': typecast = string_to_xmlnode list_item_name = None else: name_info = self._xml_info[name] typecast = name_info.get('export_typecast', string_to_xmlnode) list_item_name = name_info.get('list') value = getattr(self, name) if value is None or isinstance(value, list) and len(value) == 0: continue if list_item_name: # Element is list container, iterate over list items element_node = libxml2.newNode(name) root.addChild(element_node) for item in value: if isinstance(item, XmlSerialize): child = item.get_xml_nodes(doc, list_item_name) element_node.addChild(child) else: list_item_node = libxml2.newNode(list_item_name) element_node.addChild(list_item_node) child = typecast(doc, item) list_item_node.addChild(child) else: # Element is scalar if isinstance(value, XmlSerialize): child = value.get_xml_nodes(doc, name) root.addChild(child) else: element_node = libxml2.newNode(name) root.addChild(element_node) child = typecast(doc, value) element_node.addChild(child) except Exception as e: syslog.syslog(syslog.LOG_ERR, "%s.%s value=%s" % (self.__class__.__name__, name, value)) return root
def create_xml_node(self, name, context_dict): node = libxml2.newNode(name) for k in context_dict.keys(): if (type(context_dict[k])==dict): childNode = self.create_xml_node(k, context_dict[k]) node.addChild(childNode) else: childNode = libxml2.newNode(k) childNode.addContent(context_dict[k]) node.addChild(childNode) return node
def create_xml_node(self, name, context_dict): node = libxml2.newNode(name) for k in context_dict.keys(): if (type(context_dict[k]) == dict): childNode = self.create_xml_node(k, context_dict[k]) node.addChild(childNode) else: childNode = libxml2.newNode(k) childNode.addContent(context_dict[k]) node.addChild(childNode) return node
def _build_node(self): # <Connector port="8443" protocol="HTTP/1.1" # scheme="https" # secure="true" # SSLEnabled="true" # maxThreads="150"> # # <SSLHostConfig certificateVerification="optional" # protocols="+TLSv1,+TLSv1.1,+TLSv1.2" # sslProtocol="TLS" # ciphers="SSL_RSA_WITH_3DES_EDE_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"> # # <Certificate # certificateFile="/etc/candlepin/certs/candlepin-ca.crt" # certificateKeyFile="/etc/candlepin/certs/candlepin-ca.key" # type="RSA" # /> # </SSLHostConfig> # </Connector> connector = libxml2.newNode("Connector") self._add_attributes(connector, self.attributes) ssl_host_config = libxml2.newNode("SSLHostConfig") self._add_attributes(ssl_host_config, [ ("certificateVerification", "optional"), # Note SSLv3 is not included, to avoid poodle # For the time being, TLSv1 needs to stay enabled in Satellite deployments to support # existing python-rhsm based clients (RHEL5). ("protocols", "+TLSv1,+TLSv1.1,+TLSv1.2"), ("sslProtocol", "TLS"), ("ciphers", ",".join(SSL_CIPHERS)) ]) certificate = libxml2.newNode("Certificate") self._add_attributes(certificate, [ ('certificateFile', '/etc/candlepin/certs/candlepin-ca.crt'), ('certificateKeyFile', '/etc/candlepin/certs/candlepin-ca.key'), ('type', 'RSA') ]) # Put it all together # The libxml2 bindings don't provide an obvious way to output indented XML, so we fake # it here to make it mostly human-readable. connector.addChild(libxml2.newText("\n ")) connector.addChild(ssl_host_config) connector.addChild(libxml2.newText("\n")) ssl_host_config.addChild(libxml2.newText("\n ")) ssl_host_config.addChild(certificate) ssl_host_config.addChild(libxml2.newText("\n ")) # return return connector
def setDateAdded(self, dateadded): dateaddedValueNodes = self.xmlNode.xpathEval("date[preceding-sibling::* = 'Date Added'][1]") if len(dateaddedValueNodes) == 0: newdateaddedKeyNode = libxml2.newNode("key") self.xmlNode.addChild(newdateaddedKeyNode) newdateaddedKeyNode.setContent("Date Added") dateaddedValueNode = libxml2.newNode("first-seen") newdateaddedKeyNode.addSibling(dateaddedValueNode) else: dateaddedValueNode = dateaddedValueNodes[0] dateaddedValueNode.setContent(str(dateadded))
def setPlaycount(self, playcount): playcountValueNodes = self.xmlNode.xpathEval("integer[preceding-sibling::* = 'Play Count'][1]") if len(playcountValueNodes) == 0: newPlaycountKeyNode = libxml2.newNode("key") self.xmlNode.addChild(newPlaycountKeyNode) newPlaycountKeyNode.setContent("Play Count") playcountValueNode = libxml2.newNode("integer") newPlaycountKeyNode.addSibling(playcountValueNode) else: playcountValueNode = playcountValueNodes[0] playcountValueNode.setContent(str(playcount))
def setRating(self, rating): ratingValueNodes = self.xmlNode.xpathEval("integer[preceding-sibling::* = 'Rating'][1]") if len(ratingValueNodes) == 0: newRatingKeyNode = libxml2.newNode("key") self.xmlNode.addChild(newRatingKeyNode) newRatingKeyNode.setContent("Rating") ratingValueNode = libxml2.newNode("integer") newRatingKeyNode.addSibling(ratingValueNode) else: ratingValueNode = ratingValueNodes[0] ratingValueNode.setContent(str(rating))
def newVol(self, req): conn = util.getConnection() ret = dict() try: if not req.args.has_key('source'): raise BaseException() pool = conn.storagePoolLookupByName(req.args['source'][0]) doc = libxml2.parseDoc(pool.XMLDesc(0)) root = doc.getRootElement() pool_type = root.prop('type') poolInfo = pool.info() disk_size = int(req.args['size'][0]) if disk_size * 1024 * 1024 * 1024 > poolInfo[3]: raise BaseException() disk_prefix = None if req.args.has_key('prefix'): disk_prefix = req.args['prefix'][0] else: disk_prefix = str(uuid.uuid4()) disk_idx = 1 disk_name = disk_prefix + '-' + str(disk_idx) while True: try: pool.storageVolLookupByName(disk_name) disk_idx = disk_idx + 1 disk_name = disk_prefix + '-' + str(disk_idx) continue except: break volDoc = libxml2.parseDoc('<volume/>') volRoot = volDoc.getRootElement() node = libxml2.newNode('name') node.setContent(disk_name) volRoot.addChild(node) node = libxml2.newNode('capacity') node.newProp('unit', 'G') node.setContent(str(disk_size)) volRoot.addChild(node) if pool_type == 'dir': node = libxml2.newNode('allocation') node.newProp('unit', 'G') node.setContent('0') volRoot.addChild(node) vol = pool.createXML(volRoot.serialize(), 0) ret['prefix'] = disk_prefix ret['path'] = vol.path() ret['size'] = vol.info()[1] except: pass finally: conn.close() return ret
def postProcessXmlTranslation(self, doc, language, translators, translation): """Sets a language and translators in "doc" tree. "translators" is a string consisted of "Name <email>, years" pairs of each translator, separated by newlines.""" root = doc.getRootElement() # DocBook documents can be something other than article, handle that as well in the future while root and root.name != 'article' and root.name != 'book': root = root.next if root and (root.name == 'article' or root.name == 'book'): root.setProp('lang', language) else: return if translators == self.getStringForTranslators(): return elif translators: # Now, lets find 'articleinfo' (it can be something else, but this goes along with 'article') ai = self._find_articleinfo(root) if not ai: return # Now, lets do one translator at a time lines = translators.split("\n") for line in lines: line = line.strip() match = re.match(r"^([^<,]+)\s*(?:<([^>,]+)>)?,?\s*(.*)$", line) if match: last = self._find_lastcopyright(ai) copy = libxml2.newNode("othercredit") # copy.setProp("class", "translator") if last: copy = last.addNextSibling(copy) else: ai.addChild(copy) if match.group(3): copy.newChild(None, "year", match.group(3).encode('utf-8')) holder = libxml2.newNode("othername") if match.group(1) and match.group(2): holder.setContent( (match.group(1) + "(").encode('utf-8')) holder.newChild(None, "email", match.group(2).encode('utf-8')) holder.addContent(")") elif match.group(1): holder.setContent(match.group(1).encode('utf-8')) elif match.group(2): holder.setContent(match.group(2).encode('utf-8')) copy.newChild(None, "contrib", translation.encode('utf-8')) copy.addChild(holder)
def setPlaycount(self, playcount): playcountValueNodes = self.xmlNode.xpathEval( "integer[preceding-sibling::* = 'Play Count'][1]") if len(playcountValueNodes) == 0: newPlaycountKeyNode = libxml2.newNode("key") self.xmlNode.addChild(newPlaycountKeyNode) newPlaycountKeyNode.setContent("Play Count") playcountValueNode = libxml2.newNode("integer") newPlaycountKeyNode.addSibling(playcountValueNode) else: playcountValueNode = playcountValueNodes[0] playcountValueNode.setContent(str(playcount))
def setRating(self, rating): ratingValueNodes = self.xmlNode.xpathEval( "integer[preceding-sibling::* = 'Rating'][1]") if len(ratingValueNodes) == 0: newRatingKeyNode = libxml2.newNode("key") self.xmlNode.addChild(newRatingKeyNode) newRatingKeyNode.setContent("Rating") ratingValueNode = libxml2.newNode("integer") newRatingKeyNode.addSibling(ratingValueNode) else: ratingValueNode = ratingValueNodes[0] ratingValueNode.setContent(str(rating))
def setDateAdded(self, dateadded): dateaddedValueNodes = self.xmlNode.xpathEval( "date[preceding-sibling::* = 'Date Added'][1]") if len(dateaddedValueNodes) == 0: newdateaddedKeyNode = libxml2.newNode("key") self.xmlNode.addChild(newdateaddedKeyNode) newdateaddedKeyNode.setContent("Date Added") dateaddedValueNode = libxml2.newNode("first-seen") newdateaddedKeyNode.addSibling(dateaddedValueNode) else: dateaddedValueNode = dateaddedValueNodes[0] dateaddedValueNode.setContent(str(dateadded))
def MakeReport(self): srvs = self.services_get() rep_n = libxml2.newNode("Services") rep_n.newProp("init", self.__init) for s in srvs: srv_n = libxml2.newNode("Service") srv_n.newProp("state", srvs[s]) srv_n.addContent(s) rep_n.addChild(srv_n) return rep_n
def setPlayDate(self, playdate): playdateValueNodes = self.xmlNode.xpathEval( "integer[preceding-sibling::* = 'Play Date UTC'][1]") if len(playdateValueNodes) == 0: newPlayDateKeyNode = libxml2.newNode("key") self.xmlNode.addChild(newPlayDateKeyNode) newPlayDateKeyNode.setContent("Play Date UTC") playdateValueNode = libxml2.newNode("last-played") newPlayDateKeyNode.addSibling(playdateValueNode) else: playdateValueNode = playdateValueNodes[0] playdateValueNode.setContent(str(playdate))
def get_xml_nodes(self, doc, obj_name=None): elements, attributes = self.get_elements_and_attributes() if obj_name is None: obj_name = self.__class__.__name__ root = libxml2.newNode(obj_name) for name in attributes: name_info = self._xml_info[name] typecast = name_info.get('export_typecast', str) value = getattr(self, name) if value is not None: root.setProp(name, typecast(value)) for name in elements: try: if self._xml_info == 'unstructured': typecast = string_to_xmlnode list_item_name = None else: name_info = self._xml_info[name] typecast = name_info.get('export_typecast', string_to_xmlnode) list_item_name = name_info.get('list') value = getattr(self, name) if value is None or isinstance(value, list) and len(value) == 0: continue if list_item_name: # Element is list container, iterate over list items element_node = libxml2.newNode(name) root.addChild(element_node) for item in value: if isinstance(item, XmlSerialize): child = item.get_xml_nodes(doc, list_item_name) element_node.addChild(child) else: list_item_node = libxml2.newNode(list_item_name) element_node.addChild(list_item_node) child = typecast(doc, item) list_item_node.addChild(child) else: # Element is scalar if isinstance(value, XmlSerialize): child = value.get_xml_nodes(doc, name) root.addChild(child) else: element_node = libxml2.newNode(name) root.addChild(element_node) child = typecast(doc, value) element_node.addChild(child) except Exception, e: syslog.syslog(syslog.LOG_ERR, "%s.%s value=%s" % (self.__class__.__name__, name, value))
def __generate_internal_xml(self): "Private method: Generates the internal XML needed for XSLT template" # Generate new XML document and set <submit/> to be the root tag xml = libxml2.newDoc('1.0') submit_node = libxml2.newNode('submit') xml.setRootElement(submit_node) # Add white board text if set wb_node = libxml2.newNode('whiteboard') if self.whiteboard is not None: wb_node.addChild(libxml2.newText(self.whiteboard)) submit_node.addChild(wb_node) # Add the recipe node ... recipe_node = libxml2.newNode('recipe') submit_node.addChild(recipe_node) # ... and add all the defined arguments for key in self.jobargs.GetArgumentKeys(): if self.jobargs.IsProcessed(key): continue (tagname, tagnode) = self.jobargs.CreateTag(key) arg = self.jobargs.GetNextArgumentOnTag(tagname) while arg is not None: if arg['value']: recipe_node.addChild(tagnode) if arg['tagvaluetype'] == 'value': tagnode.addChild( libxml2.newText( self.__format_xml_value( arg['argtype'], arg['value']))) elif arg['tagvaluetype'] == 'attribute': tagnode.newProp( arg['tagvaluename'], self.__format_xml_value(arg['argtype'], arg['value'])) elif arg['tagvaluetype'] == "list": for listval in arg["value"].split(","): tagchild_n = self.jobargs.CreateChildTag(key) tagchild_n.addChild(libxml2.newText(listval)) else: raise Exception( "Unknown <tag/> type '%s' found in '%s'" % (arg['tagvaluetype'], key)) self.jobargs.SetProcessed() arg = self.jobargs.GetNextArgumentOnTag(tagname) return xml
def MakeReport(self): rep_n = libxml2.newNode("Memory") numa_n = libxml2.newNode("numa_nodes") numa_n.addContent(str(self.mem_get_numa_nodes())) rep_n.addChild(numa_n) memsize = self.mem_get_size() mem_n = libxml2.newNode("memory_size") mem_n.addContent("%.3f" % memsize[0]) mem_n.newProp("unit", memsize[1]) rep_n.addChild(mem_n) return rep_n
def doParamList(parentNode, srcNode): """ Convert the parameter list """ params = srcNode.xpathEval2("attributelist/parmlist/parm") if params: plist = libxml2.newNode("paramlist") for p in params: pnode = libxml2.newNode("param") pnode.setProp("name", getAttr(p, "name")) pnode.setProp("type", fixType(getAttr(p, "type"))) pnode.setProp("default", getAttr(p, "value")) plist.addChild(pnode) parentNode.addChild(plist)
def __create_property(self, propName, value): '''Creates a property xml node for output ''' node = libxml2.newNode('property') node.setProp('name', propName) node.addContent(value) return node
def CreateChildTag(self, key): """Create a child node for a node created by CreateTag(), used by lists""" tagname = self.arguments[key]['tagname_childs'] tagnode = libxml2.newNode(tagname) self.current_node.addChild(tagnode) return tagnode
def _append_copyright(self, root, translators): # Now, lets find 'articleinfo' (it can be something else, but this goes along with 'article') ai = self._find_articleinfo(root) if not ai: return # Now, lets do one translator at a time lines = translators.split("\n") for line in lines: line = line.strip() match = re.match(r"^([^<,]+)\s*(?:<([^>,]+)>)?,\s*(.*)$", line) if match: last = self._find_lastcopyright(ai) copy = libxml2.newNode("copyright") if last: copy = last.addNextSibling(copy) else: ai.addChild(copy) if match.group(3): copy.newChild(None, "year", match.group(3).encode('utf-8')) if match.group(1) and match.group(2): holder = match.group(1).strip()+" (%s)" % match.group(2).strip() elif match.group(1): holder = match.group(1) elif match.group(2): holder = match.group(2) else: holder = "???" copy.newChild(None, "holder", holder.encode('utf-8'))
def _html_to_docbook_node(self, html_node): if html_node.name == "text": return html_node.copyNode(False) elif html_node.prop("data-docbook-type") == "footnote": res = libxml2.newNode("footnote") child = libxml2.htmlParseDoc(html_node.prop("data-footnote"), "utf-8").getRootElement().children.children while child: res.addChild(self._html_to_docbook(child)) child = child.next self._html_to_docbook_process_properties(html_node, res) return res elif html_node.name in ["div", "span"] and html_node.prop("data-docbook-type") in DOCBOOK_ELEMENT_TYPE_TO_CLASS: res = self._html_to_docbook(html_node) self._html_to_docbook_process_properties(html_node, res) return res elif html_node.name in HTML_TO_DOCBOOK_NODES or html_node.prop("data-docbook-type"): res = self._html_to_docbook(html_node) self._html_to_docbook_process_properties(html_node, res) return res else: if not html_node.name in HTML_JUMP_NODES: self._warn_unconverted_html_node_type(html_node.name) res = [] subchild = html_node.children while subchild: xml_child = self._html_to_docbook_node(subchild) if type(xml_child) == list: res += xml_child elif xml_child != None: res.append(xml_child) subchild = subchild.next return res
def _encode(self, doc, tag, children, attributes, value, cdata, ns, nsMap={}): node = libxml2.newNode(tag) if ns: # create a prefix for the ns if not ns in nsMap: nsMap[ns] = 'ns%d' % (len(nsMap) + 1) prefix = nsMap[ns] node.setNs(node.newNs(ns, prefix)) for k, v in attributes.items(): node.setProp(k, v) if children: for (tag, attr) in children: node.addChild( self._encode(doc, tag, attr.get('children'), attr.get('attributes', {}), attr.get('value'), attr.get('cdata'), attr.get('ns'), nsMap)) else: if cdata: node.addChild(doc.newCDataBlock(value, len(value))) else: node.addChild(libxml2.newText(value)) return node
def _append_othercredit(self, root, translators): # Now, lets find 'articleinfo' (it can be something else, but this goes along with 'article') ai = self._find_authorgroup(root) if not ai: return # Now, lets do one translator at a time lines = translators.split("\n") for line in lines: line = line.strip() match = re.match(r"^([^<,]+)\s*(?:<([^>,]+)>)?,\s*(.*)$", line) if match and (match.group(1) or match.group(2)): last = self._find_lastothercredit(ai) copy = libxml2.newNode("othercredit") copy.setProp("class", "translator") if last: copy = last.addNextSibling(copy) else: ai.addChild(copy) if match.group(1): name = match.group(1).strip() if len(name) < 1: copy.newChild(None, "firstname", "???") elif name.find(" ") == -1: copy.newChild(None, "firstname", name.encode('utf-8')) else: firstname = name[:name.find(" ")] surname = name[name.find(" "):].strip() copy.newChild(None, "firstname", firstname.encode('utf-8')) copy.newChild(None, "surname", surname.encode('utf-8')) if match.group(2): copy.newChild(None, "email", match.group(2).encode('utf-8'))
def openPosition(self): dataRoot = libxml2.newNode('document') dataRoot.docSetRootElement(self.xml) cmd = libxml2.newNode('cmd') cmd.setProp('broker', 'FXCM') cmd.setProp('type', 'ClosePosition') dataRoot.addChild(cmd) instrument = libxml2.newNode('Instrument') instrument.setContent(self.instrument) cmd.addChild(instrument) ID = libxml2.newNode('ID') ID.setContent(str(self.id)) cmd.addChild(ID)
def call_gen(self, chain, type, dir, options): filename = os.path.join(dir, options.name+".xml") xmldoc = libxml2.parseFile(filename) p = xmldoc.xpathNewContext() supplied_arguments = options.arguments if (hasattr(options,'element') and options.element): element = options.element else: element='*' for option in supplied_arguments: option_name = option['name'] option_value = getattr(options,option_name) if (hasattr(options,option_name) and getattr(options,option_name)): context = p.xpathEval("//rule[@element='%s' or @element='*']/argument[name='%s']"%(element, option_name)) if (not context): raise Exception('Unknown option %s for match %s and element %s'%(option,option['name'], element)) else: # Add the value of option valueNode = libxml2.newNode('value') valueNode.addContent(option_value) context[0].addChild(valueNode) filename = self.getnextfilename(type,chain) file_path = os.path.join(sfatables_config, chain, filename) if not os.path.isdir(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) xmldoc.saveFile(file_path) p.xpathFreeContext() xmldoc.freeDoc() return True
def processModule(newDocNode, modulename): """ Start processing a new XML file, create a module element and then find the include elements """ filename = os.path.join(SRC, "%s_swig.xml" % modulename) print filename doc = libxml2.parseFile(filename) topNode = doc.getRootElement() # make a module element name = getAttr(topNode, "module") ##assert name == modulename # sanity check moduleNode = libxml2.newNode("module") moduleNode.setProp("name", name) newDocNode.addChild(moduleNode) node = topNode.children while node is not None: if node.name == "include": processInclude(moduleNode, node) node = node.next doc.freeDoc()
def _append_copyright(self, root, translators): # Now, lets find 'articleinfo' (it can be something else, but this goes along with 'article') ai = self._find_articleinfo(root) if not ai: return # Now, lets do one translator at a time lines = translators.split("\n") for line in lines: line = line.strip() match = re.match(r"^([^<,]+)\s*(?:<([^>,]+)>)?,\s*(.*)$", line) if match: last = self._find_lastcopyright(ai) copy = libxml2.newNode("copyright") if last: copy = last.addNextSibling(copy) else: ai.addChild(copy) if match.group(3): copy.newChild(None, "year", match.group(3).encode('utf-8')) if match.group(1) and match.group(2): holder = match.group( 1).strip() + " (%s)" % match.group(2).strip() elif match.group(1): holder = match.group(1) elif match.group(2): holder = match.group(2) else: holder = "???" copy.newChild(None, "holder", holder.encode('utf-8'))
def initializate_xml_out(): out_doc = libxml2.parseDoc("<openerp/>") out_root = out_doc.getRootElement() out_data = libxml2.newNode('data') out_data.setProp('noupdate','1') out_root.addChild(out_data) return out_doc, out_data
def add_xml_node_with_param(parent_node, node_name, node_value, parameter_name, parameter_value): if attr_to_string(node_value) is not None: node = libxml2.newNode(node_name) node.setContent(attr_to_string(node_value)) set_xml_param(node, parameter_name, parameter_value) parent_node.addChild(node)
def _handle_node(nodename, parentnode, parentpath): # If the passed xpath snippet (nodename) exists, return the node # If it doesn't exist, create it, and return the new node # If nodename is a node property, we can handle it up front if nodename.startswith("@"): nodename = nodename.strip("@") return parentnode.setProp(nodename, ""), parentpath if not parentpath: parentpath = nodename else: parentpath += "/%s" % nodename # See if the xpath node already exists node = _get_xpath_node(ctx, parentpath) if node: # xpath node already exists, so we don't need to create anything return node, parentpath # If we don't have a parentnode by this point, the root of the # xpath didn't find anything. Usually a coding error if not parentnode: raise RuntimeError("Could not find XML root node") # Remove conditional xpath elements for node creation. We preserved # them up until this point since it was needed for proper xpath # lookup, but they aren't valid syntax when creating the node if nodename.count("["): nodename = nodename[:nodename.index("[")] newnode = libxml2.newNode(nodename) return _add_pretty_child(parentnode, newnode), parentpath