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

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

Validated output of describestoredqueries and liststoredqueries

Line 
1"""
2WFS controller for OGC Web Services (OWS).
3
4@author: Dominic Lowe
5"""
6
7import re
8from cStringIO import StringIO
9from sets import Set
10from matplotlib.cm import get_cmap
11from pylons import request, response, c, config
12import ConfigParser
13
14import logging
15log = logging.getLogger(__name__)
16
17import Image
18
19from cows.model.wfs import WfsFeatureSummary
20from cows.model.filterencoding import FEQueryProcessor
21from cows.model import PossibleValues, WGS84BoundingBox, BoundingBox, Contents
22from cows.pylons import ows_controller
23from cows.exceptions import *
24from cows import bbox_util
25
26class WFSController(ows_controller.OWSController):
27    """
28    Subclass this controller in a pylons application and set the layerMapper
29    class attribute to implement a WFS. Each layer can be mapped to a Feature for the WFS.
30
31    @cvar layerMapper: an cows.service.wxs_iface.ILayerMapper object.
32   
33
34    """
35    layerMapper = None
36    _layerSlabCache = {}
37
38    #-------------------------------------------------------------------------
39    # Attributes required by OWSController
40
41    service = 'WFS'
42    owsOperations = (ows_controller.OWSController.owsOperations + ['DescribeFeatureType', 'GetFeature', 'DescribeStoredQueries','ListStoredQueries'])
43    validVersions = ['1.1.0', '2.0.0']
44   
45
46    #-------------------------------------------------------------------------
47
48    def __before__(self, **kwargs):
49        """
50        This default implementation of __before__() will pass all routes
51        arguments to the layer mapper to retrieve a list of layers for
52        this WFS.
53
54        It will be called automatically by pylons before each action method.
55
56
57        """
58        log.debug('loading layers')
59        self.layers, self.featureset = self.layerMapper.map(**kwargs)
60        log.debug('Feature instances %s'%self.featureset.featureinstances)
61   
62        #-------------------------------------------------------------------------
63        # Methods implementing stubs in OWSController
64
65    def _renderCapabilities(self, version, format):
66        """
67        Renders capabilities document.
68        """
69        if version == '1.1.0':
70            t = ows_controller.templateLoader.load('wfs_capabilities_1_1_0.xml')
71        elif version == '2.0.0':
72            t = ows_controller.templateLoader.load('wfs_capabilities_2_0_0.xml')
73        else:
74            # We should never get here!  The framework should raise an exception before now.
75            raise RuntimeError("Version %s not supported" % version)
76       
77        return t.generate(c=c).render()
78
79    def _loadCapabilities(self):
80        """
81        @note: Assumes self.layers has already been created by __before__().
82        Builds capabilities document.
83
84        """
85        log.info('Loading WFS Capabilites')
86       
87        ows_controller.addOperation('GetFeature')
88        ows_controller.addOperation('DescribeFeature')
89        ows_controller.addOperation('DescribeStoredQueries')
90       
91       
92        featureInfoFormats = Set()
93
94        log.debug('Loading capabilities contents')
95        c.capabilities.contents = Contents()
96       
97       
98        ftlist={}
99        #       
100       
101        for layerName, layer in self.layers.items():
102            log.info('Loading layer %s' % layerName)
103#            log.info('feature type %s'%layer._feature)
104
105            wgs84BBox = WGS84BoundingBox(layer.wgs84BBox[:2],
106                                         layer.wgs84BBox[2:])
107           
108            ds = WfsFeatureSummary(keywords=layer.keywords, 
109                                   outputformats=layer.outputformats, 
110                                   identifier=layerName,
111                                   titles=[layer.title],
112                                   abstracts=[layer.abstract],                                   
113                                   wgs84BoundingBoxes=[wgs84BBox])
114
115            c.capabilities.contents.datasetSummaries.append(ds)
116
117    def _getSchema(self, typename):
118        namespace = typename.split(':')[0]
119        schemalocation = conf
120       
121    def _parsetypename(self, typename):
122        """ parse feature type name into schema and name"""       
123        if typename not in self.layers.keys():
124            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')
125   
126        namespace, ft = typename.split(':')
127        wfsconfiglocation=config['wfsconfig']
128        wfscfg = ConfigParser.ConfigParser()
129        wfscfg.read(wfsconfiglocation)     
130        xmlschema=open(wfscfg.get('application_schemas', namespace)).read()     
131        log.debug('location of application schema %s' %(xmlschema))
132        return xmlschema
133
134    def DescribeFeatureType(self):
135        """ DescribeFeatureType """
136        version = self.getOwsParam('version', default=self.validVersions[0])
137        if version not in self.validVersions:
138            raise InvalidParameterValue('Version %s not supported' % version,
139                                        'version')
140        typename=self.getOwsParam('typename')
141        ftschema =self._parsetypename(typename)
142        log.debug(self.layers.items())       
143               
144        outputformat=self.getOwsParam('outputformat', default='text/xml')
145       
146        #temporarily returns entire schema
147        #TODO: return single featuretype definition
148        msg  = ftschema
149        response.headers['content-type'] = 'text/xml'
150        return msg
151 
152    def GetFeature(self):
153        """ GetFeature request
154        """
155        #TODO QUERY model
156        version = self.getOwsParam('version', default=self.validVersions[0])
157        if version not in self.validVersions:
158            raise InvalidParameterValue('Version %s not supported' % version,
159                                        'version')
160
161        #The GetFeature request may either use the 'query' filter encoding or a
162        #storedquery, but not both:
163#        if self.getOwsParam('storedquery_id'):
164       
165        #Parse the query to analyse the filters it contains
166        queryxml=self.getOwsParam('query',default=None)
167        storedqueryid=self.getOwsParam('storedquery_id', default=None)
168       
169        #TODO get any other parameters from self._owsParams and pass them to the stored query       
170        if queryxml:
171            qp=FEQueryProcessor()
172            c.resultset=qp.evaluate(self.featureset, queryxml)
173            log.debug('Final resultset from query processor %s'%c.resultset)
174        elif storedqueryid:
175            storedquery, func=self.layerMapper.queryDescriptions.queries[storedqueryid]
176            c.resultset=func(self.featureset, arg1='cat', arg2='dog')
177            log.debug('Final resultset from stored query %s'%c.resultset)
178        else:
179            pass #TODO need to raise error if neither query or storedquery_id are provided
180       
181        #Group resultset together in a wfs feature collection (use template)
182        response.headers['content-type'] = 'text/xml'
183        t = ows_controller.templateLoader.load('wfs_featurecollection.xml')
184        return t.generate(c=c).render()           
185
186   
187    def DescribeStoredQueries(self):
188        """ DescribeStoredQueries method. Takes zero or more stored query ids as args"""
189        allqueries=self.layerMapper.queryDescriptions.queries       
190        storedqueryid=self.getOwsParam('storedqueryid', default=None)
191        if storedqueryid is None:
192            c.storedqueries = self.layerMapper.queryDescriptions.queries
193        else:
194            c.storedqueries={}
195            for queryid in storedqueryid.split(','):
196                c.storedqueries[queryid]=self.layerMapper.queryDescriptions.queries[queryid]       
197        t = ows_controller.templateLoader.load('wfs_describestoredqueries.xml')
198        return t.generate(c=c).render() 
199         
200    def ListStoredQueries(self):
201        """ DescribeStoredQueries method. Takes zero or more stored query ids as args"""
202        c.storedqueries = self.layerMapper.queryDescriptions.queries
203        t = ows_controller.templateLoader.load('wfs_liststoredqueries.xml')
204        temp=t.generate(c=c)
205        return t.generate(c=c).render() 
Note: See TracBrowser for help on using the repository browser.