| 1 |
#!/usr/bin/env python |
| 2 |
# |
| 3 |
# Filter: XML validation. |
| 4 |
# |
| 5 |
# NB: you need to have installed libxml2 2.8.0 or newer! |
| 6 |
# Older libxml2 versions like 2.7.8 have a bug which causes failure in GML Schema |
| 7 |
# parsing. See https://bugzilla.gnome.org/show_bug.cgi?id=630130 |
| 8 |
# |
| 9 |
# Author:Just van den Broecke |
| 10 |
# |
| 11 |
from stetl.util import Util, etree |
| 12 |
from stetl.filter import Filter |
| 13 |
from stetl.packet import FORMAT |
| 14 |
|
| 15 |
log = Util.get_log("xmlvalidator") |
| 16 |
|
| 17 |
|
| 18 |
class XmlSchemaValidator(Filter): |
| 19 |
""" |
| 20 |
Validates an etree doc and prints result to log. |
| 21 |
|
| 22 |
consumes=FORMAT.etree_doc, produces=FORMAT.etree_doc |
| 23 |
""" |
| 24 |
|
| 25 |
# Constructor |
| 26 |
def __init__(self, configdict, section): |
| 27 |
Filter.__init__(self, configdict, section, consumes=FORMAT.etree_doc, produces=FORMAT.etree_doc) |
| 28 |
self.enabled = self.cfg.get_bool('enabled', True) |
| 29 |
self.xsd = self.cfg.get('xsd') |
| 30 |
log.info("Building the Schema once with (GML XSD) dependencies for schema=%s (be patient...)" % self.xsd) |
| 31 |
self.schema = etree.XMLSchema(etree.parse(self.xsd)) |
| 32 |
|
| 33 |
def invoke(self, packet): |
| 34 |
if packet.data is None or not self.enabled: |
| 35 |
return packet |
| 36 |
return self.validate(packet) |
| 37 |
|
| 38 |
def validate(self, packet): |
| 39 |
log.info("Validating doc against schema=%s ..." % self.xsd) |
| 40 |
result = self.schema.validate(packet.data) |
| 41 |
log.info("Validation result: %s" % str(result)) |
| 42 |
return packet |