1 | # Copyright (C) 2007 STFC & NERC (Science and Technology Facilities Council). |
---|
2 | # This software may be distributed under the terms of the |
---|
3 | # Q Public License, version 1.0 or later. |
---|
4 | # http://ndg.nerc.ac.uk/public_docs/QPublic_license.txt |
---|
5 | """ |
---|
6 | WCS controller driven by CSML. |
---|
7 | |
---|
8 | @author: DominicLowe, Stephen Pascoe |
---|
9 | """ |
---|
10 | |
---|
11 | |
---|
12 | try: #python 2.5 |
---|
13 | from xml.etree import ElementTree as ET |
---|
14 | except ImportError: |
---|
15 | try: |
---|
16 | # if you've installed it yourself it comes this way |
---|
17 | import ElementTree as ET |
---|
18 | except ImportError: |
---|
19 | # if you've egged it this is the way it comes |
---|
20 | from elementtree import ElementTree as ET |
---|
21 | |
---|
22 | import os, time, string, StringIO |
---|
23 | |
---|
24 | from ows_server.lib.base import * |
---|
25 | from ows_server.lib.decorators import * |
---|
26 | import ows_server.lib.validators as V |
---|
27 | |
---|
28 | from ows_common import exceptions as OWS_E |
---|
29 | from ows_common.wcs import * |
---|
30 | from ows_common.common import BoundingBox |
---|
31 | from ows_common.domain import ValuesUnit, PossibleValues |
---|
32 | |
---|
33 | from ows_server.lib.csml_util import get_csml_doc, extractToNetCDF |
---|
34 | from ows_server.lib.ndgInterface import interface |
---|
35 | from ows_server.models.wcs_CoverageDescription import CoverageDescription |
---|
36 | |
---|
37 | |
---|
38 | import logging |
---|
39 | logger = logging.getLogger('ows_server.controllers.csml_wcs_1_0') |
---|
40 | |
---|
41 | |
---|
42 | try: |
---|
43 | #python 2.5 |
---|
44 | from email.mime.text import MIMEText |
---|
45 | from email.mime.multipart import MIMEMultipart |
---|
46 | from email.MIMEBase import MIMEBase |
---|
47 | from email import encoders |
---|
48 | except: |
---|
49 | #python 2.4 |
---|
50 | from email.MIMEText import MIMEText |
---|
51 | from email.MIMEMultipart import MIMEMultipart |
---|
52 | from email.MIMEBase import MIMEBase |
---|
53 | from email import Encoders as encoders |
---|
54 | |
---|
55 | |
---|
56 | class CsmlWcs10Controller(OwsController): |
---|
57 | _ows_parameters = { |
---|
58 | 'Format': make_domain(['text/xml']), |
---|
59 | 'ExceptionFormat': make_domain(['text/xml']), |
---|
60 | } |
---|
61 | |
---|
62 | |
---|
63 | def _createMultipartMime(self, xml, netcdf): |
---|
64 | #returns a multipart mime file containing the coverage xml + a netcdf file |
---|
65 | |
---|
66 | # Create the container (outer) email message. |
---|
67 | msg=MIMEMultipart() |
---|
68 | |
---|
69 | xmlfile =StringIO.StringIO(xml) |
---|
70 | xmlfile.readline(), xmlfile.readline() #don't read in first 2 lines (the content type) as MIMEBase also provides it. |
---|
71 | |
---|
72 | |
---|
73 | #add the XML part |
---|
74 | submsg=MIMEText(xmlfile.read(), _subtype='xml') |
---|
75 | submsg.add_header('Content-ID', '<coverage.xml>') |
---|
76 | submsg.add_header('Content-Disposition', 'attachment; filename="coverage.xml"') |
---|
77 | #submsg.set_type('text/xml; name="coverage.xml"') |
---|
78 | msg.attach(submsg) |
---|
79 | |
---|
80 | |
---|
81 | #add the NetCDF part |
---|
82 | submsg= MIMEBase('application', 'CF-netcdf') #check in ogc docs |
---|
83 | submsg.set_payload(netcdf.read()) |
---|
84 | submsg.set_type('application/CF-netcdf') |
---|
85 | submsg.add_header('Content-Disposition', 'attachment; filename="coverage.nc"') |
---|
86 | submsg.add_header('Content-ID', '<coverage.nc>') |
---|
87 | netcdf.close() |
---|
88 | # Encode the payload using Base64 |
---|
89 | encoders.encode_base64(submsg) |
---|
90 | msg.attach(submsg) |
---|
91 | |
---|
92 | #return the message |
---|
93 | return msg |
---|
94 | |
---|
95 | |
---|
96 | def _loadFeatureDimensions(self, feature): |
---|
97 | dims = {} |
---|
98 | lon=feature.getLongitudeAxis() |
---|
99 | lat=feature.getLongitudeAxis() |
---|
100 | domain=feature.getDomain() |
---|
101 | for axis_name, axis in domain.iteritems(): |
---|
102 | if axis_name in [lon,lat]: |
---|
103 | continue |
---|
104 | dims[axis_name] = Domain(possibleValues=PossibleValues.fromAllowedValues(axis), |
---|
105 | #!TODO: this is a fudge until we can deduce UOM. |
---|
106 | valuesUnit=ValuesUnit(uoms=[''], |
---|
107 | referenceSystems=[''])) |
---|
108 | return dims |
---|
109 | |
---|
110 | def _loadFeatureSummary(self, feature): |
---|
111 | dims = self._loadFeatureDimensions(feature) |
---|
112 | #TODO - need to ensure proper values for Name. ID and Description are populated. |
---|
113 | cvgTitle=[feature.description.CONTENT] |
---|
114 | cvgDescription=feature.description.CONTENT |
---|
115 | cvgAbstract=[feature.description.CONTENT] |
---|
116 | csmlbbox=feature.getCSMLBoundingBox() |
---|
117 | if csmlbbox is not None: |
---|
118 | bbox=csmlbbox.getBox() |
---|
119 | else: |
---|
120 | csmlbbox=c.dataset.getCSMLBoundingBox() |
---|
121 | bbox=csmlbbox.getBox() |
---|
122 | #crs= csmlbbox.getCRSName() |
---|
123 | crs=feature.getNativeCRS() |
---|
124 | crslist=[crs] #TODO, get these crs from the csml features |
---|
125 | return WcsDatasetSummary(identifier=feature.id, |
---|
126 | titles=cvgTitle, |
---|
127 | boundingBoxes=[BoundingBox([bbox[0],bbox[1]], [bbox[2],bbox[3]], |
---|
128 | crs='CRS:84')], description=cvgDescription,abstracts=cvgAbstract, formats=['application/cf-netcdf'], |
---|
129 | supportedCRSs=crslist |
---|
130 | ) |
---|
131 | |
---|
132 | def _loadCapabilities(self): |
---|
133 | """ |
---|
134 | Overriding subclass to add layer capabilities |
---|
135 | |
---|
136 | """ |
---|
137 | # Get default capabilities from superclass |
---|
138 | sm = super(CsmlWcs10Controller, self)._loadCapabilities() |
---|
139 | ds = WcsDatasetSummary(titles=['Root Dataset'], datasetSummaries=[], CRSs=['CRS:84']) |
---|
140 | # Add a DatasetSummary for each feature |
---|
141 | for f_n in c.dataset.getFeatureList(): |
---|
142 | feature_ds = self._loadFeatureSummary(c.dataset.getFeature(f_n)) |
---|
143 | ds.datasetSummaries.append(feature_ds) |
---|
144 | sm.contents = Contents(datasetSummaries=[ds]) |
---|
145 | return sm |
---|
146 | |
---|
147 | def _buildCoverageDescriptions(self): |
---|
148 | """ builds a collection of CoverageDescription objects - used for DescribeCoverage """ |
---|
149 | CoverageDescriptions=[] |
---|
150 | csmlbbox=c.dataset.getCSMLBoundingBox() |
---|
151 | dsbbox=csmlbbox.getBox() |
---|
152 | dstimes=csmlbbox.getTimeLimits() |
---|
153 | dscrs=csmlbbox.getCRSName() |
---|
154 | for f in self.features: |
---|
155 | feature = self.features[f] |
---|
156 | csmlbbox=feature.getCSMLBoundingBox() |
---|
157 | if csmlbbox is None: #use the bounding box of the dataset. |
---|
158 | bbox=dsbbox |
---|
159 | timeLimits=dstimes |
---|
160 | crsname=dscrs |
---|
161 | else: #use the feature's bounding box info |
---|
162 | bbox=csmlbbox.getBox() |
---|
163 | timeLimits=csmlbbox.getTimeLimits() |
---|
164 | crsname=csmlbbox.getCRSName() |
---|
165 | cd=CoverageDescription(identifier=f,titles=feature.name.CONTENT, keywords=None, abstracts=feature.description.CONTENT, boundingBoxes=[BoundingBox([bbox[0],bbox[1]], [bbox[2],bbox[3]], crs=crsname)], timeDomain=timeLimits) |
---|
166 | CoverageDescriptions.append(cd) |
---|
167 | return CoverageDescriptions |
---|
168 | |
---|
169 | @operation |
---|
170 | @parameter('Format', possibleValues=['text/xml']) |
---|
171 | @parameter('Service', possibleValues=['WCS'], required=True) |
---|
172 | @parameter('Version', possibleValues=['1.0.0']) |
---|
173 | def GetCapabilities(self, uri, service=None, version=None): |
---|
174 | """ |
---|
175 | @note: format and updatesequence parameters are not supported |
---|
176 | by this WMS. |
---|
177 | |
---|
178 | """ |
---|
179 | # Populate the context object with information required by the template |
---|
180 | |
---|
181 | #get doc from cache or disk: |
---|
182 | try: |
---|
183 | rstatus,c.dataset=interface.GetParsedCSML(uri) |
---|
184 | if not rstatus: |
---|
185 | c.xml='<div class="error">%s</div>'%c.dataset |
---|
186 | resp=render_response('error') |
---|
187 | return resp |
---|
188 | |
---|
189 | if type(c.dataset) is str: |
---|
190 | #If not a csml datset is some message from exist such as 'access denied' |
---|
191 | return Response(c.dataset) |
---|
192 | return self._renderCapabilities('wcs1_0_capabilities') |
---|
193 | except Exception, e: |
---|
194 | if isinstance(e, OWS_E.OwsError): |
---|
195 | raise e |
---|
196 | elif isinstance(e, ValueError): |
---|
197 | c.xml='<div class="error">%s</div>'%e |
---|
198 | return render_response('error') |
---|
199 | else: |
---|
200 | raise OWS_E.NoApplicableCode(e) |
---|
201 | |
---|
202 | @operation |
---|
203 | @parameter('Service', possibleValues=['WCS'], required=True) |
---|
204 | @parameter('Version', possibleValues=['1.0.0']) |
---|
205 | @parameter('Identifiers', required=True) |
---|
206 | @parameter('Format', possibleValues=['text/xml'], required=True) #IS THIS MANDATORY |
---|
207 | def DescribeCoverage(self, uri, version, service, identifiers, format='text/xml'): |
---|
208 | """ |
---|
209 | WCS DescribeCoverage operation |
---|
210 | """ |
---|
211 | try: |
---|
212 | self.features={} #dictionary to hold requested coverages |
---|
213 | rstatus,c.dataset=interface.GetParsedCSML(uri) |
---|
214 | if not rstatus: raise ValueError(c.dataset) |
---|
215 | for ident in identifiers.split(','): |
---|
216 | feature = c.dataset.getFeature(ident) |
---|
217 | if feature is None: |
---|
218 | raise OWS_E.InvalidParameterValue('Coverage with id=%s not found'%ident, 'identifiers') |
---|
219 | self.features[ident]=feature |
---|
220 | c.covDescs=self._buildCoverageDescriptions() |
---|
221 | r=render_response('wcs/wcs_DescribeCoverageResponse', format='xml') |
---|
222 | r.headers['content-type'] = 'text/xml' |
---|
223 | return r |
---|
224 | except Exception, e: |
---|
225 | if isinstance(e, OWS_E.OwsError): |
---|
226 | raise e |
---|
227 | elif isinstance(e, ValueError): |
---|
228 | c.xml='<div class="error">%s</div>'%e |
---|
229 | return render_response('error') |
---|
230 | else: |
---|
231 | raise OWS_E.NoApplicableCode(e) |
---|
232 | |
---|
233 | @operation |
---|
234 | @parameter('Version', possibleValues=['1.0.0'], required=True) |
---|
235 | @parameter('Identifier', required=True) |
---|
236 | @parameter('BoundingBox', required=True, validator=V.bbox_2or3d) |
---|
237 | @parameter('TimeSequence',required=True, validator=V.iso8601_time) |
---|
238 | @parameter('Format', possibleValues=['application/netcdf'], required=True) |
---|
239 | @parameter('Store', validator = V.boolean('Store')) |
---|
240 | @parameter('Status', validator = V.boolean('Status')) |
---|
241 | #TODO some more parameters to add here |
---|
242 | # Dimension parameters Time, Elevation, etc. are handled separately |
---|
243 | def GetCoverage(self, uri, version, format, identifier, boundingbox, timesequence, store=False, status=False): |
---|
244 | # Retrieve dataset and selected feature |
---|
245 | try: |
---|
246 | rstatus,dataset=interface.GetParsedCSML(uri) |
---|
247 | if not rstatus: |
---|
248 | c.xml='<div class="error">%s</div>'%dataset |
---|
249 | resp=render_response('error') |
---|
250 | return resp |
---|
251 | feature = dataset.getFeature(identifier) |
---|
252 | if feature is None: |
---|
253 | raise OWS_E.InvalidParameterValue('Coverage not found', 'identifier') |
---|
254 | |
---|
255 | |
---|
256 | #set bounding box |
---|
257 | |
---|
258 | lon=feature.getLongitudeAxis() |
---|
259 | lat=feature.getLatitudeAxis() |
---|
260 | t=feature.getTimeAxis() |
---|
261 | print '%s %s %s'%(lon,lat,t) |
---|
262 | if None in [lon, lat, time]: |
---|
263 | #TODO need to return a suitable wcs error. |
---|
264 | print 'warning, could not get correct axis info' |
---|
265 | |
---|
266 | #create selection dictionary: |
---|
267 | sel={} |
---|
268 | sel[lat]=(boundingbox[1], boundingbox[3]) |
---|
269 | sel[lon]=(boundingbox[0], boundingbox[2]) |
---|
270 | if type(timesequence) is unicode: |
---|
271 | sel[t]=str(timesequence) |
---|
272 | else: |
---|
273 | sel[t]=timesequence |
---|
274 | |
---|
275 | #z is the 4th axis (eg height or pressure). |
---|
276 | #NOTE, need to decide whether bounding box is of form: x1,y1,z1,x2,y2,z2 or x1,y1,x2,y2,z1,z2 |
---|
277 | #currently the latter is implemented. |
---|
278 | |
---|
279 | if len(boundingbox) == 6: |
---|
280 | for ax in feature.getAxisLabels(): |
---|
281 | if ax not in [lat, lon, t]: |
---|
282 | #must be Z |
---|
283 | z=str(ax) |
---|
284 | sel[z]=(boundingbox[4], boundingbox[5]) |
---|
285 | |
---|
286 | |
---|
287 | axisNames=feature.getAxisLabels() |
---|
288 | |
---|
289 | # Extract via CSML.subsetToGridSeries() |
---|
290 | |
---|
291 | print 'SEL %s'%sel |
---|
292 | if store: |
---|
293 | #need to farm off to WPS |
---|
294 | #but for now... |
---|
295 | filename = extractToNetCDF(feature, sel, publish = True) |
---|
296 | else: |
---|
297 | filename = extractToNetCDF(feature, sel) |
---|
298 | |
---|
299 | |
---|
300 | #use the randomly allocated filename as a basis for an identifier |
---|
301 | f=os.path.basename(filename) |
---|
302 | c.fileID=os.path.splitext(f)[0] |
---|
303 | |
---|
304 | #Depending on if the 'store' parameter is set, either return the netcdf file + coverage xml as a multipart mime or return a coverage document containing a link. |
---|
305 | |
---|
306 | if store: |
---|
307 | if status: |
---|
308 | #STORE = true, STATUS = true: |
---|
309 | #hand off file "id" to StatusController to determine correct ExectuteResponse type response. |
---|
310 | status=StatusController() |
---|
311 | jobID=os.path.splitext(os.path.basename(filename)[9:])[0] #remove the 'csml_wxs_' prefix and file extension to create a jobID |
---|
312 | return status.getStatus(jobID) |
---|
313 | else: |
---|
314 | #STORE=true, STATUS = false: Return Coverage XML document with link to file. |
---|
315 | #use the temp file name (minus extension) as an ID |
---|
316 | |
---|
317 | try: |
---|
318 | hostname=request.environ['paste.config']['app_conf']['proxyname'] |
---|
319 | except: |
---|
320 | hostname=hostname=request.environ['HTTP_HOST'] |
---|
321 | c.hyperlink ='http://'+hostname+'/'+os.path.basename(request.environ['paste.config']['app_conf']['publish_dir'])+'/'+os.path.basename(filename) |
---|
322 | r=render_response('wcs_getCoverageResponse', format='xml') |
---|
323 | r.headers['content-type'] = 'text/xml' |
---|
324 | #write ndgSec to text file and store with coverage file: |
---|
325 | textName=request.environ['paste.config']['app_conf']['publish_dir']+'/'+os.path.splitext(os.path.basename(filename))[0]+'.txt' |
---|
326 | secText=open(textName, 'w') |
---|
327 | if 'ndgSec' in session: |
---|
328 | username=str(session['ndgSec']['u']) |
---|
329 | securityinfo=username |
---|
330 | else: |
---|
331 | securityinfo='No Security' |
---|
332 | secText.write(securityinfo) |
---|
333 | secText.close() |
---|
334 | return r |
---|
335 | else: |
---|
336 | #STORE = FALSE, STATUS therefore irrelevant, return Multipart Mime. |
---|
337 | netcdfFile=open(filename, 'r') |
---|
338 | c.hyperlink="cid:coverage.nc" |
---|
339 | xmlfile=render_response('wcs_getCoverageResponse', format='xml') |
---|
340 | xmlfile.headers['content-type'] = 'text/xml' |
---|
341 | multipart=self._createMultipartMime(xmlfile, netcdfFile) |
---|
342 | msg=multipart |
---|
343 | try: |
---|
344 | #0.9.6 |
---|
345 | pylons.response.headers['Content-Type']='multipart' |
---|
346 | return pylons.response(content=msg) |
---|
347 | except: |
---|
348 | #0.9.5 |
---|
349 | return Response(content=msg, mimetype='multipart') |
---|
350 | except Exception, e: |
---|
351 | if isinstance(e, OWS_E.OwsError): |
---|
352 | raise e |
---|
353 | elif isinstance(e, ValueError): |
---|
354 | c.xml='<div class="error">%s</div>'%e |
---|
355 | return render_response('error') |
---|
356 | else: |
---|
357 | raise OWS_E.NoApplicableCode(e) |
---|
358 | |
---|
359 | |
---|