source: trunk/zoo-project/zoo-services/ogr/base-vect-ops-py/cgi-env/ogr_sp.py @ 479

Last change on this file since 479 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
RevLine 
[447]1# -*- coding: utf-8 -*-
[422]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
[257]27from osgeo import *
[9]28import osgeo.ogr
[257]29import osgeo.gdal
[9]30import libxml2
[106]31import os
32import sys
[382]33import zoo
[9]34
[360]35def readFileFromBuffer(data,ext):
[382]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)
[360]43        feat = lyr.GetNextFeature()
[382]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 []
[465]54   
[360]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
[257]69def createGeometryFromWFS(conf,my_wfs_response):
[106]70    try:
[465]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
[360]75        geom=None
76    try:
[465]77        print >> sys.stderr,geom is None
[360]78        if geom is None:
[382]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"]))
[257]84        else:
[360]85            return buildFeatureFromGeomtry(conf,geom,"GML","xml")
[106]86    except:
[360]87        print >> sys.stderr,"Unable to load file input data !!!\n\n\n"
[9]88
[360]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
[257]96def extractInputs(conf,obj):
[9]97    if obj["mimeType"]=="application/json":
[360]98        return createLayerFromJson(conf,obj["value"])
[9]99    else:
[360]100        return createGeometryFromWFS(conf,obj["value"])
[9]101   
[106]102def outputResult(conf,obj,geom):
[465]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]]
[9]111    if obj["mimeType"]=="application/json":
[106]112        driverName = "GeoJSON"
113        extension = [ ".js" ]
[465]114        opts=None
[360]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" ]
[465]119        opts=None
[106]120    drv = osgeo.ogr.GetDriverByName( driverName )
[465]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
[106]125    lyr = ds.CreateLayer( "Result", None, osgeo.ogr.wkbUnknown )
[465]126    print >> sys.stderr,lyr
[106]127    i=0
[465]128    print >> sys.stderr,driverName
129    print >> sys.stderr,extension
[106]130    while i < len(geom):
[382]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 )
[465]141        try:
142            lyr.CreateFeature(geom[i])
143        except:
144            pass
[106]145        geom[i].Destroy()
146        i+=1
147    ds.Destroy()
[360]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):
[382]158    print >> sys.stderr, "Starting service ..."
[360]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
[382]178    return zoo.SERVICE_SUCCEEDED
[9]179
[465]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
[9]230def BoundaryPy(conf,inputs,outputs):
[257]231    geometry=extractInputs(conf,inputs["InputPolygon"])
[106]232    i=0
233    rgeometries=[]
234    while i < len(geometry):
[360]235        tmp=geometry[i].Clone()
236        resg=geometry[i].GetGeometryRef()
237        resg=resg.GetBoundary()
238        tmp.SetGeometryDirectly(resg)
239        rgeometries+=[tmp]
[106]240        geometry[i].Destroy()
241        i+=1
242    outputResult(conf,outputs["Result"],rgeometries)
[382]243    return zoo.SERVICE_SUCCEEDED
[9]244
245def CentroidPy(conf,inputs,outputs):
[257]246    geometry=extractInputs(conf,inputs["InputPolygon"])
[106]247    i=0
248    rgeometries=[]
249    while i < len(geometry):
[360]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]
[106]257        geometry[i].Destroy()
258        i+=1
259    outputResult(conf,outputs["Result"],rgeometries)
[388]260    return zoo.SERVICE_SUCCEEDED
[9]261
262def ConvexHullPy(conf,inputs,outputs):
[257]263    geometry=extractInputs(conf,inputs["InputPolygon"])
[106]264    i=0
265    rgeometries=[]
266    while i < len(geometry):
[360]267        tmp=geometry[i].Clone()
268        resg=geometry[i].GetGeometryRef().ConvexHull()
269        tmp.SetGeometryDirectly(resg)
270        rgeometries+=[tmp]
[106]271        geometry[i].Destroy()
272        i+=1
273    outputResult(conf,outputs["Result"],rgeometries)
[388]274    return zoo.SERVICE_SUCCEEDED
[9]275
[360]276
277
278def EnvelopePy(conf,inputs,outputs):
279    print >> sys.stderr, inputs
[9]280    try:
[107]281        bdist=float(inputs["BufferDistance"]["value"])
[9]282    except:
283        bdist=10
[257]284    geometry=extractInputs(conf,inputs["InputPolygon"])
[360]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"]
[9]288    return 3
289
290def UnionPy(conf,inputs,outputs):
[257]291    geometry1=extractInputs(conf,inputs["InputEntity1"])
292    geometry2=extractInputs(conf,inputs["InputEntity2"])
[106]293    rgeometries=[]
294    i=0
295    while i < len(geometry1):
296        j=0
297        while j < len(geometry2):
[389]298            tmp=geometry1[i].Clone()
299            resg=geometry2[j].GetGeometryRef()
[388]300            resg=resg.Union(geometry1[i].GetGeometryRef())
301            tmp.SetGeometryDirectly(resg)
302            if not(resg.IsEmpty()):
303                rgeometries+=[tmp]
[106]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)
[9]312    return 3
313
314def IntersectionPy(conf,inputs,outputs):
[360]315
[257]316    geometry1=extractInputs(conf,inputs["InputEntity1"])
317    geometry2=extractInputs(conf,inputs["InputEntity2"])
[360]318
[382]319    print >> sys.stderr,str(len(geometry1))+" "+str(len(geometry2))
320
[106]321    rgeometries=[]
[382]322    fids=[]
[106]323    i=0
324    while i < len(geometry1):
325        j=0
326        while j < len(geometry2):
[360]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)
[382]332            if resg is not None and not(resg.IsEmpty()) and fids.count(tmp.GetFID())==0:
[360]333                rgeometries+=[tmp]
[382]334                fids+=[tmp.GetFID()]
335            else:
336                tmp.Destroy()
[106]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)
[360]345    print >> sys.stderr,"/outputResult"
[9]346    return 3
347
348def DifferencePy(conf,inputs,outputs):
[257]349    geometry1=extractInputs(conf,inputs["InputEntity1"])
350    geometry2=extractInputs(conf,inputs["InputEntity2"])
[106]351    rgeometries=[]
352    i=0
353    while i < len(geometry1):
354        j=0
355        while j < len(geometry2):
[360]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]
[106]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)
[9]370    return 3
371
372def SymDifferencePy(conf,inputs,outputs):
[257]373    geometry1=extractInputs(conf,inputs["InputEntity1"])
374    geometry2=extractInputs(conf,inputs["InputEntity2"])
[106]375    rgeometries=[]
376    i=0
377    while i < len(geometry1):
378        j=0
379        while j < len(geometry2):
[360]380            tmp=geometry2[j].Clone()
381            resg=geometry1[i].GetGeometryRef()
382            resg=resg.SymmetricDifference(geometry2[i].GetGeometryRef())
383            tmp.SetGeometryDirectly(resg)
384            rgeometries+=[tmp]
[106]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)
[9]393    return 3
[360]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