Esempio n. 1
1
def main:
    map = mapscript.mapObj()
    map.name = 'Test Map'
    map.setSize(300, 300)
    map.setExtent(-180.0,-90.0,180.0,90.0)
    map.imagecolor.setRGB(80, 180, 80)
    map.units = mapscript.MS_DD

    layer = mapscript.layerObj(map)
    layer.name = "regioni"
    layer.type = mapscript.MS_LAYER_POLYGON
    layer.status = mapscript.MS_DEFAULT
    layer.data = os.getcwd() + '/../data/regioni'

    class1 = mapscript.classObj(layer)
    class1.name = "Regioni"
    style = mapscript.styleObj(class1)
    style.outlinecolor.setRGB(100, 100, 100)
    style.color.setRGB(200, 200, 200)
    extent = layer.getExtent()

    map.setExtent(extent.minx, extent.miny, extent.maxx, extent.maxy)
    mapimage = map.draw()

    mapimage.save(os.getcwd() + '/../images/mapscript_map.png')
Esempio n. 2
0
def copyLayerFile(conf, inputs, outputs):
    import mapscript
    import shutil
    if inputs.has_key("dsto"):
        m = mapscript.mapObj(conf["main"]["dataPath"] + "/dirs/" +
                             inputs["dsto"]["value"] + "/ds_ows.map")
    else:
        m = mapscript.mapObj(conf["main"]["dataPath"] +
                             "/georeferencer_maps/project_" +
                             inputs["layer"]["value"] + ".map")
    if inputs.keys().count("lfile") > 0 and inputs["lfile"]["value"] != "NULL":
        ofile = inputs["lfile"]["value"]
    else:
        if inputs.has_key("dsto"):
            ofile = m.getLayerByName(inputs["layer"]["value"]).data
        else:
            ofile = m.getLayer(0).data
    if inputs.keys().count(
            "target") > 0 and inputs["target"]["value"] != "NULL":
        shutil.copy2(ofile, inputs["target"]["value"])
    else:
        shutil.copy2(ofile, conf["main"]["dataPath"])
    if inputs.has_key("dsto"):
        outputs["Result"]["value"] = ofile.split("/")[len(ofile.split("/")) -
                                                      1]
    else:
        outputs["Result"]["value"] = zoo._("Layer copied")
    return zoo.SERVICE_SUCCEEDED
Esempio n. 3
0
 def open(self):
     self.filename = str(QtGui.QFileDialog.getOpenFileName(None, "Select one file to open", self.firstDir, "MapFile (*.map);;Text (*.txt);;All (*.*)"))
     self.map = mapscript.mapObj(self.filename)
     try:
         self.map = mapscript.mapObj(self.filename)
     except Exception:
         self.ui.statusbar.showMessage('Error: opening mapfile failed.')
     
     self.ui.statusbar.showMessage('Info: mapfile opened.')
     self.updateMapStructure()
Esempio n. 4
0
def application(env, start_response):
    for key in MAPSERV_ENV:
        if key in env:
            os.environ[key] = env[key]
        else:
            os.unsetenv(key)

    # Using a statically assigned mapfile:
    filename = os.path.join(settings_local['base_path'], 'test_mapfile.map')
    mapfile = mapscript.mapObj(filename)

    req = mapscript.OWSRequest()
    mapscript.msIO_installStdoutToBuffer()

    req.loadParamsFromURL(env['QUERY_STRING'])
    set_default_parameters(req)

    try:
        status = mapfile.OWSDispatch(req)
    except Exception as err:
        pass

    content_type = mapscript.msIO_stripStdoutBufferContentType()
    result = mapscript.msIO_getStdoutBufferBytes()
    start_response('200 OK', [('Content-type', content_type)])
    return [result]
Esempio n. 5
0
def mapserver(params,mapfile):
    """ Function implementing mapserver functionality.
    
    params: dictionary of query string of a mapserver GET request
    mapfile: path to mapfile
    
    returns: tuple with content type and response body
    """
    helper.dbg("creating map for: " + mapfile)
    request = mapscript.OWSRequest()
    #request.loadParams()
    for k in params:
        #helper.dbg( "%s : %s" % (k,params[k]))
        request.setParameter(k,params[k])
    # change the style INSPIRE:DEFAULT back to an empty string otherwise Mapserver will complain
    styles = request.getValueByName('STYLES')
    if (styles is not None and styles.count(default_style) > 0):
        styles = styles.replace(default_style, "")
        request.setParameter("STYLES", styles)
    style = request.getValueByName('STYLE')
    if style == default_style:
        request.setParameter("STYLE", "") 
            
    map = mapscript.mapObj( mapfile )
    mapscript.msIO_installStdoutToBuffer()
    map.OWSDispatch( request )
    content_type = mapscript.msIO_stripStdoutBufferContentType()
    content = mapscript.msIO_getStdoutBufferBytes()
    operation = request.getValueByName('REQUEST')
    version = request.getValueByName('VERSION')
    if (version == '1.3.0' or version is None) and operation.upper() == 'GETCAPABILITIES':
        content = altercapabilities(content, namespace, prefix, schemaLocation, language)
    #response = 'Content-type: %s\n%s' % (content_type,content)    
    return [content_type, content]
Esempio n. 6
0
def wms(request):
    import mapscript
    image = None
    for field in ['IMAGE', 'COVERAGE', 'image', 'coverage', 'id', 'ID']:
        if field in request.GET: image = request.GET[field] 
    try:
        image = int(image)
        obj = Map.objects.get(pk=image)
        filename = obj.warped
    except:
        filename = "%s" % image 
    filename = "%s/%s" % (settings.MAP_PATH, os.path.basename(filename))    
    ows = mapscript.OWSRequest()
    for k, v in request.GET.items():
        if k.lower() in ['image', 'coverage']: continue 
        ows.setParameter(k, v)
    ows.setParameter("LAYERS", "image")
    ows.setParameter("COVERAGE", "image")
    map = mapscript.mapObj('%s/wms.map' % settings.BASE_PATH)
    raster = mapscript.layerObj(map)
    raster.name = 'image'
    raster.type = mapscript.MS_LAYER_RASTER
    raster.data = filename 
    raster.status = mapscript.MS_DEFAULT
    raster.setProjection( "+init=epsg:4326" )
    raster.dump = mapscript.MS_TRUE
    raster.metadata.set("wcs_formats", "GEOTIFF JPEG2000")
    mapscript.msIO_installStdoutToBuffer()
    contents = map.OWSDispatch(ows)
    content_type = mapscript.msIO_stripStdoutBufferContentType()
    content = mapscript.msIO_getStdoutBufferBytes()
    return HttpResponse(content, content_type = content_type)
Esempio n. 7
0
    def __init__(self, request, **kwargs):
        """
        Method to setup map object based on the input parameters. The map
        object represents the mapserver mapfile and is used to render
        the wms requests.
        """
        # Store arguments
        self.request = request
        self.kwargs = kwargs

        # Create mapobject
        self.map_object = mapscript.mapObj()

        self.register_symbolset()
        self.register_layers()

        # Set map object properties
        self.map_object.setProjection('init=epsg:3857')
        self.map_object.setExtent(-180, -90, 180, 90)
        self.map_object.setSize(256, 256)
        self.map_object.setMetaData('wms_title', self.title)
        self.map_object.setMetaData('wms_srs', 'epsg:' + ' epsg:'.join(self.srs))
        self.map_object.setMetaData('wms_enable_request',
                               ' '.join(self.enable_requests))
        self.map_object.outputformat.transparent = mapscript.MS_ON

        # Set legend item size
        self.map_object.legend.keysizex = self.legend_size[0]
        self.map_object.legend.keysizey = self.legend_size[1]

        # Allow debugging
        if settings.DEBUG:
            self.map_object.debug = mapscript.MS_ON
Esempio n. 8
0
def dropLayerFile(conf, inputs, outputs):
    import mapscript
    import shutil
    m = mapscript.mapObj(conf["main"]["dataPath"] +
                         "/georeferencer_maps/project_" +
                         inputs["dso"]["value"] + ".map")
    if inputs.keys().count("layer") > 0:
        ofile = inputs["layer"]["value"]
    else:
        ofileName = m.getLayer(0).data.split("/")
        ofile = ofileName[len(ofileName) - 1]
    if type(ofile) is list:
        outputs["Result"]["value"] = ""
        for i in ofile:
            if outputs["Result"]["value"] != "":
                outputs["Result"]["value"] += ","
            outputs["Result"]["value"] += str(i)
            try:
                os.remove(i)
            except:
                continue
    else:
        outputs["Result"]["value"] += ofile
        os.remove(ofile)
    outputs["Result"]["value"] += zoo._(" deleted")
    return zoo.SERVICE_SUCCEEDED
Esempio n. 9
0
 def testSetExtent(self):
     """MapExtentTestCase.testSetExtent: test the setting of a mapObj's extent"""
     test_map = mapscript.mapObj(TESTMAPFILE)
     e = test_map.extent
     result = test_map.setExtent(e.minx, e.miny, e.maxx, e.maxy)
     self.assertAlmostEqual(test_map.scaledenom, 14.24445829)
     assert result == mapscript.MS_SUCCESS, result
Esempio n. 10
0
	def __init__(self,parent,id,size):
		wx.InitAllImageHandlers()
		self.size = size
		
		#setup map object
		self.map = mapscript.mapObj()
		self.map.width = size[0]
		self.map.height = size[1]
		#self.map.setProjection('proj=latlong,ellps=WGS84')
		self.map.setProjection('proj=lcc,ellps=GRS80') 
		# set the output format 
		self.map.setOutputFormat(mapscript.outputFormatObj('GD/PNG') )
		self.map.interlace = False #PIL can't handle interlaced PNGs
		topo=mapscript.layerObj(None) 
		topo.name="topo"  
		topo.type=mapscript.MS_LAYER_RASTER  
		topo.connectiontype=mapscript.MS_RASTER  
		topo.setProjection('proj=lcc,ellps=GRS80,datum=NAD83')
		topo.status = mapscript.MS_ON    
		topo.tileindex="maps/index.shp"
		topo.tileitem="location"
		layerNum = self.map.insertLayer(topo)
		
		#fn = self.lookupTopoFilename(0)
		#self.loadRaster(fn)
		BufferedCanvas.__init__(self,parent,id)
Esempio n. 11
0
def draw_map(name, save=0):

    # print("making map in thread %s" % (name))
    mo = mapscript.mapObj(TESTMAPFILE)
    im = mo.draw()
    if save:
        im.save('threadtest_%s.png' % (name))
Esempio n. 12
0
def saveGCPAsCSV(conf, inputs, outputs):
    if os.path.isfile(conf["main"]["dataPath"] + "/georeferencer_maps/" +
                      inputs["dso"]["value"] + "/" + inputs["file"]["value"] +
                      ".csv") and not (inputs.has_key("force")
                                       and inputs["force"]["value"] == "true"):
        conf["lenv"][
            "message"] = "Unable to create your GCP file, it seems that there is already a file with the same name for the project. To force the replacement of the current file by the one you are creating, please run with the  checked."
        return zoo.SERVICE_FAILED
    f = open(
        conf["main"]["dataPath"] + "/georeferencer_maps/" +
        inputs["dso"]["value"] + "/" + inputs["file"]["value"] + ".csv", "w")
    if inputs.keys().count("gcp") > 0:
        for i in range(0, len(inputs["gcp"]["value"])):
            print >> sys.stderr, inputs["gcp"]["value"][i]
            f.write(inputs["gcp"]["value"][i].replace(",", ";") + "\n")
    f.close()
    m = mapscript.mapObj(conf["main"]["dataPath"] +
                         "/georeferencer_maps/project_" +
                         inputs["dso"]["value"] + ".map")

    if m.web.metadata.get(
            "mmGCPCSV") is not None and m.web.metadata.get("mmGCPCSV") != "":
        tmp = m.web.metadata.get("mmGCPCSV")
        if tmp.count(inputs["file"]["value"]) == 0:
            m.web.metadata.set("mmGCPCSV", tmp + "," + inputs["file"]["value"])
            conf["senv"]["mmGCPCSV"] = tmp + "," + inputs["file"]["value"]
    else:
        m.web.metadata.set("mmGCPCSV", inputs["file"]["value"])
        conf["senv"]["mmGCPCSV"] = inputs["file"]["value"]

    m.save(conf["main"]["dataPath"] + "/georeferencer_maps/project_" +
           inputs["dso"]["value"] + ".map")
    outputs["Result"]["value"] = zoo._("CSV file saved.")
    return zoo.SERVICE_SUCCEEDED
Esempio n. 13
0
def draw_map_wms(name, save=0):

    # print("making map in thread %s" % (name))
    mo = mapscript.mapObj(TESTMAPFILE)
    # WFS layer
    lo = mapscript.layerObj()
    lo.name = 'jpl_wms'
    lo.setProjection('+init=epsg:4326')
    lo.connectiontype = mapscript.MS_WMS
    lo.connection = 'http://vmap0.tiles.osgeo.org/wms/vmap0?'
    lo.metadata.set('wms_service', 'WMS')
    lo.metadata.set('wms_server_version', '1.1.1')
    lo.metadata.set('wms_name', 'basic')
    lo.metadata.set('wms_style', 'visual')
    lo.metadata.set('wms_format', 'image/jpeg')
    lo.type = mapscript.MS_LAYER_RASTER
    lo.status = mapscript.MS_DEFAULT
    lo.debug = mapscript.MS_ON
    mo.insertLayer(lo)

    if not mo.web.imagepath:
        mo.web.imagepath = os.environ.get('TEMP', None) or INCOMING
    mo.debug = mapscript.MS_ON
    mo.selectOutputFormat('image/jpeg')
    im = mo.draw()
    if save:
        im.save('threadtest_wms_%s.jpg' % (name))
Esempio n. 14
0
    def update_latest_mapfile(self, mapfile, shapePath, geotifRelativePath):
        '''
        Update the 'latest' mapfile.

        Inputs:

            mapfile - Full path to the mapfile.

            shapePath - Value to attribute to the mapfile's 'shapepath' 
                variable.

            geotifRelativePath - Relative path to the geotiff. This path 
                is relative to the shapePath argument.
        '''

        
        mapObj = mapscript.mapObj(mapfile)
        mapObj.shapepath = shapePath
        mapWMSMetadata = mapObj.web.metadata
        mapWMSMetadata.set('wms_onlineresource', 
                           'http://%s/cgi-bin/mapserv?map=%s&' \
                            % (self.host.host, mapfile))
        layer = mapObj.getLayerByName(self.product.short_name)
        layer.data = geotifRelativePath
        layerAbstract = '%s product generated for the %s timeslot.' % \
                        (self.product.short_name, 
                         self.timeslot.strftime('%Y-%m-%d %H:%M'))
        layer.metadata.set('wms_abstract', layerAbstract)
        mapObj.save(mapfile)
        return mapfile
Esempio n. 15
0
def main(map_file):

    map = mapscript.mapObj(map_file)
    map.web.metadata.set("ows_onlineresource", "http://dummy.org/")
    ows_req = mapscript.OWSRequest()

    ows_req.type = mapscript.MS_GET_REQUEST

    ows_req.setParameter("SERVICE", "WMS")
    ows_req.setParameter("VERSION", "1.1.0")
    ows_req.setParameter("REQUEST", "GetCapabilities")

    mapscript.msIO_installStdoutToBuffer()
    dispatch_status = map.OWSDispatch(ows_req)

    if dispatch_status != mapscript.MS_SUCCESS:
        print("An error occurred")

    content_type = mapscript.msIO_stripStdoutBufferContentType()
    mapscript.msIO_stripStdoutBufferContentHeaders()
    result = mapscript.msIO_getStdoutBufferBytes()

    # [('Content-Type', 'application/vnd.ogc.wms_xml; charset=UTF-8'), ('Content-Length', '11385')]
    response_headers = [('Content-Type', content_type),
                        ('Content-Length', str(len(result)))]

    assert int(response_headers[1][1]) > 0

    dom = xml.dom.minidom.parseString(result)
    print(dom.toprettyxml(indent="", newl=""))
Esempio n. 16
0
 def testMapWithDefaultMap(self):
     """ReferenceCountingTestCase.testTestMap: test map constructor with default map file"""
     test_map = mapscript.mapObj(TESTMAPFILE)
     assert test_map.__class__.__name__ == "mapObj"
     assert test_map.thisown == 1
     assert test_map.refcount == 1
     assert test_map.getLayer(0).refcount == 2
Esempio n. 17
0
def wms(request):
    import mapscript
    image = None
    for field in ['IMAGE', 'COVERAGE', 'image', 'coverage', 'id', 'ID']:
        if field in request.GET: image = request.GET[field]
    try:
        image = int(image)
        obj = Map.objects.get(pk=image)
        filename = obj.warped
    except:
        filename = "%s" % image
    filename = "%s/%s" % (settings.MAP_PATH, os.path.basename(filename))
    ows = mapscript.OWSRequest()
    for k, v in request.GET.items():
        if k.lower() in ['image', 'coverage']: continue
        ows.setParameter(k, v)
    ows.setParameter("LAYERS", "image")
    ows.setParameter("COVERAGE", "image")
    map = mapscript.mapObj('%s/wms.map' % settings.BASE_PATH)
    raster = mapscript.layerObj(map)
    raster.name = 'image'
    raster.type = mapscript.MS_LAYER_RASTER
    raster.data = filename
    raster.status = mapscript.MS_DEFAULT
    raster.setProjection("+init=epsg:4326")
    raster.dump = mapscript.MS_TRUE
    mapscript.msIO_installStdoutToBuffer()
    contents = map.OWSDispatch(ows)
    content_type = mapscript.msIO_stripStdoutBufferContentType()
    content = mapscript.msIO_getStdoutBufferBytes()
    return HttpResponse(content, content_type=content_type)
Esempio n. 18
0
def get_style_from_mapserver(request):
    if request.method == 'GET':
        layerName = request.GET.get('layer_name')
        map = mapscript.mapObj(openthingis.settings.MAPSERVER_MAPFILE)
        layer = map.getLayerByName(layerName)
        sld = layer.generateSLD()
        return HttpResponse(sld, content_type='application/xml')
Esempio n. 19
0
 def testMapWithDefaultMap(self):
     """ReferenceCountingTestCase.testTestMap: test map constructor with default map file"""
     test_map = mapscript.mapObj(TESTMAPFILE)
     assert test_map.__class__.__name__ == "mapObj"
     assert test_map.thisown == 1
     assert test_map.refcount == 1
     assert test_map.getLayer(0).refcount == 2
    def getLayers(self):
        mapObj = mapscript.mapObj(self.mapfile)
        layers = []
        for i in range(0, mapObj.numlayers):
            layers.append(mapObj.getLayer(i).name)

        return layers
Esempio n. 21
0
def saveGeorefProject(conf,inputs,outputs):
    import mmsession
    import mapfile.service as ms

    mapfile=conf["main"]["dataPath"]+"/georeferencer_maps/project_"+inputs["map"]["value"]+".map"
    m = mapscript.mapObj(mapfile)
    conf["senv"]["mmGeoDST"]=m.web.metadata.get("mmGeoDST")
    conf["senv"]["mmGeoDSO"]=m.web.metadata.get("mmGeoDSO")
    if inputs.has_key("dso") and inputs["dso"]["value"]=="NULL":
        inputs["dso"]["value"]=m.getLayer(0).name
    conf["senv"]["mmGeoMap"]=inputs["dso"]["value"]

    import shutil
    ofile=m.getLayer(0).data
    shutil.copy2(ofile,conf["main"]["tmpPath"])
    conf["senv"]["mmGeoImg"]=ofile.split('/')[len(ofile.split('/'))-1]

    mmsession.save(conf)
    try:
	    os.mkdir(conf["main"]["dataPath"]+"/georeferencer_maps/"+inputs["dso"]["value"])
    except:
	    pass

    if not(os.path.isfile(conf["main"]["dataPath"]+"/georeferencer_maps/project_"+inputs["dso"]["value"]+".map")) or (inputs.has_key("force") and inputs["force"]["value"]=="true"):
	try:
	    import glob
	    for name in glob.glob(conf["main"]["dataPath"]+"/georeferencer_maps/"+inputs["map"]["value"]+"/*.csv"):
                shutil.copy2(name,conf["main"]["dataPath"]+"/georeferencer_maps/"+inputs["dso"]["value"])
	except Exception,e:
	    print >> sys.stderr,e
	    pass
        m.save(conf["main"]["dataPath"]+"/georeferencer_maps/project_"+inputs["dso"]["value"]+".map")
Esempio n. 22
0
 def __init__(self, rev, defn):
     self.instance = mapscript.mapObj(os.path.expanduser('/vagrant/template.map'))
     self.instance.imagetype = 'png'
     self.instance.setProjection('init=epsg:%s' % (EAlGIS().get_setting('map_srid')))
     self.rev = rev
     self.layers = []
     self.layers.append(self.make_base_layer(defn))
 def getMapObj(self):
   mapObj = None
   try:
     mapObj = mapscript.mapObj(self.mapfile)
   except mapscript.MapServerError as err:
     self.messageTextEdit.append( str(err) )
   return mapObj
Esempio n. 24
0
def query_raster_MS(mapfile_path, rasters):
    #import mapscript #dopo aggiornamento python se carico mapscript dopo le gdal via web ritorna un errore
    mapfile2 = mapfile_path
    m2 = mapscript.mapObj(mapfile2)
    p2 = mapscript.pointObj(x, y)
    #raster = rasters[0]
    for raster in rasters:
        layer2 = m2.getLayerByName(raster)
        print layer2.name
        layer2.queryByPoint(
            m2, p2, mapscript.MS_MULTIPLE, 500.0
        )  ##tolleranza in unita mappa. Se <=0 si usa la tolleranza (in pixel) definita nel file MAP
        results2 = layer2.getResults()
        if results2:
            for i in range(results2.numresults):
                result2 = results2.getResult(i)
        layer2.open()
        s2 = layer2.getShape(result2)
        if results2:
            for i in range(results2.numresults):
                result2 = results2.getResult(i)
                s2 = layer2.getShape(result2)
                for j in range(layer2.numitems):
                    print '%s: %s<br/>' % (layer2.getItem(j), s2.getValue(j))

        layer2.close()
Esempio n. 25
0
    def _render(self, inputFile, outputFile):
        mapfile = 'MapRenderer/static.map'
        # print "Input From: " + inputFile
        # print "Output to: " + outputFile

        #check output directory exists
        if not os.path.exists(self.outputPath):
            os.makedirs(self.outputPath)

        try:
            m = mapscript.mapObj(mapfile)
            m.setSize(1542,2523)

            #set layer data file
            layer = m.getLayerByName("dispersal")
            layer.data = inputFile

            m.draw().save(outputFile)
        except mapscript.MapServerError as e:
            print e
            pass
            #log.critical(e)
        except IOError as e:
            print e
            pass
Esempio n. 26
0
    def build(self):
        """
        Build a mapObj
        """

        uri = reverse("wms_endpoint")
        m = mapscript.mapObj()
        m.name = self.name
        m.setProjection("init=epsg:{}".format(self.projection))
        m.shapepath = ""
        m.units = self.units
        m.setMetaData("ows_title", self.name)
        m.setMetaData("ows_onlineresource",
                      "http://{}{}".format(settings.HOST_NAME, uri))
        m.setMetaData("wms_srs", "EPSG:{}".format(self.projection))
        m.setMetaData("wms_enable_request", self.ows_enable_request)
        m.setMetaData("wms_encoding", "utf-8")
        m.imagetype = "png"
        m.extent = self.extent.build()
        m.setSize(*self.MAP_SIZE)
        if self.image_color is not None:
            m.imageColor = self.image_color.build()
        else:
            m.imageColor = mapscript.colorObj(255, 255, 255)
        for layer in self.layers.all():
            m.insertLayer(layer.build())
        return m
Esempio n. 27
0
def SecureAccess(conf,inputs,outputs):
    global myCookies
    mapfile=conf["main"]["dataPath"]+"/public_maps/project_"+inputs["server"]["value"]+".map"
    try:
    	myMap=mapscript.mapObj(mapfile)
    except:
        conf["lenv"]["message"]=zoo._("Unable to find any project with this name!")
	return zoo.SERVICE_FAILED
    c = auth.getCon(conf)
    prefix=auth.getPrefix(conf)
    if not(validToken(c,prefix,inputs["token"]["value"])):
        conf["lenv"]["message"]=zoo._("Unable to validate your token!")
        return zoo.SERVICE_FAILED
    if not(validIp(conf,c,prefix,inputs["ip"]["value"],0,[inputs["server"]["value"]])):
        conf["lenv"]["message"]=zoo._("You are not allowed to access the ressource using this ip address!")
        return zoo.SERVICE_FAILED
    q=None
    if inputs["Query"]["mimeType"]=="application/json":
        import json
        q=json.loads(inputs["Query"]["value"])
    myAutorizedGroups=myMap.web.metadata.get('mm_access_groups').split(',')
    if myAutorizedGroups.count('public')==0 and not(q is None or q["request"].upper()=="GETCAPABILITIES" or q["request"].upper()=="GETLEGENDGRAPHIC") and not(tryIdentifyUser(conf,inputs["user"]["value"],inputs["password"]["value"])):
        conf["lenv"]["message"]=zoo._("You are not allowed to access the ressource using this user / password!")
        conf["lenv"]["status_code"]="401 Unauthorized"
        print >> sys.stderr,conf["lenv"]
        return zoo.SERVICE_FAILED
    if conf.keys().count("senv")==0:
        conf["senv"]={"group": getGroupFromToken(c,prefix,inputs["token"]["value"])}
    else:
        print >> sys.stderr,conf["senv"]
    try:
    	myCurrentGroups=conf["senv"]["group"].split(',')
    except Exception,e:
    	myCurrentGroups=[]
Esempio n. 28
0
    def update_latest_mapfile(self, mapfile, shapePath, geotifRelativePath):
        '''
        Update the 'latest' mapfile.

        Inputs:

            mapfile - Full path to the mapfile.

            shapePath - Value to attribute to the mapfile's 'shapepath' 
                variable.

            geotifRelativePath - Relative path to the geotiff. This path 
                is relative to the shapePath argument.
        '''

        mapObj = mapscript.mapObj(mapfile)
        mapObj.shapepath = shapePath
        mapWMSMetadata = mapObj.web.metadata
        mapWMSMetadata.set('wms_onlineresource',
                           'http://%s/cgi-bin/mapserv?map=%s&' \
                            % (self.host.host, mapfile))
        layer = mapObj.getLayerByName(self.product.short_name)
        layer.data = geotifRelativePath
        layerAbstract = '%s product generated for the %s timeslot.' % \
                        (self.product.short_name,
                         self.timeslot.strftime('%Y-%m-%d %H:%M'))
        layer.metadata.set('wms_abstract', layerAbstract)
        mapObj.save(mapfile)
        return mapfile
Esempio n. 29
0
def main(map_file):

    map = mapscript.mapObj(map_file)
    map.setMetaData("ows_onlineresource", "http://dummy.org/")
    ows_req = mapscript.OWSRequest()

    ows_req.type = mapscript.MS_GET_REQUEST

    ows_req.setParameter("SERVICE", "WMS")
    ows_req.setParameter("VERSION", "1.1.0")
    ows_req.setParameter("REQUEST", "GetCapabilities")

    mapscript.msIO_installStdoutToBuffer()
    dispatch_status = map.OWSDispatch(ows_req)

    if dispatch_status != mapscript.MS_SUCCESS:
        print("An error occurred")

    content_type = mapscript.msIO_stripStdoutBufferContentType()
    mapscript.msIO_stripStdoutBufferContentHeaders()
    result = mapscript.msIO_getStdoutBufferBytes()

    # [('Content-Type', 'application/vnd.ogc.wms_xml; charset=UTF-8'), ('Content-Length', '11385')]
    response_headers = [('Content-Type', content_type),
                        ('Content-Length', str(len(result)))]

    assert int(response_headers[1][1]) > 0

    dom = xml.dom.minidom.parseString(result)
    print(dom.toprettyxml(indent="", newl=""))
Esempio n. 30
0
 def testSetExtent(self):
     """MapExtentTestCase.testSetExtent: test the setting of a mapObj's extent"""
     test_map = mapscript.mapObj(TESTMAPFILE)
     e = test_map.extent
     result = test_map.setExtent(e.minx, e.miny, e.maxx, e.maxy)
     self.assertAlmostEqual(test_map.scaledenom, 14.24445829)
     assert result == mapscript.MS_SUCCESS, result
Esempio n. 31
0
def bug_673():

    
    if string.find(mapscript.msGetVersion(),'SUPPORTS=PROJ') == -1:
        return 'skip'

    map = mapscript.mapObj('../misc/ogr_direct.map')

    map.setProjection('+proj=utm +zone=11 +datum=WGS84')

    layer = map.getLayer(0)

    # Draw map without reprojection.

    layer.setProjection('+proj=utm +zone=11 +datum=WGS84')
    img1 = map.draw()

    # Draw map with reprojection

    map.setProjection('+proj=latlong +datum=WGS84')
    map.setExtent(-117.25,43.02,-117.21,43.05)

    img2 = map.draw()
    try:
        os.mkdir('result')
    except:
        pass
    img2.save( 'result/bug673.png' )

    # Verify we got the image we expected ... at least hopefully we didn't
    # get all white which would indicate the bug is back.

    return pmstestlib.compare_and_report( 'bug673.png' )
Esempio n. 32
0
def bug_673():

    if string.find(mapscript.msGetVersion(), 'SUPPORTS=PROJ') == -1:
        return 'skip'

    map = mapscript.mapObj('../misc/ogr_direct.map')

    map.setProjection('+proj=utm +zone=11 +datum=WGS84')

    layer = map.getLayer(0)

    # Draw map without reprojection.

    layer.setProjection('+proj=utm +zone=11 +datum=WGS84')
    img1 = map.draw()

    # Draw map with reprojection

    map.setProjection('+proj=latlong +datum=WGS84')
    map.setExtent(-117.25, 43.02, -117.21, 43.05)

    img2 = map.draw()
    try:
        os.mkdir('result')
    except:
        pass
    img2.save('result/bug673.png')

    # Verify we got the image we expected ... at least hopefully we didn't
    # get all white which would indicate the bug is back.

    return pmstestlib.compare_and_report('bug673.png')
Esempio n. 33
0
def saveGeoreferencedProject(conf, inputs, outputs):
    import mmsession
    import mapfile.service as ms

    mapfile = inputs["dst"]["value"] + "ds_ows.map"
    m = mapscript.mapObj(mapfile)
    ms.removeAllLayers(m, inputs["dso"]["value"])

    m.web.metadata.set("mmGeoDST", inputs["dst"]["value"])
    conf["senv"]["mmGeoDST"] = inputs["dst"]["value"]

    m.web.metadata.set("mmGeoDSO", inputs["dso"]["value"])
    conf["senv"]["mmGeoDSO"] = inputs["dso"]["value"]
    conf["senv"]["mmGeoMap"] = inputs["dso"]["value"]

    import shutil
    ofile = m.getLayer(0).data
    shutil.copy2(ofile, conf["main"]["tmpPath"])
    conf["senv"]["mmGeoImg"] = ofile.split('/')[len(ofile.split('/')) - 1]

    if inputs.keys().count("gcpfile") > 0:
        m.web.metadata.set("mmGeoGCPFile", inputs["gcpfile"]["value"])
        conf["senv"]["mmGeoGCPFile"] = inputs["gcpfile"]["value"]
    if inputs.keys().count("size") > 0:
        m.web.metadata.set("mmGeoSize", inputs["size"]["value"])
        conf["senv"]["mmGeoSize"] = inputs["size"]["value"]
    mmsession.save(conf)
    if not (os.path.isfile(conf["main"]["dataPath"] +
                           "/georeferencer_maps/project_" +
                           inputs["dso"]["value"] + ".map")):
        m.save(conf["main"]["dataPath"] + "/georeferencer_maps/project_" +
               inputs["dso"]["value"] + ".map")
    outputs["Result"]["value"] = zoo._("Georeference Project saved")
    return zoo.SERVICE_SUCCEEDED
Esempio n. 34
0
def saveGeoreferencedProject(conf,inputs,outputs):
    import mmsession
    import mapfile.service as ms

    mapfile=inputs["dst"]["value"]+"ds_ows.map"
    m = mapscript.mapObj(mapfile)
    ms.removeAllLayers(m,inputs["dso"]["value"])

    m.web.metadata.set("mmGeoDST",inputs["dst"]["value"])
    conf["senv"]["mmGeoDST"]=inputs["dst"]["value"]
    
    m.web.metadata.set("mmGeoDSO",inputs["dso"]["value"])
    conf["senv"]["mmGeoDSO"]=inputs["dso"]["value"]
    conf["senv"]["mmGeoMap"]=inputs["dso"]["value"]

    import shutil
    ofile=m.getLayer(0).data
    shutil.copy2(ofile,conf["main"]["tmpPath"])
    conf["senv"]["mmGeoImg"]=ofile.split('/')[len(ofile.split('/'))-1]

    if inputs.keys().count("gcpfile")>0:
	    m.web.metadata.set("mmGeoGCPFile",inputs["gcpfile"]["value"])
	    conf["senv"]["mmGeoGCPFile"]=inputs["gcpfile"]["value"]
    mmsession.save(conf)
    if not(os.path.isfile(conf["main"]["dataPath"]+"/georeferencer_maps/project_"+inputs["dso"]["value"]+".map")):
        m.save(conf["main"]["dataPath"]+"/georeferencer_maps/project_"+inputs["dso"]["value"]+".map")
    outputs["Result"]["value"]=zoo._("Georeference Project saved")
    return zoo.SERVICE_SUCCEEDED
Esempio n. 35
0
    def __init__(self,
                 path,
                 create=False,
                 needed=False,
                 fontset=None,
                 config=None):
        self.path = path
        self.filename = os.path.basename(self.path)
        self.name = os.path.splitext(self.filename)[0]

        if os.path.exists(self.path):
            if create and not needed:
                raise KeyExists(self.filename)
            create = False
        elif needed:
            create = True

        if create:
            self.ms = mapscript.mapObj()

            # and adding some default values...
            self.ms.name = self.name
            self.ms.setProjection(config.get("projection", "+init=epsg:4326"))
            self.ms.setExtent(*config.get("extent", [-180, -90, 180, 90]))
            self.ms.units = tools.get_units(config.get("units", "DD"))
            self.ms.setSize(1, 1)

            for outputformat in [
                    v for k in OUTPUTFORMAT.keys()
                    for v in list(OUTPUTFORMAT[k].values())
            ]:
                self.ms.appendOutputFormat(outputformat)

            for k, v in config.get('metadata', {}).iteritems():
                self.set_metadata(k, v)

            for ows in ("ows", "wms", "wfs", "wcs"):
                self.set_metadata("%s_enable_request" % ows, "*")

            if 'onlineresource' in config:
                onlineresource = urlparse.urljoin(config.get('onlineresource'),
                                                  self.ms.name)
                self.set_metadata('ows_onlineresource', onlineresource)

            fontset and self.ms.setFontSet(fontset)
        else:
            self.ms = mapscript.mapObj(self.path)
Esempio n. 36
0
    def create_mapfile(self, geotifRelativePath, geotifCommonDir, outputPath,
                       template):
        '''
        Create a new mapfile for UMN Mapserver based on the template.

        Inputs:

            geotifRelativePath - The relative path to the geotif file.
                This path is relative to 'geotifCommonDir'.

            geotifCommonDir - A common directory that is parent to all the
                generated geotiffs, so that mapserver can find the
                files that belong to different layers.

            outputPath - The full path of the new mapfile.

            template - The full path to the template mapfile to use.
        '''

        templateMap = mapscript.mapObj(template)
        # look for the file, it may already be there
        if self.host.is_file(outputPath):
            mapfile = mapscript.mapObj(outputPath)
        else:
            mapfile = templateMap.clone()
        mapfile.shapepath = geotifCommonDir
        mapfile.name = 'quicklooks'
        mapWMSMetadata = mapfile.web.metadata
        mapWMSMetadata.set('wms_title', 'quicklooks')
        mapWMSMetadata.set('wms_onlineresource',
                        'http://%s/cgi-bin/mapserv?map=%s&' \
                        % (self.host.host, outputPath))
        layer = mapfile.getLayerByName(self.product.short_name)
        if layer is None:
            layerIndex = mapfile.insertLayer(
                templateMap.getLayerByName(self.product.short_name))
            layer = mapfile.getLayer(layerIndex)
        layer.data = geotifRelativePath
        layer.status = mapscript.MS_ON
        layerWMSMetadata = layer.metadata
        layerWMSMetadata.set('wms_title', self.product.short_name)
        for i in range(mapfile.numlayers):
            otherLayer = mapfile.getLayer(i)
            if otherLayer.name != layer.name:
                otherLayer.status = mapscript.MS_OFF
        mapfile.save(outputPath)
        return outputPath
Esempio n. 37
0
    def test(self):

        test_map = mapscript.mapObj(TESTMAPFILE)
        result = test_map.generateSLD()
        assert result.startswith('<StyledLayerDescriptor version="1.0.0"'), result

        result = test_map.generateSLD("1.1.0")
        assert result.startswith('<StyledLayerDescriptor version="1.1.0"'), result
Esempio n. 38
0
    def create_mapfile(self, geotifRelativePath, geotifCommonDir, outputPath, template):
        '''
        Create a new mapfile for UMN Mapserver based on the template.

        Inputs:

            geotifRelativePath - The relative path to the geotif file.
                This path is relative to 'geotifCommonDir'.

            geotifCommonDir - A common directory that is parent to all the
                generated geotiffs, so that mapserver can find the
                files that belong to different layers.

            outputPath - The full path of the new mapfile.

            template - The full path to the template mapfile to use.
        '''

        templateMap = mapscript.mapObj(template)
        # look for the file, it may already be there
        if self.host.is_file(outputPath):
            mapfile = mapscript.mapObj(outputPath)
        else:
            mapfile = templateMap.clone()
        mapfile.shapepath = geotifCommonDir
        mapfile.name = 'quicklooks'
        mapWMSMetadata = mapfile.web.metadata
        mapWMSMetadata.set('wms_title', 'quicklooks')
        mapWMSMetadata.set('wms_onlineresource', 
                        'http://%s/cgi-bin/mapserv?map=%s&' \
                        % (self.host.host, outputPath))
        layer = mapfile.getLayerByName(self.product.short_name)
        if layer is None:
            layerIndex = mapfile.insertLayer(templateMap.getLayerByName(
                                             self.product.short_name))
            layer = mapfile.getLayer(layerIndex)
        layer.data = geotifRelativePath
        layer.status = mapscript.MS_ON
        layerWMSMetadata = layer.metadata
        layerWMSMetadata.set('wms_title', self.product.short_name)
        for i in range(mapfile.numlayers):
            otherLayer = mapfile.getLayer(i)
            if otherLayer.name != layer.name:
                otherLayer.status = mapscript.MS_OFF
        mapfile.save(outputPath)
        return outputPath
Esempio n. 39
0
def removeDS(conf,inputs,outputs):
    #have to check before
    import datastores.directories.service as dirs
    import mapscript
    mj=mapscript.mapObj(inputs["dst"]["value"]+"/ds_ows.map")
    mj.removeLayer(mj.getLayerByName(inputs["dso"]["value"]).index)
    mj.save(conf["main"]["dataPath"]+"/ds_ows.map")
    return dirs.removeDS(conf,inputs,outputs)
Esempio n. 40
0
def loadMap(mapfile):
    """Loads mapfile"""
    try:
        map = mapscript.mapObj(mapfile)
        return map
    except Exception, e:
        print (e)
        sys.exit()
Esempio n. 41
0
def removeDS(conf, inputs, outputs):
    #have to check before
    import datastores.directories.service as dirs
    import mapscript
    mj = mapscript.mapObj(inputs["dst"]["value"] + "/ds_ows.map")
    mj.removeLayer(mj.getLayerByName(inputs["dso"]["value"]).index)
    mj.save(conf["main"]["dataPath"] + "/ds_ows.map")
    return dirs.removeDS(conf, inputs, outputs)
Esempio n. 42
0
def draw_map_to_file(map_id, output_file):
    print 'mapserver.draw_map_to_file(%s, %s)' % (map_id, output_file)
    try:
        mapa = mapscript.mapObj('%s.map' % os.path.join(settings.MAPAS_PATH, map_id))
        mapa.draw().save(output_file)
        return True
    except Exception:
        return False
Esempio n. 43
0
 def setUp(self):
     self.mapobj1 = mapscript.mapObj(TESTMAPFILE)
     # Change the extent for purposes of zoom testing
     rect = mapscript.rectObj()
     rect.minx, rect.miny, rect.maxx, rect.maxy = (-50.0, -50.0, 50.0, 50.0)
     self.mapobj1.extent = rect
     # Change height/width as well
     self.mapobj1.width, self.mapobj1.height = (100, 100)
Esempio n. 44
0
 def setUp(self):
     self.mapobj1 = mapscript.mapObj(TESTMAPFILE)
     # Change the extent for purposes of zoom testing
     rect = mapscript.rectObj()
     rect.minx, rect.miny, rect.maxx, rect.maxy = (-50.0, -50.0, 50.0, 50.0)
     self.mapobj1.extent = rect
     # Change height/width as well
     self.mapobj1.width, self.mapobj1.height = (100, 100)
Esempio n. 45
0
 def testExternalClassification(self):
     mo = mapscript.mapObj()
     mo.setSize(400, 400)
     mo.setExtent(-2.5, -2.5, 2.5, 2.5)
     mo.selectOutputFormat('image/png')
     mo.insertLayer(self.ilayer)
     im = mo.draw()
     im.save('testExternalClassification.png')
Esempio n. 46
0
 def testReBindingExtent(self):
     """test the rebinding of a map's extent"""
     test_map = mapscript.mapObj(TESTMAPFILE)
     rect1 = mapscript.rectObj(-10.0, -10.0, 10.0, 10.0)
     rect2 = mapscript.rectObj(-10.0, -10.0, 10.0, 10.0)
     test_map.extent = rect1
     assert repr(test_map.extent) != repr(rect1), (test_map.extent, rect1)
     del rect1
     self.assertRectsEqual(test_map.extent, rect2)
Esempio n. 47
0
def trigger_exception(name):

    # print("triggering exception in thread %s" % (name))
    mo = mapscript.mapObj(TESTMAPFILE)
    try:
        mo.setExtent(1, 50, -1, 51)
        raise Exception("We expected a MapServer exception")
    except mapscript.MapServerError:
        pass
Esempio n. 48
0
 def __init__(self, rev, defn):
     self.instance = mapscript.mapObj(
         os.path.expanduser('/app/backend/mapserver/template.map'))
     self.instance.imagetype = 'png'
     self.instance.setProjection('init=epsg:%s' %
                                 (EAlGIS().get_setting('map_srid')))
     self.rev = rev
     self.layers = []
     self.layers.append(self.make_base_layer(defn))
Esempio n. 49
0
def test_mapfile():
	"""Test mapfile syntax, print result and exit script."""

	try:
		print 'Checking mapfile.'
		m = mapscript.mapObj(_mapfile())
		print 'OK, %s layers found.' % m.numlayers
	except Exception, err:
		print 'ERROR: %s' % err
Esempio n. 50
0
def test_mapfile():
    """Test mapfile syntax, print result and exit script."""

    try:
        print 'Checking mapfile.'
        m = mapscript.mapObj(_mapfile())
        print 'OK, %s layers found.' % m.numlayers
    except Exception, err:
        print 'ERROR: %s' % err
Esempio n. 51
0
 def get_map(self, layers, southwest=None, northeast=None, scans=None,
             srs=Units.EPSG_900913, height=300, width=300, format=OutputFormat.PNG,
             opacity=100, extra_layers=None, show_north_arrow=False, **kwargs):
     """
     Renders a MapServer-generated map, in the user-specified format, according
     to a set of optional key word arguments.
     """
     if layers is not None:
         self.layers.extend(layers)
     msmap = mapscript.mapObj(settings.MAP_FILE)
     
     #draw base layers:
     if extra_layers is not None:
         self.layers.extend(extra_layers)
     for n in self.layers:
         l = msmap.getLayerByName(n.provider_id) #WMS_Overlay Object
         l.status = 1
         l.opacity = opacity
     
     #set map image width and height:
     msmap.set_width(width)
     msmap.set_height(height)
     
     #turn on scale bar:
     msmap.scalebar.status = 3       # 3=code for 'embed'
     
     if show_north_arrow:
         self._add_north_arrow(msmap, height)
     
     #scans = [1]
     if scans is not None and len(scans) > 0:
         self._render_scans(msmap, scans, srs)
         
     #update map extents, if specified:
     if southwest is not None and northeast is not None:
         if southwest.srs != srs: southwest.transform(srs)
         if northeast.srs != srs: northeast.transform(srs)
         #west, south, east, north:
         msmap.setExtent(southwest.x, southwest.y, northeast.x, northeast.y)
         msmap.setProjection('init=epsg:%s' % (srs))  
     
     #render map image:
     map_image = msmap.draw()
     
     #convert from MapScript Image to PIL Image (for further manipulation):
     bytes = StringIO.StringIO(map_image.getBytes())
     new_image = Image.open(bytes)#.convert('RGBA')
     return_image = Image.new(mode='RGBA',size=(width,height),color=(255,255,255,0))
     return_image.paste(new_image, (0, 0), new_image)
     
     #return object    
     if format == OutputFormat.HTTP_RESPONSE:
         response = HttpResponse(mimetype="image/png")
         return_image.save(response, "PNG")
         return response
     elif format == OutputFormat.PNG:
         return return_image
Esempio n. 52
0
 def get_map(self, layers, southwest=None, northeast=None, scans=None,
             srs=Units.EPSG_900913, height=300, width=300, format=OutputFormat.PNG,
             opacity=100, extra_layers=None, show_north_arrow=False, **kwargs):
     """
     Renders a MapServer-generated map, in the user-specified format, according
     to a set of optional key word arguments.
     """
     self.layers.extend(layers)
     msmap = mapscript.mapObj(settings.MAP_FILE)
     
     #draw base layers:
     if extra_layers is not None:
         self.layers.extend(extra_layers)
     for n in self.layers:
         l = msmap.getLayerByName(n.provider_id) #WMS_Overlay Object
         l.status = 1
         l.opacity = opacity
     
     #set map image width and height:
     msmap.set_width(width)
     msmap.set_height(height)
     
     #turn on scale bar:
     msmap.scalebar.status = 3       # 3=code for 'embed'
     
     if show_north_arrow:
         self._add_north_arrow(msmap, height)
     
     #scans = [1]
     if scans is not None and len(scans) > 0:
         self._render_scans(msmap, scans, srs)
         
     #update map extents, if specified:
     if southwest is not None and northeast is not None:
         if southwest.srs != srs: southwest.transform(srs)
         if northeast.srs != srs: northeast.transform(srs)
         #west, south, east, north:
         msmap.setExtent(southwest.x, southwest.y, northeast.x, northeast.y)
         msmap.setProjection('init=epsg:%s' % (srs))  
     
     #render map image:
     map_image = msmap.draw()
     
     #convert from MapScript Image to PIL Image (for further manipulation):
     bytes = StringIO.StringIO(map_image.getBytes())
     new_image = Image.open(bytes)#.convert('RGBA')
     return_image = Image.new(mode='RGBA',size=(width,height),color=(255,255,255,0))
     return_image.paste(new_image, (0, 0), new_image)
     
     #return object    
     if format == OutputFormat.HTTP_RESPONSE:
         response = HttpResponse(mimetype="image/png")
         return_image.save(response, "PNG")
         return response
     elif format == OutputFormat.PNG:
         return return_image