/usr/lib/thuban/Extensions/wms/parser.py is in thuban 1.2.2-12build3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 | # Copyright (c) 2004 by Intevation GmbH
# Authors:
# Martin Schulze <joey@infodrom.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
Inspect WMS Capabilities for later processing.
Information should only be retrieved with the proper get*() methods.
class WMSCapabilitiesParser:
__init__()
grok(string)
getTitle()
getAbstract()
getFees()
getAccessConstraints()
getFormats()
getLayers()
getSRS()
getLayerTitle(layer)
getLayerSRS(layer)
getLayerLatLonBBox(layer)
getLayerBBox(layer, srs)
isQueryable(layer)
"""
__version__ = "$Revision: 2439 $"
# $Source$
# $Id: parser.py 2439 2004-12-09 10:37:44Z joey $
import xml.dom.minidom
from xml.dom import Node
from domutils import getElementsByName, getElementByName
from Thuban import _
class WMSCapabilitiesParser:
"""
Thuban class to parse capabilities supplied as large string.
This class provides methods to parse and retrieve particular
information from the WMS capabilities XML. Information should
only be extracted by the respective get*() methods.
"""
layers = None
title = None
abstract = None
fees = None
access = None
formats = None
error = None
def __init__(self):
"""
Initialises an instance in this class.
"""
# Note that we must not initialise internal variables of the
# class in a mutable way or it will be shared among all
# instances. None is immutable, [] is not.
self.error = []
def grok(self, data):
"""
Parses the XML response to a WMS GetCapabilities request.
Internal datastructure of the class will be filled.
Information should only be retrieved with the respective
get*() methods.
"""
xml_dom = xml.dom.minidom.parseString(data)
root = xml_dom.documentElement
# Extract the title
foo = getElementByName(getElementByName(root, 'Service'), 'Title')
if foo:
self.title = foo.childNodes[0].data
# Extract the abstract
foo = getElementByName(getElementByName(root, 'Service'), 'Abstract')
if foo and len(foo.childNodes[0].data):
self.abstract = foo.childNodes[0].data
# Extract fees information
foo = getElementByName(getElementByName(root, 'Service'), 'Fees')
if foo and len(foo.childNodes[0].data) \
and foo.childNodes[0].data.lower() != 'none':
self.fees = foo.childNodes[0].data
# Extract access information
foo = getElementByName(getElementByName(root, 'Service'),
'AccessConstraints')
if foo and len(foo.childNodes[0].data) \
and foo.childNodes[0].data.lower() != 'none':
self.access = foo.childNodes[0].data
foo = getElementByName(getElementByName(
root, 'Capability'), 'Request')
# Need to distinguish between Map and GetMap for v1.0 and v1.1
bar = getElementByName(foo, 'GetMap')
if bar:
# WMS 1.1
foo = getElementsByName(bar, 'Format')
self.formats = map((lambda i: i.childNodes[0].data), foo)
else:
# WMS 1.0
foo = getElementByName(getElementByName(
foo, 'Map'), 'Format')
for node in foo.childNodes:
if node.nodeType == Node.ELEMENT_NODE:
try:
self.formats.append(node.nodeName)
except AttributeError:
self.formats = [node.nodeName]
# Extract layer names
self.layers = []
self.peekLayers(getElementByName(getElementByName(
root, 'Capability'), 'Layer'), -1)
xml_dom.unlink()
def peekLayers(self, top, parent):
"""
Inspect the provided DOM fragment referenced as top.
This method will inspect all included layers and traverse the
tree recursively in order to fill the internal datastructure.
Note that SRS other than EPSG:* are not yet supported,
especially there is no support for AUTO and NONE.
"""
index = len (self.layers)
self.layers.append({})
self.layers[index]['parent'] = parent
for foo in top.attributes.keys():
if foo == 'queryable':
self.layers[index]['queryable'] \
= int(top.attributes.get(foo).nodeValue)
foo = getElementByName(top, 'Title')
if foo and len(foo.childNodes[0].data):
self.layers[index]['title'] = foo.childNodes[0].data
else:
# A <Title> is required for each layer, <name> is optional
# See OGC 01-068r3, 7.1.4.5.1 and 7.1.4.5.2
self.error.append(_("No title found for layer #%d") % index)
foo = getElementByName(top, 'Name')
if foo and len(foo.childNodes[0].data):
self.layers[index]['name'] = foo.childNodes[0].data
# These values are only used for an integrity check
for foo in getElementsByName(top, 'SRS'):
for srs in foo.childNodes[0].data.split(" "):
if srs[0:5] == 'EPSG:':
srs = srs[5:]
try:
int(srs)
try:
self.layers[index]['srs'].append(srs)
except KeyError:
self.layers[index]['srs'] = [srs]
except ValueError:
if srs[0:4].upper() == 'AUTO' \
or srs[0:4].upper() == 'NONE':
try:
self.layers[index]['_srs_'].append(srs)
except KeyError:
self.layers[index]['_srs_'] = [srs]
else:
self.error.append(_("SRS '%s' is not numerical and not"
" AUTO/NONE in layer '%s'") \
% (srs, self.layers[index]['title']))
foo = getElementByName(top, 'LatLonBoundingBox')
if foo is not None:
self.layers[index]['llbbox'] = {}
for corner in ['minx', 'miny', 'maxx', 'maxy']:
self.layers[index]['llbbox'][corner] \
= foo.attributes.get(corner).nodeValue
boxes = getElementsByName(top, 'BoundingBox')
if boxes != []:
self.layers[index]['bbox'] = {}
for foo in boxes:
srs = foo.attributes.get('SRS').nodeValue
if srs[0:5] == 'EPSG:':
srs = srs[5:]
self.layers[index]['bbox'][srs] = {}
for corner in ['minx', 'miny', 'maxx', 'maxy']:
self.layers[index]['bbox'][srs][corner] \
= foo.attributes.get(corner).nodeValue
# Traverse subsidiary layers
sublayer = getElementsByName(top, 'Layer')
for l in sublayer:
self.peekLayers(l, index)
def getTitle(self):
"""
Returns the main title of the WMS object.
If no title is provided in the capabilities, an empty string
is returned.
"""
if self.title is None:
return ''
else:
return self.title
def getAbstract(self):
"""
Returns the abstract of the WMS object.
If no abstract is provided in the capabilities, an empty
string is returned.
"""
if self.abstract is None:
return ''
else:
return self.abstract
def getFees(self):
"""
Returns the fees information of the WMS object.
If no information is provided in the capabilities or if it is
set to 'none', an empty string is returned.
"""
if self.fees is None:
return ''
else:
return self.fees
def getAccessConstraints(self):
"""
Returns information about access constraints for the WMS object.
If no information is provided in the capabilities or if it is
set to 'none', an empty string is returned.
"""
if self.access is None:
return ''
else:
return self.access
def getFormats(self):
"""
Returns a list of supported output formats.
These are used in the GetMap request. This method will
default to 'image/jpeg' if no format is recognised in XML
Capabilities, assuming that JPEG will always be supported on
the server side.
"""
if self.formats is None:
return ['image/jpeg']
else:
return self.formats
def getLayers(self):
"""
Returns a list of layer names.
Only named layers will be returned, since a layer may have a
title but doesn't have to have a name associated to it as
well. If no layers were found, an empty list is returned.
"""
result = []
for layer in self.layers:
if 'name' in layer:
result.append(layer['name'])
return result
def getSRS(self):
"""
Returns the root list of spatial reference systems (SRS).
This list is taken from the root layer. Those SRS are common
to all subsidiary layers. If no SRS are common to all layers,
an empty list is returned. If no layers were detected, an
empty list is returned as well.
"""
if len(self.layers) == 0:
return []
# index 0 denotes the root layer by design
if 'srs' in self.layers[0].keys():
return self.layers[0]['srs']
def getLayerTitle(self, name):
"""
Returns the title of the named layer.
If no such title or no such layer exists, an empty string is
returned.
"""
for layer in self.layers:
if 'name' in layer:
if layer['name'] == name:
if 'title' in layer:
return layer['title']
return ''
def getLayerSRS(self, name):
"""
Returns a list of spacial reference systems (SRS).
The SRS are specified by the European Petroleum Survey Group
(EPSG). There should be at least one SRS per layer, though.
The prefix 'EPSG:' will be stripped. If none exists, an empty
list is returned.
The specification [OGC 01-068r3] says about inheritance of
SRS:
- Every layer is available in one or more SRS (or in an
undefined SRS)
- Geographic information whose SRS is undefined
(e.g. digitised historical maps) shall use 'NONE'
(case-sensitive). This implementation does not support
this.
- Every layer shall have at least one SRS element that is
either stated explicitly or inherited from a parent layer.
- The root layer element shall include a sequence of zero or
more SRS elements listing all SRS which are common for to
all subsidiary layers.
- Layers may optionally add to the global SRS list, or to the
list inherited from a parent layer.
- A server which has the ability to transform data to
different SRSes may choose not to provide an explicit
BoundingBox for every possible SRS available for each Layer.
Thus the list of <SRS> elements are authoritative.
This implementation returns the list of SRS for the given
layer, calculated by looking at BoundingBoxes defined in the
named layer and all layers higher in the hierarchy up to the
root layer which weren't overwritten.
"""
for i in range(len(self.layers)):
if 'name' in self.layers[i]:
if self.layers[i]['name'] == name:
pivot = i
break
else:
return []
result = []
while pivot != -1:
if 'srs' in self.layers[pivot]:
for srs in self.layers[pivot]['srs']:
if srs not in result:
result.append(srs)
pivot = self.layers[pivot]['parent']
return result
def getLayerLatLonBBox(self, name):
"""
Returns a dictionary of the LatLonBoundingBox.
... for the named layer if it exists. The SRS is always
EPSG:4326 per convention. There should be at least one,
though, inherited from the root layer at least. If none
exists, the value None is returned.
"""
for layer in self.layers:
if 'name' in layer:
if layer['name'] == name:
if 'llbbox' in layer:
return layer['llbbox']
else:
# No LatLonBoundingBox found in current layer,
# so traverse the hierarchy upwards and check
# again until there is one.
pivot = layer
while pivot['parent'] != -1:
pivot = self.layers[pivot['parent']]
if 'llbbox' in pivot:
return pivot['llbbox']
return None
def getLayerBBox(self, name, srs):
"""
Returns a dictionary of the BoundingBox.
If no such BoundingBox exists, None is returned.
The specification [OGC 01-068r3] says about BoundingBoxes:
- Layers may have zero or more BoundingBox elements what are
either stated explicitly or inherited from a parent layer.
- A layer may have multiple BoundingBox elements, but each one
shall state a different SRS.
- A layer inherits any BoundingBoxes defined by its
parents.
- A BoundingBox inherited from the parent layer for a
particular SRS is replaced by any declaration for the same
SRS in the current layer.
- A BoundingBox in the child layer for a new SRS which is not
already declared by the parent, is added to the list of
BoundingBoxes for the child layer.
- A single layer shall not contain more than one BoundingBox
element for the same SRS.
"""
for layer in self.layers:
if 'name' in layer:
if layer['name'] == name:
if 'bbox' in layer:
if srs in layer['bbox']:
return layer['bbox'][srs]
# No BoundingBox for the given SRS found in
# current layer, so traverse the hierarchy upwards
# and check again until there is one.
pivot = layer
while pivot['parent'] != -1:
pivot = self.layers[pivot['parent']]
if 'bbox' in pivot:
if srs in pivot['bbox']:
return pivot['bbox'][srs]
# No matching BBox found, let's see if it was EPSG:4326
if srs == '4326':
return self.getLayerLatLonBBox(name)
return None
def isQueryable(self, name):
"""
Returns the value of the queryable attribute of a layer.
This attribute denotes whether this layer can be queried
through the GetFeatureInfo request. The default value is 0.
The specification [OGC 01-068r3] this attribute can be
inherited.
"""
for layer in self.layers:
if 'name' in layer:
if layer['name'] == name:
try:
return layer['queryable']
except KeyError:
# No attribute in this layer, so traverse the
# hierarchy upwards
pivot = layer
while pivot['parent'] != -1:
pivot = self.layers[pivot['parent']]
if 'queryable' in pivot:
return pivot['queryable']
return 0
if __name__ == "__main__":
print "This module cannot be executed standalone."
import os
sample = "test/sample.xml"
try:
f = open(sample, "r")
except IOError:
try:
f = open(os.path.dirname(__file__) + "/" + sample, "r")
except IOError:
print "Cannot open %s for reading" % sample
if f is not None:
sample = f.read();
f.close()
ina = WMSCapabilitiesParser()
ina.grok(sample)
|