def processParameters(self, requestname, params): finalparams = {} for paramname, paramdef in self.SERVICE_PARAMS[requestname].items(): if paramname not in params.keys() and paramdef.mandatory: raise OGCException( 'Mandatory parameter "%s" missing from request.' % paramname) elif paramname in params.keys(): try: params[paramname] = paramdef.cast(params[paramname]) except OGCException: raise except: raise OGCException( 'Invalid value "%s" for parameter "%s".' % (params[paramname], paramname)) if paramdef.allowedvalues and params[ paramname] not in paramdef.allowedvalues: if not paramdef.fallback: raise OGCException( 'Parameter "%s" has an illegal value.' % paramname) else: finalparams[paramname] = paramdef.default else: finalparams[paramname] = params[paramname] elif not paramdef.mandatory and paramdef.default: finalparams[paramname] = paramdef.default return finalparams
def __init__(self, version="1.1.1"): version = version.split('.') if len(version) != 3: raise OGCException('Badly formatted version number.') try: version = map(int, version) except: raise OGCException('Badly formatted version number.') self.version = version
def __call__(self, apacheReq): try: reqparams = util.FieldStorage(apacheReq, keep_blank_values=1) if not reqparams: eh = ExceptionHandler130(self.debug) response = eh.getresponse(reqparams) apacheReq.content_type = response.content_type else: reqparams = lowerparams(reqparams) port = apacheReq.connection.local_addr[1] onlineresource = 'http://%s:%s%s?' % ( apacheReq.hostname, port, apacheReq.subprocess_env['SCRIPT_NAME']) if not reqparams.has_key('request'): raise OGCException('Missing Request parameter.') request = reqparams['request'] del reqparams['request'] if request == 'GetCapabilities' and not reqparams.has_key( 'service'): raise OGCException('Missing service parameter.') if request in ['GetMap', 'GetFeatureInfo']: service = 'WMS' else: service = reqparams['service'] if reqparams.has_key('service'): del reqparams['service'] try: ogcserver = __import__('ogcserver.' + service) except: raise OGCException('Unsupported service "%s".' % service) ServiceHandlerFactory = getattr(ogcserver, service).ServiceHandlerFactory servicehandler = ServiceHandlerFactory( self.conf, self.mapfactory, onlineresource, reqparams.get('version', None)) if reqparams.has_key('version'): del reqparams['version'] if request not in servicehandler.SERVICE_PARAMS.keys(): raise OGCException( 'Operation "%s" not supported.' % request, 'OperationNotSupported') # Get parameters and pass to WMSFactory in custom "setup" method ogcparams = servicehandler.processParameters( request, reqparams) try: requesthandler = getattr(servicehandler, request) except: raise OGCException( 'Operation "%s" not supported.' % request, 'OperationNotSupported') response = requesthandler(ogcparams) apacheReq.content_type = response.content_type apacheReq.status = apache.HTTP_OK except Exception, E: return self.traceback(apacheReq, E)
def ogc_response(request, mapfactory): conf = SafeConfigParser() conf.readfp(open(base_path + "/ogcserver.conf")) reqparams = lowerparams(request.GET) if 'srs' in reqparams: reqparams['srs'] = str(reqparams['srs']) if 'styles' not in reqparams: reqparams['styles'] = '' onlineresource = 'http://%s%s?' % (request.META['HTTP_HOST'], request.META['PATH_INFO']) if not reqparams.has_key('request'): raise OGCException('Missing request parameter.') req = reqparams['request'] del reqparams['request'] if req == 'GetCapabilities' and not reqparams.has_key('service'): raise OGCException('Missing service parameter.') if req in ['GetMap', 'GetFeatureInfo']: service = 'WMS' else: service = reqparams['service'] if reqparams.has_key('service'): del reqparams['service'] try: ogcserver = __import__('ogcserver.' + service) except: raise OGCException('Unsupported service "%s".' % service) ServiceHandlerFactory = getattr(ogcserver, service).ServiceHandlerFactory servicehandler = ServiceHandlerFactory(conf, mapfactory, onlineresource, reqparams.get('version', None)) if reqparams.has_key('version'): del reqparams['version'] if req not in servicehandler.SERVICE_PARAMS.keys(): raise OGCException('Operation "%s" not supported.' % request, 'OperationNotSupported') ogcparams = servicehandler.processParameters(req, reqparams) try: requesthandler = getattr(servicehandler, req) except: raise OGCException('Operation "%s" not supported.' % req, 'OperationNotSupported') # stick the user agent in the request params # so that we can add ugly hacks for specific buggy clients ogcparams['HTTP_USER_AGENT'] = request.META['HTTP_USER_AGENT'] wms_resp = requesthandler(ogcparams) response = HttpResponse() response['Content-length'] = str(len(wms_resp.content)) response['Content-Type'] = wms_resp.content_type response.write(wms_resp.content) return response
def __call__(self, crsstring): if not re.match('^[A-Z]{3,5}:\d+$', crsstring): raise OGCException( 'Invalid format for the CRS parameter: %s' % crsstring, 'InvalidCRS') crsparts = crsstring.split(':') if crsparts[0] in self.allowednamespaces: return CRS(crsparts[0], crsparts[1]) else: raise OGCException('Invalid CRS Namespace: %s' % crsparts[0], 'InvalidCRS')
def GetFeatureInfo(self, params, querymethodname='query_point'): m = self._buildMap(params) if params['info_format'] == 'text/plain': writer = TextFeatureInfo() elif params['info_format'] == 'text/xml': writer = XMLFeatureInfo() if params['query_layers'] and params['query_layers'][0] == '__all__': for layerindex, layer in enumerate(m.layers): featureset = getattr(m, querymethodname)(layerindex, params['i'], params['j']) features = featureset.features if features: writer.addlayer(layer.name) for feat in features: writer.addfeature() if mapnik_version() >= 800: for prop, value in feat.attributes.iteritems(): writer.addattribute(prop, value) else: for prop in feat.properties: writer.addattribute(prop[0], prop[1]) else: for layerindex, layername in enumerate(params['query_layers']): if layername in params['layers']: # TODO - pretty sure this is bogus, we can't pull from m.layers by the layerindex of the # 'query_layers' subset, need to pull from: # self.mapfactory.layers[layername] if m.layers[layerindex].queryable: featureset = getattr(m, querymethodname)(layerindex, params['i'], params['j']) features = featureset.features if features: writer.addlayer(m.layers[layerindex].name) for feat in features: writer.addfeature() if mapnik_version() >= 800: for prop, value in feat.attributes.iteritems( ): writer.addattribute(prop, value) else: for prop in feat.properties: writer.addattribute(prop[0], prop[1]) else: raise OGCException( 'Requested query layer "%s" is not marked queryable.' % layername, 'LayerNotQueryable') else: raise OGCException( 'Requested query layer "%s" not in the LAYERS parameter.' % layername) return Response(params['info_format'], str(writer))
def process(self, request): """Process request.""" reqparams = {} for key, value in request.GET.items(): reqparams[key.lower()] = str(value) # create dynamic styles and layers self.process_trip(request, reqparams) self.mapfactory.finalize() # process request onlineresource = 'http://%s:%s%s?' % (request.META['SERVER_NAME'], request.META['SERVER_PORT'], request.META['SCRIPT_NAME']) if not reqparams.has_key('request'): raise OGCException('Missing request parameter.') request = reqparams['request'] del reqparams['request'] if request == 'GetCapabilities' and not reqparams.has_key('service'): raise OGCException('Missing service parameter.') if request in ['GetMap', 'GetFeatureInfo']: service = 'WMS' else: service = reqparams['service'] if reqparams.has_key('service'): del reqparams['service'] try: try: mapnikmodule = __import__('ogcserver.' + service) except Exception, e: print "service: %s could not be imported" % service except: raise OGCException('Unsupported service "%s".' % service) servicehandlerfactory = getattr(mapnikmodule, service).ServiceHandlerFactory servicehandler = servicehandlerfactory(self.conf, self.mapfactory, onlineresource, reqparams.get('version', None)) if reqparams.has_key('version'): del reqparams['version'] if request not in servicehandler.SERVICE_PARAMS.keys(): raise OGCException('Operation "%s" not supported.' % request, 'OperationNotSupported') ogcparams = servicehandler.processParameters(request, reqparams) try: requesthandler = getattr(servicehandler, request) except: raise OGCException('Operation "%s" not supported.' % request, 'OperationNotSupported') resp = requesthandler(ogcparams) data = resp.content response = HttpResponse(data, content_type=resp.content_type) return response
def GetMap(self, params): if params['width'] > int(self.conf.get( 'service', 'maxwidth')) or params['height'] > int( self.conf.get('service', 'maxheight')): raise OGCException( 'Requested map size exceeds limits set by this server.') return WMSBaseServiceHandler.GetMap(self, params)
def ColorFactory(colorstring): if re.match('^0x[a-fA-F0-9]{6}$', colorstring): return Color(eval('0x' + colorstring[2:4]), eval('0x' + colorstring[4:6]), eval('0x' + colorstring[6:8])) else: try: return Color(colorstring) except: raise OGCException( 'Invalid color value. Must be of format "0xFFFFFF", or any format acceptable my mapnik.Color()' )
def __call__(self, environ, start_response): reqparams = {} base = True for key, value in parse_qs(environ['QUERY_STRING'], True).items(): reqparams[key.lower()] = value[0] base = False if self.conf.has_option_with_value('service', 'baseurl'): onlineresource = '%s' % self.conf.get('service', 'baseurl') else: # if there is no baseurl in the config file try to guess a valid one onlineresource = 'http://%s%s%s?' % (environ['HTTP_HOST'], environ['SCRIPT_NAME'], environ['PATH_INFO']) try: if not reqparams.has_key('request'): raise OGCException('Missing request parameter.') request = reqparams['request'] del reqparams['request'] if request == 'GetCapabilities' and not reqparams.has_key('service'): raise OGCException('Missing service parameter.') if request in ['GetMap', 'GetFeatureInfo']: service = 'WMS' else: try: service = reqparams['service'] except: service = 'WMS' request = 'GetCapabilities' if reqparams.has_key('service'): del reqparams['service'] try: ogcserver = do_import('ogcserver') except: raise OGCException('Unsupported service "%s".' % service) ServiceHandlerFactory = getattr(ogcserver, service).ServiceHandlerFactory servicehandler = ServiceHandlerFactory(self.conf, self.mapfactory, onlineresource, reqparams.get('version', None)) if reqparams.has_key('version'): del reqparams['version'] if request not in servicehandler.SERVICE_PARAMS.keys(): raise OGCException('Operation "%s" not supported.' % request, 'OperationNotSupported') ogcparams = servicehandler.processParameters(request, reqparams) try: requesthandler = getattr(servicehandler, request) except: raise OGCException('Operation "%s" not supported.' % request, 'OperationNotSupported') # stick the user agent in the request params # so that we can add ugly hacks for specific buggy clients ogcparams['HTTP_USER_AGENT'] = environ.get('HTTP_USER_AGENT', '') response = requesthandler(ogcparams) except: version = reqparams.get('version', None) if not version: version = Version() else: version = Version(version) if version >= '1.3.0': eh = ExceptionHandler130(self.debug,base,self.home_html) else: eh = ExceptionHandler111(self.debug,base,self.home_html) response = eh.getresponse(reqparams) response_headers = [('Content-Type', response.content_type),('Content-Length', str(len(response.content)))] if self.max_age: response_headers.append(('Cache-Control', self.max_age)) start_response('200 OK', response_headers) yield response.content
def _buildMap(self, params): if str(params['crs']) not in self.allowedepsgcodes: raise OGCException( 'Unsupported CRS "%s" requested.' % str(params['crs']).upper(), 'InvalidCRS') if params['bbox'][0] >= params['bbox'][2]: raise OGCException( "BBOX values don't make sense. minx is greater than maxx.") if params['bbox'][1] >= params['bbox'][3]: raise OGCException( "BBOX values don't make sense. miny is greater than maxy.") # relax this for now to allow for a set of specific layers (meta layers even) # to be used without known their styles or putting the right # of commas... #if params.has_key('styles') and len(params['styles']) != len(params['layers']): # raise OGCException('STYLES length does not match LAYERS length.') m = Map(params['width'], params['height'], '+init=%s' % params['crs']) if params.has_key('transparent') and params['transparent'] in ( 'FALSE', 'False', 'false'): if params['bgcolor']: m.background = params['bgcolor'] elif not params.has_key( 'transparent') and self.mapfactory.map_attributes.get( 'bgcolor'): m.background = self.mapfactory.map_attributes['bgcolor'] else: m.background = Color(0, 0, 0, 0) if params.has_key('buffer_size'): if params['buffer_size']: m.buffer_size = params['buffer_size'] else: buffer_ = self.mapfactory.map_attributes.get('buffer_size') if buffer_: m.buffer_size = self.mapfactory.map_attributes['buffer_size'] # haiti spec tmp hack! show meta layers without having # to request huge string to avoid some client truncating it! if params['layers'] and params['layers'][0] in ( 'osm_haiti_overlay', 'osm_haiti_overlay_900913'): for layer_obj in self.mapfactory.ordered_layers: layer = copy_layer(layer_obj) if not hasattr(layer, 'meta_style'): pass else: layer.styles.append(layer.meta_style) m.append_style( layer.meta_style, self.mapfactory.meta_styles[layer.meta_style]) m.layers.append(layer) # a non WMS spec way of requesting all layers # uses orderedlayers that preserves original ordering in XML mapfile elif params['layers'] and params['layers'][0] == '__all__': for layer_obj in self.mapfactory.ordered_layers: # if we don't copy the layer here we get # duplicate layers added to the map because the # layer is kept around and the styles "pile up"... layer = copy_layer(layer_obj) if hasattr(layer, 'meta_style'): continue reqstyle = layer.wmsdefaultstyle if reqstyle in self.mapfactory.aggregatestyles.keys(): for stylename in self.mapfactory.aggregatestyles[reqstyle]: layer.styles.append(stylename) else: layer.styles.append(reqstyle) for stylename in layer.styles: if stylename in self.mapfactory.styles.keys(): m.append_style(stylename, self.mapfactory.styles[stylename]) m.layers.append(layer) else: for layerindex, layername in enumerate(params['layers']): if layername in self.mapfactory.meta_layers: layer = copy_layer(self.mapfactory.meta_layers[layername]) layer.styles.append(layername) m.append_style(layername, self.mapfactory.meta_styles[layername]) else: try: # uses unordered dict of layers # order based on params['layers'] request which # should be originally informed by order of GetCaps response layer = copy_layer(self.mapfactory.layers[layername]) except KeyError: raise OGCException( 'Layer "%s" not defined.' % layername, 'LayerNotDefined') try: reqstyle = params['styles'][layerindex] except IndexError: reqstyle = '' if reqstyle and reqstyle not in layer.wmsextrastyles: raise OGCException( 'Invalid style "%s" requested for layer "%s".' % (reqstyle, layername), 'StyleNotDefined') if not reqstyle: reqstyle = layer.wmsdefaultstyle if reqstyle in self.mapfactory.aggregatestyles.keys(): for stylename in self.mapfactory.aggregatestyles[ reqstyle]: layer.styles.append(stylename) else: layer.styles.append(reqstyle) for stylename in layer.styles: if stylename in self.mapfactory.styles.keys(): m.append_style(stylename, self.mapfactory.styles[stylename]) else: raise ServerConfigurationError( 'Layer "%s" refers to non-existent style "%s".' % (layername, stylename)) m.layers.append(layer) m.zoom_to_box( Envelope(params['bbox'][0], params['bbox'][1], params['bbox'][2], params['bbox'][3])) return m
def process(self, req): base = False if not req.params: base = True reqparams = lowerparams(req.params) if self.conf.has_option_with_value('service', 'baseurl'): onlineresource = '%s' % self.conf.get('service', 'baseurl') else: # if there is no baseurl in the config file try to guess a valid one onlineresource = 'http://%s%s?' % (req.environ['HTTP_HOST'], req.environ['SCRIPT_NAME']) try: if not reqparams.has_key('request'): raise OGCException('Missing request parameter.') request = reqparams['request'] del reqparams['request'] if request == 'GetCapabilities' and not reqparams.has_key( 'service'): raise OGCException('Missing service parameter.') if request in ['GetMap', 'GetFeatureInfo']: service = 'WMS' else: service = reqparams['service'] if reqparams.has_key('service'): del reqparams['service'] try: ogcserver = __import__('ogcserver.' + service) except: raise OGCException('Unsupported service "%s".' % service) ServiceHandlerFactory = getattr(ogcserver, service).ServiceHandlerFactory servicehandler = ServiceHandlerFactory( self.conf, self.mapfactory, onlineresource, reqparams.get('version', None)) if reqparams.has_key('version'): del reqparams['version'] if request not in servicehandler.SERVICE_PARAMS.keys(): raise OGCException('Operation "%s" not supported.' % request, 'OperationNotSupported') ogcparams = servicehandler.processParameters(request, reqparams) try: requesthandler = getattr(servicehandler, request) except: raise OGCException('Operation "%s" not supported.' % request, 'OperationNotSupported') # stick the user agent in the request params # so that we can add ugly hacks for specific buggy clients ogcparams['HTTP_USER_AGENT'] = req.environ['HTTP_USER_AGENT'] response = requesthandler(ogcparams) except: version = reqparams.get('version', None) if not version: version = Version() else: version = Version(version) if version >= '1.3.0': eh = ExceptionHandler130(self.debug, base, self.home_html) else: eh = ExceptionHandler111(self.debug, base, self.home_html) response = eh.getresponse(reqparams) req.set_header('Content-Type', response.content_type) req.set_header('Content-Length', str(len(response.content))) req.write(response.content)
def _buildMap(self, params): """This variant of buildmap just serves up the map as defined in the xml file, plus some customizations from the params. Style and SRS are ignored.""" if str(params['crs']) not in self.allowedepsgcodes: raise OGCException( 'Unsupported CRS "%s" requested.' % str(params['crs']).upper(), 'InvalidCRS') if params['bbox'][0] >= params['bbox'][2]: raise OGCException( "BBOX values don't make sense. minx is greater than maxx.") if params['bbox'][1] >= params['bbox'][3]: raise OGCException( "BBOX values don't make sense. miny is greater than maxy.") # There should be only one layer requested. if len(params['layers']) <> 1: raise OGCException( "When specifying a pre-rendered map, only one layer is allowed." ) # retrieve the map object and set width and height. # leave srs alone. m = self.mapfactory.layers[params['layers'][0]] m.width = params['width'] m.height = params['height'] transparent = params.get('transparent', '').lower() == 'true' # disable transparent on incompatible formats if transparent and params.get('format', '') == 'image/jpeg': transparent = False if transparent: # transparent has highest priority pass elif params.has_key('bgcolor'): # if not transparent use bgcolor in url m.background = params['bgcolor'] else: # if not bgcolor in url use map background if mapnik_version() >= 200000: bgcolor = self.mapfactory.map_attributes.get('bgcolor', None) else: bgcolor = self.mapfactory.map_attributes.get( 'background-color', None) if bgcolor: m.background = bgcolor else: # if not map background defined use white color m.background = Color(255, 255, 255, 255) if params.has_key('buffer_size'): if params['buffer_size']: m.buffer_size = params['buffer_size'] else: buffer_ = self.mapfactory.map_attributes.get('buffer_size') if buffer_: m.buffer_size = self.mapfactory.map_attributes['buffer_size'] m.zoom_to_box( Box2d(params['bbox'][0], params['bbox'][1], params['bbox'][2], params['bbox'][3])) return m
def request_mapnik(self, env, mapdata, que=None): """ render on mapnik request """ if self.mapnik_ver >= 300000: map_obj = mapdata else: map_obj = self.ogcserver_constructor(mapdata) reqparams = {} base = True for key, value in parse_qs(env['QUERY_STRING'], True).items(): reqparams[key.lower()] = value[0] base = False if self.ogcconf.has_option_with_value('service', 'baseurl'): onlineresource = '%s' % self.ogcconf.get('service', 'baseurl') else: onlineresource = 'http://%s%s%s?' % ( env['HTTP_HOST'], env['SCRIPT_NAME'], env['PATH_INFO'] ) try: if not reqparams.has_key('request'): raise OGCException('Missing request parameter.') request = reqparams['request'] del reqparams['request'] if request == 'GetCapabilities' and not reqparams.has_key('service'): raise OGCException('Missing service parameter.') if request in ['GetMap', 'GetFeatureInfo']: service = 'WMS' else: try: service = reqparams['service'] except: service = 'WMS' request = 'GetCapabilities' if reqparams.has_key('service'): del reqparams['service'] ServiceHandlerFactory = getattr(self.ogcserver, service).ServiceHandlerFactory servicehandler = ServiceHandlerFactory( self.ogcconf, map_obj, onlineresource, reqparams.get('version', None) ) if reqparams.has_key('version'): del reqparams['version'] if request not in servicehandler.SERVICE_PARAMS.keys(): raise OGCException( 'Operation "%s" not supported.' % request, 'OperationNotSupported' ) ogcparams = servicehandler.processParameters(request, reqparams) try: requesthandler = getattr(servicehandler, request) except: raise OGCException( 'Operation "%s" not supported.' % request, 'OperationNotSupported' ) ogcparams['HTTP_USER_AGENT'] = env.get('HTTP_USER_AGENT', '') response = requesthandler(ogcparams) except: version = reqparams.get('version', None) if not version: version = Version() else: version = Version(version) if version >= '1.3.0': eh = ExceptionHandler130(self.debug,base,self.home_html) else: eh = ExceptionHandler111(self.debug,base,self.home_html) response = eh.getresponse(reqparams) out_response = (response.content_type, response.content) if que is None: return out_response else: que.put(out_response)