source: cows/trunk/cows/pylons/wfs_controller.py @ 5132

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/cows/trunk/cows/pylons/wfs_controller.py@5132
Revision 5132, 12.8 KB checked in by domlowe, 11 years ago (diff)

typename parameter enabled in WFS #2

RevLine 
[4912]1# BSD Licence
2# Copyright (c) 2009, Science & Technology Facilities Council (STFC)
3# All rights reserved.
4#
5# See the LICENSE file in the source distribution of this software for
6# the full license text.
7
[4274]8"""
9WFS controller for OGC Web Services (OWS).
10
11@author: Dominic Lowe
12"""
13
14import re
15from cStringIO import StringIO
16from sets import Set
[4910]17from pylons import request, response, c
[4287]18import ConfigParser
[4417]19import xml.etree.ElementTree as etree
[4274]20import logging
21log = logging.getLogger(__name__)
22
23import Image
24
25from cows.model.wfs import WfsFeatureSummary
[4344]26from cows.model.filterencoding import FEQueryProcessor
[4274]27from cows.model import PossibleValues, WGS84BoundingBox, BoundingBox, Contents
28from cows.pylons import ows_controller
29from cows.exceptions import *
30from cows import bbox_util
[4910]31from cows.service.imps.csmlbackend.config import config
[4274]32
33class WFSController(ows_controller.OWSController):
34    """
35    Subclass this controller in a pylons application and set the layerMapper
36    class attribute to implement a WFS. Each layer can be mapped to a Feature for the WFS.
37
38    @cvar layerMapper: an cows.service.wxs_iface.ILayerMapper object.
39   
40
41    """
42    layerMapper = None
43    _layerSlabCache = {}
44
45    #-------------------------------------------------------------------------
46    # Attributes required by OWSController
47
48    service = 'WFS'
[4415]49    owsOperations = (ows_controller.OWSController.owsOperations + ['DescribeFeatureType', 'GetFeature', 'DescribeStoredQueries','ListStoredQueries', 'GetPropertyValue'])
[4394]50    validVersions = ['1.1.0', '2.0.0']
51   
[4274]52
53    #-------------------------------------------------------------------------
54
55    def __before__(self, **kwargs):
56        """
57        This default implementation of __before__() will pass all routes
58        arguments to the layer mapper to retrieve a list of layers for
59        this WFS.
60
61        It will be called automatically by pylons before each action method.
62
63
64        """
[4289]65        log.debug('loading layers')
[4292]66        self.layers, self.featureset = self.layerMapper.map(**kwargs)
67        log.debug('Feature instances %s'%self.featureset.featureinstances)
[4274]68   
69        #-------------------------------------------------------------------------
70        # Methods implementing stubs in OWSController
71
72    def _renderCapabilities(self, version, format):
73        """
74        Renders capabilities document.
75        """
76        if version == '1.1.0':
77            t = ows_controller.templateLoader.load('wfs_capabilities_1_1_0.xml')
[4394]78        elif version == '2.0.0':
79            t = ows_controller.templateLoader.load('wfs_capabilities_2_0_0.xml')
[4274]80        else:
81            # We should never get here!  The framework should raise an exception before now.
82            raise RuntimeError("Version %s not supported" % version)
83       
84        return t.generate(c=c).render()
85
86    def _loadCapabilities(self):
87        """
88        @note: Assumes self.layers has already been created by __before__().
89        Builds capabilities document.
90
91        """
92        log.info('Loading WFS Capabilites')
93       
94        ows_controller.addOperation('GetFeature')
95        ows_controller.addOperation('DescribeFeature')
[4398]96        ows_controller.addOperation('DescribeStoredQueries')
[4415]97        ows_controller.addOperation('ListStoredQueries')
98        ows_controller.addOperation('GetPropertyValue')
[4274]99       
100       
101        featureInfoFormats = Set()
102
103        log.debug('Loading capabilities contents')
104        c.capabilities.contents = Contents()
105       
106       
107        ftlist={}
[4292]108        #       
[4274]109       
110        for layerName, layer in self.layers.items():
111            log.info('Loading layer %s' % layerName)
[4278]112#            log.info('feature type %s'%layer._feature)
[4274]113
114            wgs84BBox = WGS84BoundingBox(layer.wgs84BBox[:2],
115                                         layer.wgs84BBox[2:])
116           
[4284]117            ds = WfsFeatureSummary(keywords=layer.keywords, 
118                                   outputformats=layer.outputformats, 
119                                   identifier=layerName,
[4274]120                                   titles=[layer.title],
121                                   abstracts=[layer.abstract],                                   
122                                   wgs84BoundingBoxes=[wgs84BBox])
123
124            c.capabilities.contents.datasetSummaries.append(ds)
[4287]125
126    def _getSchema(self, typename):
127        namespace = typename.split(':')[0]
128        schemalocation = conf
129       
130    def _parsetypename(self, typename):
[4417]131        """ parse feature type name into schema and name and return schema"""       
[4287]132        if typename not in self.layers.keys():
133            raise InvalidParameterValue('Invalid typename parameter: %s. Typename must consist of namespace and featuretype separated with a colon, as displayed in the GetCapabilities response.'%typename, 'typename')
134   
135        namespace, ft = typename.split(':')
136        wfsconfiglocation=config['wfsconfig']
137        wfscfg = ConfigParser.ConfigParser()
138        wfscfg.read(wfsconfiglocation)     
139        xmlschema=open(wfscfg.get('application_schemas', namespace)).read()     
140        log.debug('location of application schema %s' %(xmlschema))
141        return xmlschema
[4415]142   
[5131]143    def _runQuery(self, queryxml = None, storedqueryid=None, typename=None, **kwargs):
[4415]144        """ this is used by both the GetFeature and GetPropertyValue methods to
145        run a wfs:query over a featurecollection and return a subset of the collection.
146        The query may be defined as an xml <wfs:query> or may be referenced by a StoredQuery_id
147        """
[4422]148        additionalobjects=[] #not implemented for filter encoding, just for storedqueries (e.g. subsetting)
[4415]149        if queryxml:
150            qp=FEQueryProcessor()
151            resultset=qp.evaluate(self.featureset, queryxml)
152            log.debug('Final resultset from query processor %s'%resultset)
153        elif storedqueryid:
154            storedquery, func=self.layerMapper.queryDescriptions.queries[storedqueryid]
[4422]155            storedqueryresult=func(self.featureset, **kwargs)
156            if len(storedqueryresult) == 2:
157                resultset=storedqueryresult[0]
158                additionalobjects=storedqueryresult[1]
159            else:
160                resultset=storedqueryresult
[4415]161            log.debug('Final resultset from stored query %s'%resultset)
[4417]162        else:           
[5131]163            #If neither query or storedquery_id are provided then return entire featureset, filtered on 'typename' if supplied.
[4417]164            resultset=self.featureset.getFeatureList()
[5131]165            if typename:
166                templist = resultset[:]
167                for feature in templist:
168                    if feature.featuretype != typename:
169                        resultset.remove(feature)
170                resultset=resultset
[4422]171        return resultset, additionalobjects
[4287]172
[4417]173    def _applyXPath(self, xpath, features):
174        """ applies an xpath expression to a set of features and returns
175        a set of wfs:members containing property values expressed in the xpath"""
176        resultset=[]       
[4431]177        #if xpath is looking for an attribute, handle it differently - this should be unnecessary when migrated to element tree 1.3
178        #i.e. if of the form /somepath/path[@attribute]
179        attstart=xpath.find('[')
180        if attstart == -1: #no attribute           
181            for feature in features:
182                featureXML=feature._feature.elem #the underlying XML
183                valuecomponent=featureXML.find(xpath)
184                if valuecomponent is not None:
185                    valstr=etree.tostring(valuecomponent)           
186                    resultset.append(valstr)
187        else:
188            #there is an attribute:
189            attributeName=xpath.split('[')[1][1:-1]
190            xpath=xpath.split('[')[0]
191            for feature in features:
192                featureXML=feature._feature.elem #the underlying XML
193                log.debug('xpath path %s'%xpath)
194                log.debug('attribute %s'%attributeName)
195                if len(xpath) ==0:
196                    valuecomponent=featureXML
197                else:
198                    valuecomponent=featureXML.find(xpath)
199                log.debug('valuecomponent %s'%valuecomponent)
200                if valuecomponent is not None:
[4481]201                    attribute=valuecomponent.get(attributeName)         
202                    resultset.append(attribute)           
[4431]203        log.debug(resultset)
[4417]204        return resultset     
205   
206   
[4274]207    def DescribeFeatureType(self):
208        """ DescribeFeatureType """
[4287]209        version = self.getOwsParam('version', default=self.validVersions[0])
210        if version not in self.validVersions:
211            raise InvalidParameterValue('Version %s not supported' % version,
212                                        'version')
213        typename=self.getOwsParam('typename')
214        ftschema =self._parsetypename(typename)
[4292]215        log.debug(self.layers.items())       
216               
[4287]217        outputformat=self.getOwsParam('outputformat', default='text/xml')
218       
219        #temporarily returns entire schema
220        #TODO: return single featuretype definition
221        msg  = ftschema
[4288]222        response.headers['content-type'] = 'text/xml'
[4287]223        return msg
[4417]224           
[4274]225 
[4415]226    def GetPropertyValue(self):
227        """ GetPropertyValue request - similar to get feature but only returns chosen property
228        values """
229        valueReference = self.getOwsParam('valueReference')
230        queryxml=self.getOwsParam('query',default=None)
231        storedqueryid=self.getOwsParam('storedquery_id', default=None)
[5131]232        typename=self.getOwsParam('typename', default=None)
[4415]233        #get any other parameters from self._owsParams and pass them to the stored query
234        otherparams={}
235        for key in self._owsParams.keys():
[5131]236            if key not in ['query', 'request', 'service', 'version', 'storedquery_id', 'typename', 'valuereference']:
[4415]237                otherparams[key]=self._owsParams[key]     
[5131]238        featureresultset, additionalobjects =self._runQuery(queryxml, storedqueryid, typename **otherparams)       
[4417]239       
240        #Now need to take account of valueReferencexpath, and distill the
[4415]241        #resultset down to just the requested properties.
[4417]242        c.resultset=self._applyXPath(valueReference, featureresultset)
[4415]243       
244        response.headers['content-type'] = 'text/xml'
245        #TODO, new template for values
246        t = ows_controller.templateLoader.load('wfs_valuecollection.xml')
247        return t.generate(c=c).render() 
248 
[4274]249    def GetFeature(self):
250        """ GetFeature request
251        """
252        version = self.getOwsParam('version', default=self.validVersions[0])
253        if version not in self.validVersions:
254            raise InvalidParameterValue('Version %s not supported' % version,
255                                        'version')
[4298]256
[4400]257        #The GetFeature request may either use the 'query' filter encoding or a
[4415]258        #storedquery, but not both:     
[4298]259        #Parse the query to analyse the filters it contains
[4400]260        queryxml=self.getOwsParam('query',default=None)
261        storedqueryid=self.getOwsParam('storedquery_id', default=None)
[5132]262        typename=self.getOwsParam('typename', default=None)
[4344]263       
[4415]264        #retrieve any other parameters and pass them off to the stored query (they are ignored in the case of the queryxml option
265        otherparams={}
266        for key in self._owsParams.keys():
[5132]267            if key not in ['query', 'request', 'service', 'version', 'storedquery_id', 'typename']:
[4415]268                otherparams[key]=self._owsParams[key]       
[5132]269        c.resultset, c.additionalobjects=self._runQuery(queryxml, storedqueryid, typename, **otherparams)
[4415]270               
[4344]271        #Group resultset together in a wfs feature collection (use template)
[4289]272        response.headers['content-type'] = 'text/xml'
[4298]273        t = ows_controller.templateLoader.load('wfs_featurecollection.xml')
274        return t.generate(c=c).render()           
275
[4408]276   
[4398]277    def DescribeStoredQueries(self):
278        """ DescribeStoredQueries method. Takes zero or more stored query ids as args"""
[4408]279        allqueries=self.layerMapper.queryDescriptions.queries       
280        storedqueryid=self.getOwsParam('storedqueryid', default=None)
281        if storedqueryid is None:
282            c.storedqueries = self.layerMapper.queryDescriptions.queries
283        else:
284            c.storedqueries={}
285            for queryid in storedqueryid.split(','):
286                c.storedqueries[queryid]=self.layerMapper.queryDescriptions.queries[queryid]       
[4413]287        response.headers['Content-Type'] = 'text/xml'
[4398]288        t = ows_controller.templateLoader.load('wfs_describestoredqueries.xml')
289        return t.generate(c=c).render() 
290         
[4408]291    def ListStoredQueries(self):
292        """ DescribeStoredQueries method. Takes zero or more stored query ids as args"""
293        c.storedqueries = self.layerMapper.queryDescriptions.queries
294        t = ows_controller.templateLoader.load('wfs_liststoredqueries.xml')
[4413]295        response.headers['Content-Type'] = 'text/xml'
[4408]296        return t.generate(c=c).render() 
Note: See TracBrowser for help on using the repository browser.