2019-10-29 01:01:31 -04:00
|
|
|
import copy
|
2019-09-30 22:08:37 -04:00
|
|
|
import os
|
2019-10-28 11:39:25 -04:00
|
|
|
import re
|
2019-09-30 22:08:37 -04:00
|
|
|
##
|
2019-10-28 11:39:25 -04:00
|
|
|
import requests
|
2019-10-29 01:01:31 -04:00
|
|
|
from lxml import etree, objectify
|
2019-09-30 22:08:37 -04:00
|
|
|
|
2019-10-28 14:11:35 -04:00
|
|
|
|
2019-09-30 22:08:37 -04:00
|
|
|
class Config(object):
|
2019-10-28 14:11:35 -04:00
|
|
|
def __init__(self, xsd_path = None, *args, **kwargs):
|
|
|
|
self.xsd_path = None
|
2019-10-28 11:39:25 -04:00
|
|
|
self.tree = None
|
|
|
|
self.namespaced_tree = None
|
2019-09-30 22:08:37 -04:00
|
|
|
self.xml = None
|
2019-10-28 11:39:25 -04:00
|
|
|
self.namespaced_xml = None
|
|
|
|
self.raw = None
|
|
|
|
self.xsd = None
|
2019-10-28 14:11:35 -04:00
|
|
|
self.defaultsParser = None
|
2019-10-29 01:01:31 -04:00
|
|
|
self.obj = None
|
2019-09-30 22:08:37 -04:00
|
|
|
|
2019-10-28 14:11:35 -04:00
|
|
|
def main(self, validate = True, populate_defaults = True):
|
2019-10-28 11:39:25 -04:00
|
|
|
self.fetch()
|
|
|
|
self.parseRaw()
|
2019-10-28 14:11:35 -04:00
|
|
|
if populate_defaults:
|
|
|
|
self.populateDefaults()
|
2019-10-28 11:39:25 -04:00
|
|
|
if validate:
|
|
|
|
self.validate()
|
2019-10-29 01:01:31 -04:00
|
|
|
self.pythonize()
|
2019-10-28 11:39:25 -04:00
|
|
|
return()
|
2019-09-30 22:08:37 -04:00
|
|
|
|
2019-10-28 11:39:25 -04:00
|
|
|
def fetch(self): # Just a fail-safe; this is overridden by specific subclasses.
|
2019-09-30 22:08:37 -04:00
|
|
|
pass
|
2019-10-28 11:39:25 -04:00
|
|
|
return()
|
|
|
|
|
|
|
|
def getXSD(self, xsdpath = None):
|
2019-10-28 14:11:35 -04:00
|
|
|
if not xsdpath:
|
|
|
|
xsdpath = self.xsd_path
|
2019-10-28 11:39:25 -04:00
|
|
|
raw_xsd = None
|
|
|
|
if xsdpath:
|
|
|
|
xsdpath = os.path.abspath(os.path.expanduser(xsdpath))
|
|
|
|
if not os.path.isfile(xsdpath):
|
|
|
|
raise ValueError(('An explicit XSD path was specified but '
|
|
|
|
'does not exist on the local filesystem'))
|
|
|
|
with open(xsdpath, 'rb') as fh:
|
|
|
|
raw_xsd = fh.read()
|
|
|
|
else:
|
|
|
|
xsi = self.xml.nsmap.get('xsi', 'http://www.w3.org/2001/XMLSchema-instance')
|
|
|
|
schemaLocation = '{{{0}}}schemaLocation'.format(xsi)
|
|
|
|
schemaURL = self.xml.attrib.get(schemaLocation,
|
|
|
|
'https://aif-ng.io/aif.xsd?ref={0}'.format(self.xml.attrib['version']))
|
2019-10-28 14:11:35 -04:00
|
|
|
split_url = schemaURL.split()
|
|
|
|
if len(split_url) == 2: # a properly defined schemaLocation
|
|
|
|
schemaURL = split_url[1]
|
|
|
|
else:
|
2019-10-29 01:01:31 -04:00
|
|
|
schemaURL = split_url[0] # a LAZY schemaLocation
|
2019-10-28 11:39:25 -04:00
|
|
|
req = requests.get(schemaURL)
|
2019-10-28 14:11:35 -04:00
|
|
|
if not req.ok:
|
|
|
|
# TODO: logging!
|
2019-10-28 11:39:25 -04:00
|
|
|
raise RuntimeError('Could not download XSD')
|
|
|
|
raw_xsd = req.content
|
|
|
|
self.xsd = etree.XMLSchema(etree.XML(raw_xsd))
|
|
|
|
return()
|
|
|
|
|
2019-10-28 14:11:35 -04:00
|
|
|
def parseRaw(self, parser = None):
|
|
|
|
# self.xml = etree.parse(self.raw, parser = parser)
|
|
|
|
self.xml = etree.fromstring(self.raw, parser = parser)
|
|
|
|
# self.namespaced_xml = etree.parse(self.raw, parser = parser)
|
|
|
|
self.namespaced_xml = etree.fromstring(self.raw, parser = parser)
|
|
|
|
self.tree = self.xml.getroottree()
|
|
|
|
self.namespaced_tree = self.namespaced_xml.getroottree()
|
2019-10-28 11:39:25 -04:00
|
|
|
self.tree.xinclude()
|
|
|
|
self.namespaced_tree.xinclude()
|
2019-10-28 14:11:35 -04:00
|
|
|
self.stripNS()
|
|
|
|
return()
|
|
|
|
|
|
|
|
def populateDefaults(self):
|
|
|
|
if not self.xsd:
|
|
|
|
self.getXSD()
|
|
|
|
if not self.defaultsParser:
|
|
|
|
self.defaultsParser = etree.XMLParser(schema = self.xsd, attribute_defaults = True)
|
|
|
|
self.parseRaw(parser = self.defaultsParser)
|
|
|
|
return()
|
|
|
|
|
2019-10-29 01:01:31 -04:00
|
|
|
def pythonize(self, stripped = True, obj = 'tree'):
|
|
|
|
# https://bugs.launchpad.net/lxml/+bug/1850221
|
|
|
|
strobj = self.toString(stripped = stripped, obj = obj)
|
|
|
|
self.obj = objectify.fromstring(strobj)
|
|
|
|
objectify.annotate(self.obj)
|
|
|
|
objectify.xsiannotate(self.obj)
|
|
|
|
return()
|
|
|
|
|
2019-10-28 14:11:35 -04:00
|
|
|
def removeDefaults(self):
|
|
|
|
self.parseRaw()
|
2019-10-28 11:39:25 -04:00
|
|
|
return()
|
|
|
|
|
2019-10-29 01:01:31 -04:00
|
|
|
def stripNS(self, obj = None):
|
2019-10-28 11:39:25 -04:00
|
|
|
# https://stackoverflow.com/questions/30232031/how-can-i-strip-namespaces-out-of-an-lxml-tree/30233635#30233635
|
2019-10-29 01:01:31 -04:00
|
|
|
xpathq = "descendant-or-self::*[namespace-uri()!='']"
|
|
|
|
if not obj:
|
|
|
|
for x in (self.tree, self.xml):
|
|
|
|
for e in x.xpath(xpathq):
|
|
|
|
e.tag = etree.QName(e).localname
|
|
|
|
elif isinstance(obj, (etree._Element, etree._ElementTree)):
|
|
|
|
obj = copy.deepcopy(obj)
|
|
|
|
for e in obj.xpath(xpathq):
|
2019-10-28 11:39:25 -04:00
|
|
|
e.tag = etree.QName(e).localname
|
2019-10-29 01:01:31 -04:00
|
|
|
return(obj)
|
|
|
|
else:
|
|
|
|
raise ValueError('Did not know how to parse obj parameter')
|
2019-10-28 11:39:25 -04:00
|
|
|
return()
|
|
|
|
|
2019-10-29 01:01:31 -04:00
|
|
|
def toString(self, stripped = False, obj = None):
|
|
|
|
if isinstance(obj, (etree._Element, etree._ElementTree)):
|
|
|
|
if stripped:
|
|
|
|
obj = self.stripNS(obj)
|
|
|
|
elif obj in ('tree', None):
|
|
|
|
if not stripped:
|
|
|
|
obj = self.namespaced_tree
|
|
|
|
else:
|
|
|
|
obj = self.tree
|
|
|
|
elif obj == 'xml':
|
|
|
|
if not stripped:
|
|
|
|
obj = self.namespaced_xml
|
|
|
|
else:
|
|
|
|
obj = self.xml
|
|
|
|
else:
|
|
|
|
raise ValueError(('obj parameter must be "tree", "xml", or of type '
|
|
|
|
'lxml.etree._Element or lxml.etree._ElementTree'))
|
|
|
|
obj = copy.deepcopy(obj)
|
|
|
|
strxml = etree.tostring(obj,
|
|
|
|
encoding = 'utf-8',
|
|
|
|
xml_declaration = True,
|
|
|
|
pretty_print = True,
|
|
|
|
with_tail = True,
|
|
|
|
inclusive_ns_prefixes = True)
|
|
|
|
return(strxml)
|
|
|
|
|
2019-10-28 11:39:25 -04:00
|
|
|
def validate(self):
|
|
|
|
if not self.xsd:
|
|
|
|
self.getXSD()
|
2019-10-28 14:11:35 -04:00
|
|
|
self.xsd.assertValid(self.namespaced_tree)
|
2019-10-28 11:39:25 -04:00
|
|
|
return()
|
|
|
|
|
|
|
|
|
|
|
|
class LocalFile(Config):
|
2019-10-28 14:11:35 -04:00
|
|
|
def __init__(self, path, xsd_path = None, *args, **kwargs):
|
|
|
|
super().__init__(xsd_path = xsd_path, *args, **kwargs)
|
|
|
|
self.type = 'local'
|
2019-10-31 23:20:05 -04:00
|
|
|
self.source = path
|
2019-10-28 11:39:25 -04:00
|
|
|
|
|
|
|
def fetch(self):
|
2019-10-28 14:11:35 -04:00
|
|
|
self.source = os.path.realpath(self.source)
|
|
|
|
if not os.path.isfile(self.source):
|
|
|
|
raise ValueError('{0} does not exist'.format(self.source))
|
|
|
|
with open(self.source, 'rb') as fh:
|
2019-10-28 11:39:25 -04:00
|
|
|
self.raw = fh.read()
|
|
|
|
return()
|
|
|
|
|
|
|
|
|
|
|
|
class RemoteFile(Config):
|
2019-10-28 14:11:35 -04:00
|
|
|
def __init__(self, uri, xsd_path = None, *args, **kwargs):
|
2019-10-28 11:39:25 -04:00
|
|
|
super().__init__(*args, **kwargs)
|
2019-10-28 14:11:35 -04:00
|
|
|
self.type = 'remote'
|
|
|
|
self.source = uri
|
2019-10-28 11:39:25 -04:00
|
|
|
|
|
|
|
def fetch(self):
|
2019-10-28 14:11:35 -04:00
|
|
|
r = requests.get(self.source)
|
2019-10-28 11:39:25 -04:00
|
|
|
if not r.ok():
|
|
|
|
raise RuntimeError('Could not download XML')
|
|
|
|
self.raw = r.content
|
|
|
|
return()
|
|
|
|
|
|
|
|
|
|
|
|
class ConfigStr(Config):
|
2019-10-28 14:11:35 -04:00
|
|
|
def __init__(self, rawxml, xsd_path = None, *args, **kwargs):
|
2019-10-28 11:39:25 -04:00
|
|
|
super().__init__(*args, **kwargs)
|
2019-10-28 14:11:35 -04:00
|
|
|
self.type = 'raw_str'
|
|
|
|
self.source = rawxml
|
2019-10-28 11:39:25 -04:00
|
|
|
|
|
|
|
def fetch(self):
|
2019-10-28 14:11:35 -04:00
|
|
|
self.raw = self.source.encode('utf-8')
|
2019-10-28 11:39:25 -04:00
|
|
|
return()
|
|
|
|
|
2019-10-28 14:11:35 -04:00
|
|
|
|
2019-10-28 11:39:25 -04:00
|
|
|
class ConfigBin(Config):
|
2019-10-28 14:11:35 -04:00
|
|
|
def __init__(self, rawbinaryxml, xsd_path = None, *args, **kwargs):
|
2019-10-28 11:39:25 -04:00
|
|
|
super().__init__(*args, **kwargs)
|
2019-10-28 14:11:35 -04:00
|
|
|
self.type = 'raw_bin'
|
|
|
|
self.source = rawbinaryxml
|
2019-10-28 11:39:25 -04:00
|
|
|
|
|
|
|
def fetch(self):
|
2019-10-28 14:11:35 -04:00
|
|
|
self.raw = self.source
|
2019-10-28 11:39:25 -04:00
|
|
|
return()
|
|
|
|
|
|
|
|
|
2019-10-29 22:37:36 -04:00
|
|
|
detector = {'raw': (re.compile(r'^\s*(?P<xml><(\?xml|aif)\s+.*)\s*$', re.DOTALL | re.MULTILINE), ConfigStr),
|
|
|
|
'remote': (re.compile(r'^(?P<uri>(?P<proto>(https?|ftps?)://)(?P<path>.*))\s*$'), RemoteFile),
|
|
|
|
'local': (re.compile(r'^(file://)?(?P<path>(/?[^/]+)+/?)$'), LocalFile)}
|
|
|
|
|
|
|
|
|
2019-10-28 14:11:35 -04:00
|
|
|
def getConfig(cfg_ref, validate = True, populate_defaults = True, xsd_path = None):
|
2019-10-28 11:39:25 -04:00
|
|
|
cfgobj = None
|
|
|
|
# This is kind of gross.
|
2019-10-29 22:37:36 -04:00
|
|
|
for configtype, (pattern, configClass) in detector.items():
|
2019-10-28 11:39:25 -04:00
|
|
|
try:
|
|
|
|
if pattern.search(cfg_ref):
|
2019-10-29 22:37:36 -04:00
|
|
|
cfgobj = configClass(cfg_ref, xsd_path = xsd_path)
|
|
|
|
break
|
2019-10-28 11:39:25 -04:00
|
|
|
except TypeError:
|
2019-10-29 22:37:36 -04:00
|
|
|
ptrn = re.compile(detector['raw'][0].pattern.encode('utf-8'))
|
2019-10-28 11:39:25 -04:00
|
|
|
if not ptrn.search(cfg_ref):
|
|
|
|
raise ValueError('Received junk data for cfg_ref')
|
|
|
|
else:
|
2019-10-28 14:11:35 -04:00
|
|
|
cfgobj = ConfigBin(cfg_ref, xsd_path = xsd_path)
|
2019-10-28 11:39:25 -04:00
|
|
|
break
|
2019-10-28 14:11:35 -04:00
|
|
|
if cfgobj:
|
|
|
|
cfgobj.main(validate = validate, populate_defaults = populate_defaults)
|
2019-10-28 11:39:25 -04:00
|
|
|
return(cfgobj)
|