source: branches/ms-style/zoo-project/zoo-services/ogr/base-vect-ops-py/cgi-env/ogr_sp.py @ 986

Last change on this file since 986 was 465, checked in by djay, 11 years ago

Add the optional YAML ZCFG support #4 and the zcfg2yaml converter. Return error messages that enable the service provider to quickly identify the root cause of errors due to configuration file syntax #90. Fix logic in addMapToMap #91. Enable multiple range definition using default and supported blocks. Add the lastest revision number in version.h (available from Python ZOO-API as zoo.VERSION).

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-python
File size: 13.2 KB
Line 
1# -*- coding: utf-8 -*-
2#
3# Author : Gérald FENOY
4#
5# Copyright 2009-2013 GeoLabs SARL. All rights reserved.
6#
7# Permission is hereby granted, free of charge, to any person obtaining a
8# copy of this software and associated documentation files (the
9# "Software"), to deal in the Software without restriction, including with
10# out limitation the rights to use, copy, modify, merge, publish,
11# distribute, sublicense, and/or sell copies of the Software, and to
12# permit persons to whom the Software is furnished to do so, subject to
13# the following conditions:
14#
15# The above copyright notice and this permission notice shall be included
16# in all copies or substantial portions of the Software.
17#
18# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25#
26
27from osgeo import *
28import osgeo.ogr
29import osgeo.gdal
30import libxml2
31import os
32import sys
33import zoo
34
35def readFileFromBuffer(data,ext):
36    try:
37        geometry=[]
38        print >> sys.stderr,'/vsimem//temp1'+ext
39        #print >> sys.stderr,data
40        osgeo.gdal.FileFromMemBuffer('/vsimem//temp1'+ext,data)
41        ds = osgeo.ogr.Open('/vsimem//temp1'+ext)
42        lyr = ds.GetLayer(0)
43        feat = lyr.GetNextFeature()
44        while feat is not None:
45            geometry+=[feat.Clone()]
46            feat.Destroy()
47            feat = lyr.GetNextFeature()
48        ds.Destroy()
49        osgeo.gdal.Unlink('/vsimem//temp1'+ext)
50        return geometry
51    except Exception,e:
52        print >> sys.stderr,e
53        return []
54   
55def buildFeatureFromGeomtry(conf,geom,driverName,ext):
56    drv = osgeo.ogr.GetDriverByName( driverName )
57    ds = drv.CreateDataSource( "/vsimem//store"+conf["lenv"]["sid"]+"0."+ext )
58    lyr = ds.CreateLayer( "Result", None, osgeo.ogr.wkbUnknown )
59    field_defn = osgeo.ogr.FieldDefn( "Name", osgeo.ogr.OFTString )
60    field_defn.SetWidth( len("Result10000") )
61    lyr.CreateField ( field_defn )
62    feat = osgeo.ogr.Feature(lyr.GetLayerDefn())
63    feat.SetField( "Name", "Input0" )
64    feat.SetGeometry(geom)
65    lyr.CreateFeature(feat)
66    ds.Destroy()
67    return [feat]
68
69def createGeometryFromWFS(conf,my_wfs_response):
70    try:
71        geom=osgeo.ogr.CreateGeometryFromGML(my_wfs_response.replace('<?xml version="1.0" encoding="utf-8"?>\n','').replace('<?xml version=\'1.0\' encoding="utf-8"?>\n',''))
72    except Exception,e:
73        print >> sys.stderr,"**"
74        print >> sys.stderr,e
75        geom=None
76    try:
77        print >> sys.stderr,geom is None
78        if geom is None:
79            if not(conf["lenv"].has_key("cnt")):
80                conf["lenv"]["cnt"]=0
81            else:
82                conf["lenv"]["cnt"]+=1
83            return readFileFromBuffer(my_wfs_response,str(conf["lenv"]["cnt"]))
84        else:
85            return buildFeatureFromGeomtry(conf,geom,"GML","xml")
86    except:
87        print >> sys.stderr,"Unable to load file input data !!!\n\n\n"
88
89def createLayerFromJson(conf,obj):
90    geom=osgeo.ogr.CreateGeometryFromJson(obj)
91    if geom is None:
92        return readFileFromBuffer(obj,".json")
93    else:
94        return buildFeatureFromGeomtry(conf,geom,"GeoJSON","json")
95
96def extractInputs(conf,obj):
97    if obj["mimeType"]=="application/json":
98        return createLayerFromJson(conf,obj["value"])
99    else:
100        return createGeometryFromWFS(conf,obj["value"])
101   
102def outputResult(conf,obj,geom):
103    if obj["mimeType"].count("text/xml")>0:
104        driverName = "GML"
105        extension = [ ".xml" , ".xsd" ]
106        format_list = { "2.": 'GML2', "3.1.1": 'GML3', "3.1": 'GML3Deegree', "3.2": 'GML3.2' }
107        opts=['FORMAT=%s,GML3_LONGSRS=YES',format_list["3.2"]]
108        for i in format_list:
109            if obj["mimeType"].count(i)>0:
110                opts=['FORMAT=%s,GML3_LONGSRS=YES',format_list[i]]
111    if obj["mimeType"]=="application/json":
112        driverName = "GeoJSON"
113        extension = [ ".js" ]
114        opts=None
115    if obj.keys().count("schema")>0 and \
116            obj["schema"]=="http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd":
117        driverName = "KML"
118        extension = [ ".kml" ]
119        opts=None
120    drv = osgeo.ogr.GetDriverByName( driverName )
121    print >> sys.stderr,drv
122    # Create virtual file
123    ds = drv.CreateDataSource( "/vsimem/store"+conf["lenv"]["sid"]+extension[0],options = opts)
124    print >> sys.stderr,ds
125    lyr = ds.CreateLayer( "Result", None, osgeo.ogr.wkbUnknown )
126    print >> sys.stderr,lyr
127    i=0
128    print >> sys.stderr,driverName
129    print >> sys.stderr,extension
130    while i < len(geom):
131        if i==0 and driverName!="GeoJSON":
132            poDstFDefn=geom[i].GetDefnRef()
133            if poDstFDefn is not None:
134                nDstFieldCount = poDstFDefn.GetFieldCount()
135                for iField in range(nDstFieldCount):
136                    poSrcFieldDefn = poDstFDefn.GetFieldDefn(iField)
137                    oFieldDefn = osgeo.ogr.FieldDefn(poSrcFieldDefn.GetNameRef(),poSrcFieldDefn.GetType())
138                    oFieldDefn.SetWidth( poSrcFieldDefn.GetWidth() )
139                    oFieldDefn.SetPrecision( poSrcFieldDefn.GetPrecision() )
140                    lyr.CreateField( oFieldDefn )
141        try:
142            lyr.CreateFeature(geom[i])
143        except:
144            pass
145        geom[i].Destroy()
146        i+=1
147    ds.Destroy()
148    vsiFile=osgeo.gdal.VSIFOpenL("/vsimem/store"+conf["lenv"]["sid"]+extension[0],"r")
149    i=0
150    while osgeo.gdal.VSIFSeekL(vsiFile,0,os.SEEK_END)>0:
151        i+=1
152    fileSize=osgeo.gdal.VSIFTellL(vsiFile)
153    osgeo.gdal.VSIFSeekL(vsiFile,0,os.SEEK_SET)
154    obj["value"]=osgeo.gdal.VSIFReadL(fileSize,1,vsiFile)
155    osgeo.gdal.Unlink("/vsimem/store"+conf["lenv"]["sid"]+extension[0])
156
157def BufferPy(conf,inputs,outputs):
158    print >> sys.stderr, "Starting service ..."
159    try:
160        bdist=float(inputs["BufferDistance"]["value"])
161    except:
162        bdist=1
163    print >> sys.stderr, bdist
164    geometry=extractInputs(conf,inputs["InputPolygon"])
165    i=0
166    rgeometries=[]
167    while i < len(geometry):
168        tmp=geometry[i].Clone()
169        resg=geometry[i].GetGeometryRef().Buffer(bdist)
170        tmp.SetGeometryDirectly(resg)
171        rgeometries+=[tmp]
172        geometry[i].Destroy()
173        resg.thisown=False 
174        tmp.thisown=False
175        i+=1
176    outputResult(conf,outputs["Result"],rgeometries)
177    i=0
178    return zoo.SERVICE_SUCCEEDED
179
180def Clean(conf,inputs,outputs):
181    from shapely.wkb import loads
182    print >> sys.stderr, "Starting service ..."
183    features=extractInputs(conf,inputs["InputData"])
184    i=0
185    rgeometries=[]
186    while i < len(features):
187        tmp=features[i].Clone()
188        resg=features[i].GetGeometryRef()
189        if resg is not None:
190            geom = loads(resg.ExportToWkb())
191            if geom.is_valid:
192                tmp.SetGeometryDirectly(resg)
193                rgeometries+=[tmp]
194                print >> sys.stderr,"valid !"
195            else:
196                print >> sys.stderr,"invalid !"
197                print >> sys.stderr,geom.wkt[0:50]
198        features[i].Destroy()
199        resg.thisown=False 
200        tmp.thisown=False
201        i+=1
202    outputResult(conf,outputs["Result"],rgeometries)
203    i=0
204    print >> sys.stderr,"Return"
205    return zoo.SERVICE_SUCCEEDED
206
207def TransformService(conf,inputs,outputs):
208    from osgeo import osr
209    geometry=extractInputs(conf,inputs["InputData"])
210    sourceRef = osr.SpatialReference()
211    tmp=inputs["SourceCRS"]["value"].split(":")
212    sourceRef.ImportFromEPSG(int(tmp[len(tmp)-1]))
213    targetRef = osr.SpatialReference()   
214    tmp=inputs["TargetCRS"]["value"].split(":")
215    targetRef.ImportFromEPSG(int(tmp[len(tmp)-1]))
216    transform = osr.CoordinateTransformation(sourceRef, targetRef)
217    i=0
218    rgeometries=[]
219    while i < len(geometry):
220        tmp=geometry[i].Clone()
221        resg=geometry[i].GetGeometryRef()
222        resg.Transform(transform)
223        tmp.SetGeometryDirectly(resg.Clone())
224        rgeometries+=[tmp]
225        geometry[i].Destroy()
226        i+=1
227    outputResult(conf,outputs["TransformedData"],rgeometries)
228    return zoo.SERVICE_SUCCEEDED
229
230def BoundaryPy(conf,inputs,outputs):
231    geometry=extractInputs(conf,inputs["InputPolygon"])
232    i=0
233    rgeometries=[]
234    while i < len(geometry):
235        tmp=geometry[i].Clone()
236        resg=geometry[i].GetGeometryRef()
237        resg=resg.GetBoundary()
238        tmp.SetGeometryDirectly(resg)
239        rgeometries+=[tmp]
240        geometry[i].Destroy()
241        i+=1
242    outputResult(conf,outputs["Result"],rgeometries)
243    return zoo.SERVICE_SUCCEEDED
244
245def CentroidPy(conf,inputs,outputs):
246    geometry=extractInputs(conf,inputs["InputPolygon"])
247    i=0
248    rgeometries=[]
249    while i < len(geometry):
250        tmp=geometry[i].Clone()
251        resg=geometry[i].GetGeometryRef()
252        if resg.GetGeometryType()!=3:
253            resg=resg.ConvexHull()
254        resg=resg.Centroid()
255        tmp.SetGeometryDirectly(resg)
256        rgeometries+=[tmp]
257        geometry[i].Destroy()
258        i+=1
259    outputResult(conf,outputs["Result"],rgeometries)
260    return zoo.SERVICE_SUCCEEDED
261
262def ConvexHullPy(conf,inputs,outputs):
263    geometry=extractInputs(conf,inputs["InputPolygon"])
264    i=0
265    rgeometries=[]
266    while i < len(geometry):
267        tmp=geometry[i].Clone()
268        resg=geometry[i].GetGeometryRef().ConvexHull()
269        tmp.SetGeometryDirectly(resg)
270        rgeometries+=[tmp]
271        geometry[i].Destroy()
272        i+=1
273    outputResult(conf,outputs["Result"],rgeometries)
274    return zoo.SERVICE_SUCCEEDED
275
276
277
278def EnvelopePy(conf,inputs,outputs):
279    print >> sys.stderr, inputs
280    try:
281        bdist=float(inputs["BufferDistance"]["value"])
282    except:
283        bdist=10
284    geometry=extractInputs(conf,inputs["InputPolygon"])
285    tmp=geometry[0].GetGeometryRef().GetEnvelope()
286    outputs["Result"]["value"]=str(tmp[0])+','+str(tmp[2])+','+str(tmp[1])+','+str(tmp[3])+','+'urn:ogc:def:crs:OGC:1.3:CRS84'
287    print >> sys.stderr,outputs["Result"]
288    return 3
289
290def UnionPy(conf,inputs,outputs):
291    geometry1=extractInputs(conf,inputs["InputEntity1"])
292    geometry2=extractInputs(conf,inputs["InputEntity2"])
293    rgeometries=[]
294    i=0
295    while i < len(geometry1):
296        j=0
297        while j < len(geometry2):
298            tmp=geometry1[i].Clone()
299            resg=geometry2[j].GetGeometryRef()
300            resg=resg.Union(geometry1[i].GetGeometryRef())
301            tmp.SetGeometryDirectly(resg)
302            if not(resg.IsEmpty()):
303                rgeometries+=[tmp]
304            j+=1
305        geometry1[i].Destroy()
306        i+=1
307    i=0
308    while i < len(geometry2):
309        geometry2[i].Destroy()
310        i+=1
311    outputResult(conf,outputs["Result"],rgeometries)
312    return 3
313
314def IntersectionPy(conf,inputs,outputs):
315
316    geometry1=extractInputs(conf,inputs["InputEntity1"])
317    geometry2=extractInputs(conf,inputs["InputEntity2"])
318
319    print >> sys.stderr,str(len(geometry1))+" "+str(len(geometry2))
320
321    rgeometries=[]
322    fids=[]
323    i=0
324    while i < len(geometry1):
325        j=0
326        while j < len(geometry2):
327            tmp=geometry2[j].Clone()
328            resg=geometry2[j].GetGeometryRef()
329            #resg=resg.Intersection(geometry1[i].GetGeometryRef())
330            resg=geometry1[i].GetGeometryRef().Intersection(resg)
331            tmp.SetGeometryDirectly(resg)
332            if resg is not None and not(resg.IsEmpty()) and fids.count(tmp.GetFID())==0:
333                rgeometries+=[tmp]
334                fids+=[tmp.GetFID()]
335            else:
336                tmp.Destroy()
337            j+=1
338        geometry1[i].Destroy()
339        i+=1
340    i=0
341    while i < len(geometry2):
342        geometry2[i].Destroy()
343        i+=1
344    outputResult(conf,outputs["Result"],rgeometries)
345    print >> sys.stderr,"/outputResult"
346    return 3
347
348def DifferencePy(conf,inputs,outputs):
349    geometry1=extractInputs(conf,inputs["InputEntity1"])
350    geometry2=extractInputs(conf,inputs["InputEntity2"])
351    rgeometries=[]
352    i=0
353    while i < len(geometry1):
354        j=0
355        while j < len(geometry2):
356            tmp=geometry2[j].Clone()
357            resg=geometry1[i].GetGeometryRef()
358            resg=resg.Difference(geometry2[i].GetGeometryRef())
359            tmp.SetGeometryDirectly(resg)
360            if not(resg.IsEmpty()):
361                rgeometries+=[tmp]
362            j+=1
363        geometry1[i].Destroy()
364        i+=1
365    i=0
366    while i < len(geometry2):
367        geometry2[i].Destroy()
368        i+=1
369    outputResult(conf,outputs["Result"],rgeometries)
370    return 3
371
372def SymDifferencePy(conf,inputs,outputs):
373    geometry1=extractInputs(conf,inputs["InputEntity1"])
374    geometry2=extractInputs(conf,inputs["InputEntity2"])
375    rgeometries=[]
376    i=0
377    while i < len(geometry1):
378        j=0
379        while j < len(geometry2):
380            tmp=geometry2[j].Clone()
381            resg=geometry1[i].GetGeometryRef()
382            resg=resg.SymmetricDifference(geometry2[i].GetGeometryRef())
383            tmp.SetGeometryDirectly(resg)
384            rgeometries+=[tmp]
385            j+=1
386        geometry1[i].Destroy()
387        i+=1
388    i=0
389    while i < len(geometry2):
390        geometry2[i].Destroy()
391        i+=1
392    outputResult(conf,outputs["Result"],rgeometries)
393    return 3
394
Note: See TracBrowser for help on using the repository browser.

Search

ZOO Sponsors

http://www.zoo-project.org/trac/chrome/site/img/geolabs-logo.pnghttp://www.zoo-project.org/trac/chrome/site/img/neogeo-logo.png http://www.zoo-project.org/trac/chrome/site/img/apptech-logo.png http://www.zoo-project.org/trac/chrome/site/img/3liz-logo.png http://www.zoo-project.org/trac/chrome/site/img/gateway-logo.png

Become a sponsor !

Knowledge partners

http://www.zoo-project.org/trac/chrome/site/img/ocu-logo.png http://www.zoo-project.org/trac/chrome/site/img/gucas-logo.png http://www.zoo-project.org/trac/chrome/site/img/polimi-logo.png http://www.zoo-project.org/trac/chrome/site/img/fem-logo.png http://www.zoo-project.org/trac/chrome/site/img/supsi-logo.png http://www.zoo-project.org/trac/chrome/site/img/cumtb-logo.png

Become a knowledge partner

Related links

http://zoo-project.org/img/ogclogo.png http://zoo-project.org/img/osgeologo.png