def __init__(self, configpath, mapfile=None,fonts=None,home_html=None): conf = SafeConfigParser() conf.readfp(open(configpath)) # TODO - be able to supply in config as well self.home_html = home_html self.conf = conf if fonts: mapnik.register_fonts(fonts) if mapfile: wms_factory = BaseWMSFactory(configpath) # TODO - add support for Cascadenik MML wms_factory.loadXML(mapfile) wms_factory.finalize() self.mapfactory = wms_factory else: if not conf.has_option_with_value('server', 'module'): raise ServerConfigurationError('The factory module is not defined in the configuration file.') try: mapfactorymodule = do_import(conf.get('server', 'module')) except ImportError: raise ServerConfigurationError('The factory module could not be loaded.') if hasattr(mapfactorymodule, 'WMSFactory'): self.mapfactory = getattr(mapfactorymodule, 'WMSFactory')() else: raise ServerConfigurationError('The factory module does not have a WMSFactory class.') if conf.has_option('server', 'debug'): self.debug = int(conf.get('server', 'debug')) else: self.debug = 0 if self.conf.has_option_with_value('server', 'maxage'): self.max_age = 'max-age=%d' % self.conf.get('server', 'maxage') else: self.max_age = None
def __init__(self, configpath): conf = SafeConfigParser() conf.readfp(open(configpath)) self.conf = conf if not conf.has_option_with_value('server', 'module'): raise ServerConfigurationError( 'The factory module is not defined in the configuration file.') try: mapfactorymodule = __import__(conf.get('server', 'module')) except ImportError: raise ServerConfigurationError( 'The factory module could not be loaded.') if hasattr(mapfactorymodule, 'WMSFactory'): self.mapfactory = getattr(mapfactorymodule, 'WMSFactory')() else: raise ServerConfigurationError( 'The factory module does not have a WMSFactory class.') if conf.has_option('server', 'debug'): self.debug = int(conf.get('server', 'debug')) else: self.debug = 0 if self.conf.has_option_with_value('server', 'maxage'): self.max_age = 'max-age=%d' % self.conf.get('server', 'maxage') else: self.max_age = None
def register_style(self, name, style): if not name: raise ServerConfigurationError('Attempted to register a style without providing a name.') if name in self.aggregatestyles.keys() or name in self.styles.keys(): raise ServerConfigurationError("Attempted to register a style with a name already in use: '%s'" % name) if not isinstance(style, Style): raise ServerConfigurationError('Bad style object passed to register_style() for style "%s".' % name) self.styles[name] = style
def finalize(self): if len(self.layers) == 0: raise ServerConfigurationError('No layers defined!') if len(self.styles) == 0: raise ServerConfigurationError('No styles defined!') for layer in self.layers.values(): for style in list(layer.styles) + list(layer.wmsextrastyles): if style not in self.styles.keys() + self.aggregatestyles.keys(): raise ServerConfigurationError('Layer "%s" refers to undefined style "%s".' % (layer.name, style))
def register_aggregate_style(self, name, stylenames): if not name: raise ServerConfigurationError('Attempted to register an aggregate style without providing a name.') if name in self.aggregatestyles.keys() or name in self.styles.keys(): raise ServerConfigurationError('Attempted to register an aggregate style with a name already in use.') self.aggregatestyles[name] = [] for stylename in stylenames: if stylename not in self.styles.keys(): raise ServerConfigurationError('Attempted to register an aggregate style containing a style that does not exist.') self.aggregatestyles[name].append(stylename)
def __init__(self, configpath, mapfile=None, fonts=None, home_html=None): # 实例化 ConfigParser 并加载配置文件 conf = SafeConfigParser() # 从配置文件读取并分析(分列)配置信息 conf.readfp(open(configpath)) # TODO - be able to supply in config as well self.home_html = home_html self.conf = conf if fonts: # 注册指定字体 mapnik.register_fonts(fonts) if mapfile: # 生成BaseWMSFactory实例 wms_factory = BaseWMSFactory(configpath) # TODO - add support for Cascadenik MML wms_factory.loadXML(mapfile) wms_factory.finalize() self.mapfactory = wms_factory else: # 阅读default.conf,有疑惑??? # # 原default.conf文件中module未定义,需要使用要在default.conf中自行定义 if not conf.has_option_with_value('server', 'module'): raise ServerConfigurationError( 'The factory module is not defined in the configuration file.' ) # 导入指定module try: # get(section,option),Get an option value for the named # section. mapfactorymodule = do_import(conf.get('server', 'module')) except ImportError: raise ServerConfigurationError( 'The factory module could not be loaded.') if hasattr(mapfactorymodule, 'WMSFactory'): # Get a named attribute from an object; getattr(x, 'y') is # equivalent to x.y. self.mapfactory = getattr(mapfactorymodule, 'WMSFactory')() else: raise ServerConfigurationError( 'The factory module does not have a WMSFactory class.') if conf.has_option('server', 'debug'): self.debug = int(conf.get('server', 'debug')) else: self.debug = 0 if self.conf.has_option_with_value('server', 'maxage'): self.max_age = 'max-age=%d' % self.conf.get('server', 'maxage') else: self.max_age = None
def register_style(self, name, style): # 差错处理,是否输入name,name是否已经存在,style类型是否正确 if not name: raise ServerConfigurationError( 'Attempted to register a style without providing a name.') if name in self.aggregatestyles.keys() or name in self.styles.keys(): raise ServerConfigurationError( "Attempted to register a style with a name already in use: '%s'" % name) if not isinstance(style, Style): raise ServerConfigurationError( 'Bad style object passed to register_style() for style "%s".' % name) # 在对象的style属性的dict中添加style self.styles[name] = style
def loadXML(self, xmlfile=None, strict=False, xmlstring='', basepath=''): """Loads and stores a complete map definition in leiu of a set of layers. Stores an empty style of the same name, which is the only option for rendering. The map will be rendered as prescribed in the XML.""" config = ConfigParser.SafeConfigParser() map_wms_srs = None if self.configpath: config.readfp(open(self.configpath)) if config.has_option('map', 'wms_srs'): map_wms_srs = config.get('map', 'wms_srs') tmp_map = Map(0,0) if xmlfile: load_map(tmp_map, xmlfile, strict) elif xmlstring: load_map_from_string(tmp_map, xmlstring, strict, basepath) else: raise ServerConfigurationError("Mapnik configuration XML is not specified - 'xmlfile' and 'xmlstring' variables are empty.\ Please set one of this variables to load mapnik map object.") # parse map level attributes if tmp_map.background: self.map_attributes['bgcolor'] = tmp_map.background if tmp_map.buffer_size: self.map_attributes['buffer_size'] = tmp_map.buffer_size if xmlfile is None : # Map objects have no name, so just call it default. layer_name = 'default' else : # The layer name is the basename of the xml file or the # whole file name layer_name = xmlfile fname_match = re.match('([A-Za-z0-9_\-\.]+).xml', xmlfile) if fname_match is not None : layer_name = fname_match.group(1) else : layer_name = xmlfile style_name = layer_name style_obj = Style() # Make the map have attributes expected of layers tmp_map.name = layer_name map_p = common.Projection(tmp_map.srs) if map_wms_srs is None : tmp_map.wms_srs = map_p.epsgstring() else : tmp_map.wms_srs = map_wms_srs tmp_map.queryable = False # set map extent from config file. geog_coords = config.get('map','wms_extent').split(',') geog_box = Box2d(float(geog_coords[0]), float(geog_coords[1]), float(geog_coords[2]), float(geog_coords[3])) proj_box = geog_box.forward(map_p) tmp_map.zoom_to_box(proj_box) tmp_map.maximum_extent = proj_box self.register_style(style_name, style_obj) self.register_layer(tmp_map, style_name)
def __init__(self, mandatory, cast, default=None, allowedvalues=None, fallback=False): """ An OGC request parameter definition. Used to describe a parameter's characteristics. @param mandatory: Is this parameter required by the request? @type mandatory: Boolean. @param default: Default value to use if one is not provided and the parameter is optional. @type default: None or any valid value. @param allowedvalues: A list of allowed values for the parameter. If a value is provided that is not in this list, an error is raised. @type allowedvalues: A python tuple of values. @param fallback: Whether the value of the parameter should fall back to the default should an illegal value be provided. @type fallback: Boolean. @return: A L{ParameterDefinition} instance. """ if mandatory not in [True, False]: raise ServerConfigurationError( "Bad value for 'mandatory' parameter, must be True or False.") self.mandatory = mandatory if not callable(cast): raise ServerConfigurationError( 'Cast parameter definition must be callable.') self.cast = cast self.default = default if allowedvalues and type(allowedvalues) != type(()): raise ServerConfigurationError( "Bad value for 'allowedvalues' parameter, must be a tuple.") self.allowedvalues = allowedvalues if fallback not in [True, False]: raise ServerConfigurationError( "Bad value for 'fallback' parameter, must be True or False.") self.fallback = fallback
def __init__(self, conf, mapfactory, opsonlineresource): self.conf = conf self.mapfactory = mapfactory self.opsonlineresource = opsonlineresource if self.conf.has_option('service', 'allowedepsgcodes'): self.allowedepsgcodes = map(lambda code: 'epsg:%s' % code, self.conf.get('service', 'allowedepsgcodes').split(',')) else: raise ServerConfigurationError('Allowed EPSG codes not properly configured.') self.capabilities = None
def __init__(self, configpath, server_module, fonts=None, home_html=None, **kwargs ): BasePasteWSGIApp.__init__(self, configpath, font=fonts, home_html=home_html, **kwargs) try: mapfactorymodule = do_import(server_module) except ImportError: raise ServerConfigurationError('The factory module could not be loaded.') if hasattr(mapfactorymodule, 'WMSFactory'): self.mapfactory = getattr(mapfactorymodule, 'WMSFactory')(configpath) else: raise ServerConfigurationError('The factory module does not have a WMSFactory class.')
def register_layer(self, layer, defaultstyle, extrastyles=()): layername = layer.name if not layername: raise ServerConfigurationError('Attempted to register an unnamed layer.') if not layer.wms_srs and not re.match('^\+init=epsg:\d+$', layer.srs) and not re.match('^\+proj=.*$', layer.srs): raise ServerConfigurationError('Attempted to register a layer without an epsg projection defined.') if defaultstyle not in self.styles.keys() + self.aggregatestyles.keys(): raise ServerConfigurationError('Attempted to register a layer with an non-existent default style.') layer.wmsdefaultstyle = defaultstyle if isinstance(extrastyles, tuple): for stylename in extrastyles: if type(stylename) == type(''): if stylename not in self.styles.keys() + self.aggregatestyles.keys(): raise ServerConfigurationError('Attempted to register a layer with an non-existent extra style.') else: ServerConfigurationError('Attempted to register a layer with an invalid extra style name.') layer.wmsextrastyles = extrastyles else: raise ServerConfigurationError('Layer "%s" was passed an invalid list of extra styles. List must be a tuple of strings.' % layername) layerproj = common.Projection(layer.srs) env = getattr(layer, 'maximum_extent', layer.envelope()) llp = layerproj.inverse(Coord(env.minx, env.miny)) urp = layerproj.inverse(Coord(env.maxx, env.maxy)) if self.latlonbb is None: self.latlonbb = Box2d(llp, urp) else: self.latlonbb.expand_to_include(Box2d(llp, urp)) self.ordered_layers.append(layer) self.layers[layername] = layer
def __init__(self, home_html=None): conf = SafeConfigParser() conf.readfp(open(self.configpath)) # TODO - be able to supply in config as well self.home_html = home_html self.conf = conf if not conf.has_option_with_value('server', 'module'): raise ServerConfigurationError( 'The factory module is not defined in the configuration file.') try: mapfactorymodule = __import__(conf.get('server', 'module')) except ImportError: raise ServerConfigurationError( 'The factory module could not be loaded.') if hasattr(mapfactorymodule, 'WMSFactory'): self.mapfactory = getattr(mapfactorymodule, 'WMSFactory')() else: raise ServerConfigurationError( 'The factory module does not have a WMSFactory class.') if conf.has_option('server', 'debug'): self.debug = int(conf.get('server', 'debug')) else: self.debug = 0
def register_layer(self, layer, defaultstyle, extrastyles=()): layername = layer.name #差错机制,检测相关参数是否有效 if not layername: #ServerConfigurationError为从ogcserver.exceptions中导入的方法,执行内容为空 raise ServerConfigurationError( 'Attempted to register an unnamed layer.') if not layer.wms_srs and not re.match('^\+init=epsg:\d+$', layer.srs) and not re.match( '^\+proj=.*$', layer.srs): raise ServerConfigurationError( 'Attempted to register a layer without an epsg projection defined.' ) if defaultstyle not in self.styles.keys() + self.aggregatestyles.keys( ): raise ServerConfigurationError( 'Attempted to register a layer with an non-existent default style.' ) layer.wmsdefaultstyle = defaultstyle # 判断是否为tuple类型,('a',)为tuple类型,aggregates也为tuple类型 # type(('a',))输出为 tuple if isinstance(extrastyles, tuple): # for stylename in extrastyles: # 如果stylename类型为str if type(stylename) == type(''): if stylename not in self.styles.keys( ) + self.aggregatestyles.keys(): raise ServerConfigurationError( 'Attempted to register a layer with an non-existent extra style.' ) else: ServerConfigurationError( 'Attempted to register a layer with an invalid extra style name.' ) # wmsextrastyles???? layer.wmsextrastyles = extrastyles else: raise ServerConfigurationError( 'Layer "%s" was passed an invalid list of extra styles. List must be a tuple of strings.' % layername) # 调用common中Projection layerproj = common.Projection(layer.srs) env = layer.envelope() llp = layerproj.inverse(Coord(env.minx, env.miny)) urp = layerproj.inverse(Coord(env.maxx, env.maxy)) if self.latlonbb is None: self.latlonbb = Envelope(llp, urp) else: self.latlonbb.expand_to_include(Envelope(llp, urp)) self.ordered_layers.append(layer) self.layers[layername] = layer
def register_layer(self, layer, defaultstyle, extrastyles=()): layername = layer.name if not layername: raise ServerConfigurationError( 'Attempted to register an unnamed layer.') if not layer.wms_srs and not re.match('^\+init=epsg:\d+$', layer.srs) and not re.match( '^\+proj=.*$', layer.srs): raise ServerConfigurationError( 'Attempted to register a layer without an epsg projection defined.' ) if defaultstyle not in self.styles.keys() + self.aggregatestyles.keys( ): raise ServerConfigurationError( 'Attempted to register a layer with an non-existent default style.' ) layer.wmsdefaultstyle = defaultstyle if isinstance(extrastyles, tuple): for stylename in extrastyles: if type(stylename) == type(''): if stylename not in self.styles.keys( ) + self.aggregatestyles.keys(): raise ServerConfigurationError( 'Attempted to register a layer with an non-existent extra style.' ) else: ServerConfigurationError( 'Attempted to register a layer with an invalid extra style name.' ) layer.wmsextrastyles = extrastyles else: raise ServerConfigurationError( 'Layer "%s" was passed an invalid list of extra styles. List must be a tuple of strings.' % layername) self.ordered_layers.append(layer) self.layers[layername] = layer
def myloadXML(self, xmlfile, strict=False): config = ConfigParser.SafeConfigParser() map_wms_srs = None if self.configpath: config.readfp(open(self.configpath)) if config.has_option('map', 'wms_srs'): map_wms_srs = config.get('map', 'wms_srs') tmp_map = mapnik.Map(0, 0) xml_f = open(xmlfile, 'rb') xml_str = xml_f.read() xml_f.close() mapnik.load_map_from_string(tmp_map, xml_str, strict) # parse map level attributes if tmp_map.background: self.map_attributes['bgcolor'] = tmp_map.background if tmp_map.buffer_size: self.map_attributes['buffer_size'] = tmp_map.buffer_size for lyr in tmp_map.layers: layer_section = 'layer_%s' % lyr.name layer_wms_srs = None if config.has_option(layer_section, 'wms_srs'): layer_wms_srs = config.get(layer_section, 'wms_srs') else: layer_wms_srs = map_wms_srs style_count = len(lyr.styles) if style_count == 0: raise ServerConfigurationError( "Cannot register Layer '%s' without a style" % lyr.name) elif style_count == 1: style_obj = tmp_map.find_style(lyr.styles[0]) style_name = lyr.styles[0] meta_s = extract_named_rules(style_obj) if meta_s: self.meta_styles['%s_meta' % lyr.name] = meta_s if hasattr(lyr, 'abstract'): name_ = lyr.abstract else: name_ = lyr.name meta_layer_name = '%s:%s' % (name_, '-'.join(meta_s.names)) meta_layer_name = meta_layer_name.replace(' ', '_') self.meta_styles[meta_layer_name] = meta_s meta_lyr = ogcserver.common.copy_layer(lyr) meta_lyr.meta_style = meta_layer_name meta_lyr.name = meta_layer_name meta_lyr.wmsextrastyles = () meta_lyr.defaultstyle = meta_layer_name meta_lyr.wms_srs = layer_wms_srs self.ordered_layers.append(meta_lyr) self.meta_layers[meta_layer_name] = meta_lyr print meta_layer_name if style_name not in self.aggregatestyles.keys( ) and style_name not in self.styles.keys(): self.register_style(style_name, style_obj) # must copy layer here otherwise we'll segfault lyr_ = ogcserver.common.copy_layer(lyr) lyr_.wms_srs = layer_wms_srs self.register_layer(lyr_, style_name, extrastyles=(style_name, )) elif style_count > 1: for style_name in lyr.styles: style_obj = tmp_map.find_style(style_name) meta_s = extract_named_rules(style_obj) if meta_s: self.meta_styles['%s_meta' % lyr.name] = meta_s if hasattr(lyr, 'abstract'): name_ = lyr.abstract else: name_ = lyr.name meta_layer_name = '%s:%s' % (name_, '-'.join( meta_s.names)) meta_layer_name = meta_layer_name.replace(' ', '_') self.meta_styles[meta_layer_name] = meta_s meta_lyr = ogcserver.common.copy_layer(lyr) meta_lyr.meta_style = meta_layer_name print meta_layer_name meta_lyr.name = meta_layer_name meta_lyr.wmsextrastyles = () meta_lyr.defaultstyle = meta_layer_name meta_lyr.wms_srs = layer_wms_srs self.ordered_layers.append(meta_lyr) self.meta_layers[meta_layer_name] = meta_lyr if style_name not in self.aggregatestyles.keys( ) and style_name not in self.styles.keys(): self.register_style(style_name, style_obj) aggregates = tuple([sty for sty in lyr.styles]) aggregates_name = '%s_aggregates' % lyr.name self.register_aggregate_style(aggregates_name, aggregates) # must copy layer here otherwise we'll segfault lyr_ = ogcserver.common.copy_layer(lyr) lyr_.wms_srs = layer_wms_srs self.register_layer(lyr_, aggregates_name, extrastyles=aggregates) #sty,rl = Style(), Rule() #poly = PolygonSymbolizer(Color('#f2eff9')) #line = LineSymbolizer(Color('#ff3366'),.5) #rl.symbols.extend([poly,line]) #sty.rules.append(rl) #self.register_style('world_style',sty) #lyr = Layer('world',PROJ4_STRING) #lyr.datasource = Shapefile(file=SHAPEFILE) #lyr.title = 'World Borders' #lyr.abstract = 'Country Borders of the World' #self.register_layer(lyr,'world_style',('world_style',)) self.finalize()
def loadXML(self, xmlfile=None, strict=False, xmlstring='', basepath=''): config = ConfigParser.SafeConfigParser() #声明变量,用于保存 map中的wms_srs map_wms_srs = None if self.configpath: config.readfp(open(self.configpath)) if config.has_option('map', 'wms_srs'): map_wms_srs = config.get('map', 'wms_srs') #声明变量tmp_map保存Map(0,0),Map从mapnik模块中导入,此处详见doc/mapnik_help.text tmp_map = Map(0, 0) #支持文件模式和字符串格式的输入 if xmlfile: load_map(tmp_map, xmlfile, strict) elif xmlstring: load_map_from_string(tmp_map, xmlstring, strict, basepath) else: #差错机制 raise ServerConfigurationError( "Mapnik configuration XML is not specified - 'xmlfile' and 'xmlstring' variables are empty.\ Please set one of this variables to load mapnik map object.") # parse map level attributes #解析地图图层特征参数 #背景颜色(待查) if tmp_map.background: self.map_attributes['bgcolor'] = tmp_map.background #buffer大小(待查) if tmp_map.buffer_size: self.map_attributes['buffer_size'] = tmp_map.buffer_size #对tmp_map中layers中所有lyr,进行参数解析 for lyr in tmp_map.layers: layer_section = 'layer_%s' % lyr.name layer_wms_srs = None if config.has_option(layer_section, 'wms_srs'): layer_wms_srs = config.get(layer_section, 'wms_srs') else: layer_wms_srs = map_wms_srs if config.has_option(layer_section, 'title'): lyr.title = config.get(layer_section, 'title') else: lyr.title = '' if config.has_option(layer_section, 'abstract'): lyr.abstract = config.get(layer_section, 'abstract') else: lyr.abstract = '' style_count = len(lyr.styles) #必须设定有lyr.styles if style_count == 0: raise ServerConfigurationError( "Cannot register Layer '%s' without a style" % lyr.name) elif style_count == 1: #.find_style方法为mapnik中Map类的方法????? style_obj = tmp_map.find_style(lyr.styles[0]) style_name = lyr.styles[0] # 对style_obj进行处理,提取参数返回为 style类 meta_s = extract_named_rules(style_obj) if meta_s: # BaseWMSFactory类的meta_styles属性 self.meta_styles['%s_meta' % lyr.name] = meta_s # 判断lyr是否含有abstract属性 if hasattr(lyr, 'abstract'): name_ = lyr.abstract else: name_ = lyr.name # 将meta_s.names中的字符串序列用“-”连接 meta_layer_name = '%s:%s' % (name_, '-'.join(meta_s.names)) # 将meta_layer_name中的空格全部替换为“_” meta_layer_name = meta_layer_name.replace(' ', '_') self.meta_styles[meta_layer_name] = meta_s meta_lyr = common.copy_layer(lyr) meta_lyr.meta_style = meta_layer_name meta_lyr.name = meta_layer_name meta_lyr.wmsextrastyles = () meta_lyr.defaultstyle = meta_layer_name meta_lyr.wms_srs = layer_wms_srs self.ordered_layers.append(meta_lyr) self.meta_layers[meta_layer_name] = meta_lyr print meta_layer_name # 如果aggregatestyles和styles中没有style_name的关键字,则注册style。.register_style为本类定义的方法 if style_name not in self.aggregatestyles.keys( ) and style_name not in self.styles.keys(): self.register_style(style_name, style_obj) # must copy layer here otherwise we'll segfault # c此处必须拷贝图层,否则将出现段错误 # common lyr_ = common.copy_layer(lyr) lyr_.wms_srs = layer_wms_srs #register_layer为本类定义的一个方法, self.register_layer(lyr_, style_name, extrastyles=(style_name, )) # 当style_count > 1时,处理步骤与style_count = 1时大致相同, elif style_count > 1: for style_name in lyr.styles: style_obj = tmp_map.find_style(style_name) meta_s = extract_named_rules(style_obj) if meta_s: self.meta_styles['%s_meta' % lyr.name] = meta_s if hasattr(lyr, 'abstract'): name_ = lyr.abstract else: name_ = lyr.name meta_layer_name = '%s:%s' % (name_, '-'.join( meta_s.names)) meta_layer_name = meta_layer_name.replace(' ', '_') self.meta_styles[meta_layer_name] = meta_s meta_lyr = common.copy_layer(lyr) meta_lyr.meta_style = meta_layer_name print meta_layer_name meta_lyr.name = meta_layer_name meta_lyr.wmsextrastyles = () meta_lyr.defaultstyle = meta_layer_name meta_lyr.wms_srs = layer_wms_srs self.ordered_layers.append(meta_lyr) self.meta_layers[meta_layer_name] = meta_lyr if style_name not in self.aggregatestyles.keys( ) and style_name not in self.styles.keys(): self.register_style(style_name, style_obj) # 与style_count = 1时的不同之处, aggregates = tuple([sty for sty in lyr.styles]) aggregates_name = '%s_aggregates' % lyr.name self.register_aggregate_style(aggregates_name, aggregates) # must copy layer here otherwise we'll segfault lyr_ = common.copy_layer(lyr) lyr_.wms_srs = layer_wms_srs self.register_layer(lyr_, aggregates_name, extrastyles=aggregates) if 'default' in aggregates: sys.stderr.write( "Warning: Multi-style layer '%s' contains a regular style named 'default'. \ This style will effectively be hidden by the 'all styles' default style for multi-style layers.\n" % lyr_.name)
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 processServiceCapabilities(self, capetree): if len(self.conf.items('service')) > 0: servicee = capetree.find('Service') if servicee == None: servicee = capetree.find('{http://www.opengis.net/wms}Service') for item in self.CONF_SERVICE: if self.conf.has_option_with_value('service', item[0]): value = self.conf.get('service', item[0]).strip() try: item[2](value) except: raise ServerConfigurationError( 'Configuration parameter [%s]->%s has an invalid value: %s.' % ('service', item[0], value)) if item[0] == 'onlineresource': element = ElementTree.Element('%s' % item[1]) servicee.append(element) element.set('{http://www.w3.org/1999/xlink}href', value) element.set('{http://www.w3.org/1999/xlink}type', 'simple') elif item[0] == 'keywordlist': element = ElementTree.Element('%s' % item[1]) servicee.append(element) keywords = value.split(',') keywords = map(str.strip, keywords) for keyword in keywords: kelement = ElementTree.Element('Keyword') kelement.text = keyword element.append(kelement) else: element = ElementTree.Element('%s' % item[1]) element.text = to_unicode(value) servicee.append(element) if len(self.conf.items_with_value('contact')) > 0: element = ElementTree.Element('ContactInformation') servicee.append(element) for item in self.CONF_CONTACT: if self.conf.has_option_with_value('contact', item[0]): value = self.conf.get('contact', item[0]).strip() try: item[2](value) except: raise ServerConfigurationError( 'Configuration parameter [%s]->%s has an invalid value: %s.' % ('service', item[0], value)) celement = ElementTree.Element('%s' % item[1]) celement.text = value element.append(celement) for item in self.CONF_CONTACT_PERSON_PRIMARY + self.CONF_CONTACT_ADDRESS: if item in self.CONF_CONTACT_PERSON_PRIMARY: tagname = 'ContactPersonPrimary' else: tagname = 'ContactAddress' if self.conf.has_option_with_value('contact', item[0]): if element.find(tagname) == None: subelement = ElementTree.Element(tagname) element.append(subelement) value = self.conf.get('contact', item[0]).strip() try: item[2](value) except: raise ServerConfigurationError( 'Configuration parameter [%s]->%s has an invalid value: %s.' % ('service', item[0], value)) celement = ElementTree.Element('%s' % item[1]) celement.text = value subelement.append(celement)
def finalize(self): if len(self.layers) <> 1: raise ServerConfigurationError('Layers improperly defined!') if len(self.styles) <> 1: raise ServerConfigurationError('Styles improperly defined!')
def loadXML(self, xmlfile=None, strict=False, xmlstring='', basepath=''): config = ConfigParser.SafeConfigParser() map_wms_srs = None if self.configpath: config.readfp(open(self.configpath)) if config.has_option('map', 'wms_srs'): map_wms_srs = config.get('map', 'wms_srs') tmp_map = Map(0, 0) if xmlfile: load_map(tmp_map, xmlfile, strict) elif xmlstring: load_map_from_string(tmp_map, xmlstring, strict, basepath) else: raise ServerConfigurationError( "Mapnik configuration XML is not specified - 'xmlfile' and 'xmlstring' variables are empty.\ Please set one of this variables to load mapnik map object.") # get the map scale if tmp_map.parameters: if tmp_map.parameters['scale']: self.map_scale = float(tmp_map.parameters['scale']) # parse map level attributes if tmp_map.background: self.map_attributes['bgcolor'] = tmp_map.background if tmp_map.buffer_size: self.map_attributes['buffer_size'] = tmp_map.buffer_size for lyr in tmp_map.layers: layer_section = 'layer_%s' % lyr.name layer_wms_srs = None if config.has_option(layer_section, 'wms_srs'): layer_wms_srs = config.get(layer_section, 'wms_srs') else: layer_wms_srs = map_wms_srs if config.has_option(layer_section, 'title'): lyr.title = config.get(layer_section, 'title') else: lyr.title = '' if config.has_option(layer_section, 'abstract'): lyr.abstract = config.get(layer_section, 'abstract') else: lyr.abstract = '' style_count = len(lyr.styles) if style_count == 0: raise ServerConfigurationError( "Cannot register Layer '%s' without a style" % lyr.name) elif style_count == 1: style_obj = tmp_map.find_style(lyr.styles[0]) style_name = lyr.styles[0] meta_s = extract_named_rules(style_obj) if meta_s: self.meta_styles['%s_meta' % lyr.name] = meta_s if hasattr(lyr, 'abstract'): name_ = lyr.abstract else: name_ = lyr.name meta_layer_name = '%s:%s' % (name_, '-'.join(meta_s.names)) meta_layer_name = meta_layer_name.replace(' ', '_') self.meta_styles[meta_layer_name] = meta_s meta_lyr = common.copy_layer(lyr) meta_lyr.meta_style = meta_layer_name meta_lyr.name = meta_layer_name meta_lyr.wmsextrastyles = () meta_lyr.defaultstyle = meta_layer_name meta_lyr.wms_srs = layer_wms_srs self.ordered_layers.append(meta_lyr) self.meta_layers[meta_layer_name] = meta_lyr print meta_layer_name if style_name not in self.aggregatestyles.keys( ) and style_name not in self.styles.keys(): self.register_style(style_name, style_obj) # must copy layer here otherwise we'll segfault lyr_ = common.copy_layer(lyr) lyr_.wms_srs = layer_wms_srs self.register_layer(lyr_, style_name, extrastyles=(style_name, )) elif style_count > 1: for style_name in lyr.styles: style_obj = tmp_map.find_style(style_name) meta_s = extract_named_rules(style_obj) if meta_s: self.meta_styles['%s_meta' % lyr.name] = meta_s if hasattr(lyr, 'abstract'): name_ = lyr.abstract else: name_ = lyr.name meta_layer_name = '%s:%s' % (name_, '-'.join( meta_s.names)) meta_layer_name = meta_layer_name.replace(' ', '_') self.meta_styles[meta_layer_name] = meta_s meta_lyr = common.copy_layer(lyr) meta_lyr.meta_style = meta_layer_name print meta_layer_name meta_lyr.name = meta_layer_name meta_lyr.wmsextrastyles = () meta_lyr.defaultstyle = meta_layer_name meta_lyr.wms_srs = layer_wms_srs self.ordered_layers.append(meta_lyr) self.meta_layers[meta_layer_name] = meta_lyr if style_name not in self.aggregatestyles.keys( ) and style_name not in self.styles.keys(): self.register_style(style_name, style_obj) aggregates = tuple([sty for sty in lyr.styles]) aggregates_name = '%s_aggregates' % lyr.name self.register_aggregate_style(aggregates_name, aggregates) # must copy layer here otherwise we'll segfault lyr_ = common.copy_layer(lyr) lyr_.wms_srs = layer_wms_srs self.register_layer(lyr_, aggregates_name, extrastyles=aggregates) if 'default' in aggregates: sys.stderr.write( "Warning: Multi-style layer '%s' contains a regular style named 'default'. \ This style will effectively be hidden by the 'all styles' default style for multi-style layers.\n" % lyr_.name)
def loadXML(self, xmlfile, strict=False): config = ConfigParser.SafeConfigParser() map_wms_srs = None if self.configpath: config.readfp(open(self.configpath)) if config.has_option('map', 'wms_srs'): map_wms_srs = config.get('map', 'wms_srs') tmp_map = Map(0, 0) load_map(tmp_map, xmlfile, strict) # parse map level attributes if tmp_map.background: self.map_attributes['bgcolor'] = tmp_map.background if tmp_map.buffer_size: self.map_attributes['buffer_size'] = tmp_map.buffer_size for lyr in tmp_map.layers: layer_section = 'layer_%s' % lyr.name layer_wms_srs = None if config.has_option(layer_section, 'wms_srs'): layer_wms_srs = config.get(layer_section, 'wms_srs') else: layer_wms_srs = map_wms_srs style_count = len(lyr.styles) if style_count == 0: raise ServerConfigurationError( "Cannot register Layer '%s' without a style" % lyr.name) elif style_count == 1: style_obj = tmp_map.find_style(lyr.styles[0]) style_name = lyr.styles[0] meta_s = extract_named_rules(style_obj) if meta_s: self.meta_styles['%s_meta' % lyr.name] = meta_s if hasattr(lyr, 'abstract'): name_ = lyr.abstract else: name_ = lyr.name meta_layer_name = '%s:%s' % (name_, '-'.join(meta_s.names)) meta_layer_name = meta_layer_name.replace(' ', '_') self.meta_styles[meta_layer_name] = meta_s meta_lyr = common.copy_layer(lyr) meta_lyr.meta_style = meta_layer_name meta_lyr.name = meta_layer_name meta_lyr.wmsextrastyles = () meta_lyr.defaultstyle = meta_layer_name meta_lyr.wms_srs = layer_wms_srs self.ordered_layers.append(meta_lyr) self.meta_layers[meta_layer_name] = meta_lyr print meta_layer_name if style_name not in self.aggregatestyles.keys( ) and style_name not in self.styles.keys(): self.register_style(style_name, style_obj) # must copy layer here otherwise we'll segfault lyr_ = common.copy_layer(lyr) lyr_.wms_srs = layer_wms_srs self.register_layer(lyr_, style_name, extrastyles=(style_name, )) elif style_count > 1: for style_name in lyr.styles: style_obj = tmp_map.find_style(style_name) meta_s = extract_named_rules(style_obj) if meta_s: self.meta_styles['%s_meta' % lyr.name] = meta_s if hasattr(lyr, 'abstract'): name_ = lyr.abstract else: name_ = lyr.name meta_layer_name = '%s:%s' % (name_, '-'.join( meta_s.names)) meta_layer_name = meta_layer_name.replace(' ', '_') self.meta_styles[meta_layer_name] = meta_s meta_lyr = common.copy_layer(lyr) meta_lyr.meta_style = meta_layer_name print meta_layer_name meta_lyr.name = meta_layer_name meta_lyr.wmsextrastyles = () meta_lyr.defaultstyle = meta_layer_name meta_lyr.wms_srs = layer_wms_srs self.ordered_layers.append(meta_lyr) self.meta_layers[meta_layer_name] = meta_lyr if style_name not in self.aggregatestyles.keys( ) and style_name not in self.styles.keys(): self.register_style(style_name, style_obj) aggregates = tuple([sty for sty in lyr.styles]) aggregates_name = '%s_aggregates' % lyr.name self.register_aggregate_style(aggregates_name, aggregates) # must copy layer here otherwise we'll segfault lyr_ = common.copy_layer(lyr) lyr_.wms_srs = layer_wms_srs self.register_layer(lyr_, aggregates_name, extrastyles=aggregates)