コード例 #1
0
ファイル: wms111.py プロジェクト: yalaudah/OWSLib
 def __init__(self, elem):
     """."""
     self.name = xmltag_split(elem.tag)
     # formatOptions
     self.formatOptions = [f.text for f in elem.findall('Format')]
     self.methods = []
     for verb in elem.findall('DCPType/HTTP/*'):
         url = verb.find('OnlineResource').attrib['{http://www.w3.org/1999/xlink}href']
         self.methods.append({'type' : xmltag_split(verb.tag), 'url': url})
コード例 #2
0
ファイル: wfs100.py プロジェクト: selimnairb/OWSLib
 def __init__(self, elem):
     """."""
     self.name = xmltag_split(elem.tag)
     # formatOptions
     self.formatOptions = [f.tag for f in elem.findall(nspath('ResultFormat/*'))]
     self.methods = []
     for verb in elem.findall(nspath('DCPType/HTTP/*')):
         url = verb.attrib['onlineResource']
         self.methods.append({'type' : xmltag_split(verb.tag), 'url': url})
コード例 #3
0
ファイル: wfs100.py プロジェクト: zhangmingda/OWSLib
 def __init__(self, elem):
     """."""
     self.name = xmltag_split(elem.tag)
     # formatOptions
     self.formatOptions = [f.tag for f in elem.findall(nspath('ResultFormat/*'))]
     self.methods = []
     for verb in elem.findall(nspath('DCPType/HTTP/*')):
         url = verb.attrib['onlineResource']
         self.methods.append({'type' : xmltag_split(verb.tag), 'url': url})
コード例 #4
0
ファイル: wfs100.py プロジェクト: cehbrecht/OWSLib
 def __init__(self, elem):
     """."""
     self.name = xmltag_split(elem.tag)
     # formatOptions
     self.formatOptions = [f.tag for f in elem.findall(nspath("ResultFormat/*"))]
     self.methods = []
     for verb in elem.findall(nspath("DCPType/HTTP/*")):
         url = verb.attrib["onlineResource"]
         self.methods.append({"type": xmltag_split(verb.tag), "url": url})
コード例 #5
0
ファイル: wms130.py プロジェクト: KeyproOy/OWSLib
 def __init__(self, elem):
     """."""
     self.name = xmltag_split(elem.tag)
     # formatOptions
     self.formatOptions = [f.text for f in elem.findall(nspath('Format', WMS_NAMESPACE))]
     self.methods = []
     for verb in elem.findall(nspath('DCPType/HTTP/*', WMS_NAMESPACE)):
         url = verb.find(nspath('OnlineResource', WMS_NAMESPACE)).attrib['{http://www.w3.org/1999/xlink}href']
         self.methods.append({'type': xmltag_split(verb.tag), 'url': url})
コード例 #6
0
ファイル: subwms130.py プロジェクト: ZelongY/forfun
 def __init__(self, elem):
     """."""
     self.name = xmltag_split(elem.tag)
     # formatOptions
     self.formatOptions = [
         f.text
         for f in elem.findall(subcommon.nspath('Format', WMS_NAMESPACE))
     ]
     self.methods = []
     for verb in elem.findall(
             subcommon.nspath('DCPType/HTTP/*', WMS_NAMESPACE)):
         url = verb.find(
             subcommon.nspath('OnlineResource', ns=WMS_NAMESPACE))
         xlink_ns = url.nsmap['xlink']
         url = url.attrib[subcommon.nspath('href', ns=xlink_ns)]
         self.methods.append({'type': xmltag_split(verb.tag), 'url': url})
コード例 #7
0
ファイル: ows.py プロジェクト: afarnham/owslib
    def __init__(self, elem, namespace=DEFAULT_OWS_NAMESPACE):
        self.name = elem.attrib['name']
        self.formatOptions = ['text/xml']
        methods = []
        parameters = []
        constraints = []

        for verb in elem.findall(util.nspath('DCP/HTTP/*', namespace)):
            methods.append((util.xmltag_split(verb.tag), {
                'url':
                verb.attrib[util.nspath('href', XLINK_NAMESPACE)]
            }))
        self.methods = dict(methods)

        for parameter in elem.findall(util.nspath('Parameter', namespace)):
            parameters.append((parameter.attrib['name'], {
                'values': [
                    i.text
                    for i in parameter.findall(util.nspath('Value', namespace))
                ]
            }))
        self.parameters = dict(parameters)

        for constraint in elem.findall(util.nspath('Constraint', namespace)):
            constraints.append((constraint.attrib['name'], {
                'values': [
                    i.text for i in constraint.findall(
                        util.nspath('Value', namespace))
                ]
            }))
        self.constraints = dict(constraints)
コード例 #8
0
ファイル: ows.py プロジェクト: jannefleischer/OWSLib
    def __init__(self, elem, namespace=DEFAULT_OWS_NAMESPACE):
        if 'name' not in elem.attrib:  # This is not a valid element
            return
        self.name = elem.attrib['name']
        self.formatOptions = ['text/xml']
        parameters = []
        self.methods = []
        self.constraints = []

        for verb in elem.findall(util.nspath('DCP/HTTP/*', namespace)):
            url = util.testXMLAttribute(verb, util.nspath('href', XLINK_NAMESPACE))
            if url is not None:
                verb_constraints = [Constraint(conts, namespace) for conts in verb.findall(
                    util.nspath('Constraint', namespace))]
                self.methods.append({'constraints': verb_constraints, 'type': util.xmltag_split(verb.tag), 'url': url})

        for parameter in elem.findall(util.nspath('Parameter', namespace)):
            if namespace == OWS_NAMESPACE_1_1_0:
                parameters.append((parameter.attrib['name'], {'values': [i.text for i in parameter.findall(
                    util.nspath('AllowedValues/Value', namespace))]}))
            else:
                parameters.append((parameter.attrib['name'], {'values': [i.text for i in parameter.findall(
                    util.nspath('Value', namespace))]}))
        self.parameters = dict(parameters)

        for constraint in elem.findall(util.nspath('Constraint', namespace)):
            self.constraints.append(Constraint(constraint, namespace))
コード例 #9
0
    def __init__(self, md=None):
        Owslib.iso.MD_Metadata.__init__(self, md)
        if md is not None:
            val = md.find(
                util.nspath_eval(
                    'gmd:identificationInfo/gmd:MD_DataIdentification',
                    Owslib.iso.namespaces,
                ),
            )
            val2 = md.find(
                util.nspath_eval(
                    'gmd:identificationInfo/srv:SV_ServiceIdentification',
                    Owslib.iso.namespaces,
                ),
            )

            if val is not None:
                self.identification = MD_DataIdentification_MOD(val, 'dataset')
                self.serviceidentification = None
            elif val2 is not None:
                self.identification = MD_DataIdentification_MOD(
                    val2, 'service',
                )
                self.serviceidentification = Owslib.iso.\
                    SV_ServiceIdentification(val2)
            else:
                self.identification = None
                self.serviceidentification = None

            self.identificationinfo = []
            for idinfo in md.findall(
                    util.nspath_eval(
                        'gmd:identificationInfo',
                        Owslib.iso.namespaces,
                    ),
            ):
                val = list(idinfo)[0]
                tagval = util.xmltag_split(val.tag)
                if tagval == 'MD_DataIdentification':
                    self.identificationinfo.append(
                        MD_DataIdentification_MOD(val, 'dataset'),
                    )
                elif tagval == 'MD_ServiceIdentification':
                    self.identificationinfo.append(
                        MD_DataIdentification_MOD(val, 'service'),
                    )
                elif tagval == 'SV_ServiceIdentification':
                    self.identificationinfo.append(
                        Owslib.iso.SV_ServiceIdentification(val),
                    )

            val = md.find(
                util.nspath_eval(
                    'gmd:distributionInfo/gmd:MD_Distribution',
                    Owslib.iso.namespaces,
                ),
            )
コード例 #10
0
ファイル: ows.py プロジェクト: Nathan-Wang/OWSLib
    def __init__(self,elem,namespace=DEFAULT_OWS_NAMESPACE):
        self.name = elem.attrib['name']
        self.formatOptions = ['text/xml']
        methods = []
        parameters = []
        constraints = []

        for verb in elem.findall(util.nspath('DCP/HTTP/*', namespace)):
            methods.append((util.xmltag_split(verb.tag), {'url': verb.attrib[util.nspath('href', XLINK_NAMESPACE)]}))
        self.methods = dict(methods)

        for parameter in elem.findall(util.nspath('Parameter', namespace)):
            parameters.append((parameter.attrib['name'], {'values': [i.text for i in parameter.findall(util.nspath('Value', namespace))]}))
        self.parameters = dict(parameters)

        for constraint in elem.findall(util.nspath('Constraint', namespace)):
            constraints.append((constraint.attrib['name'], {'values': [i.text for i in constraint.findall(util.nspath('Value', namespace))]}))
        self.constraints = dict(constraints)
コード例 #11
0
ファイル: ows.py プロジェクト: percious/owslib
    def __init__(self, element, namespace=None):
        self._root = element

        self.name = testXMLAttribute(self._root,'name')

        methods = []
        for verb in self._root.findall(nsp('DCP/HTTP/*', namespace)):
            url = testXMLAttribute(verb, nspath_eval('xlink:href'))
            methods.append((xmltag_split(verb.tag), {'url': url}))
        self.methods = dict(methods)

        parameters = []
        for parameter in self._root.findall(nsp('Parameter', namespace)):
            parameters.append((testXMLAttribute(parameter,'name'), {'values': [i.text for i in parameter.findall('.//' + nsp('Value', namespace))]}))
        self.parameters = dict(parameters)

        constraints = []
        for constraint in self._root.findall(nsp('Constraint', namespace)):
            constraints.append((testXMLAttribute(constraint,'name'), {'values': [i.text for i in constraint.findall('.//' + nsp('Value', namespace))]}))
        self.constraints = dict(constraints)
コード例 #12
0
ファイル: ows.py プロジェクト: CowanSM/owslib
    def __init__(self, element, ows_version='1.0.0'):
        self._root = element
        global _ows_version
        _ows_version = ows_version

        self.name = testXMLAttribute(self._root,'name')

        methods = []
        for verb in self._root.findall(ns_ows('ows:DCP/ows:HTTP/*')):
            url = testXMLAttribute(verb, nspath_eval('xlink:href'))
            methods.append((xmltag_split(verb.tag), {'url': url}))
        self.methods = dict(methods)

        parameters = []
        for parameter in self._root.findall(ns_ows('ows:Parameter')):
            parameters.append((testXMLAttribute(parameter,'name'), {'values': [i.text for i in parameter.findall(ns_ows('.//ows:Value'))]}))
        self.parameters = dict(parameters)

        constraints = []
        for constraint in self._root.findall(ns_ows('ows:Constraint')):
            constraints.append((testXMLAttribute(constraint,'name'), {'values': [i.text for i in constraint.findall(ns_ows('.//ows:Value'))]}))
        self.constraints = dict(constraints)
コード例 #13
0
ファイル: ows.py プロジェクト: ACorradini/QGIS
    def __init__(self, elem, namespace=DEFAULT_OWS_NAMESPACE):
        self.name = elem.attrib['name']
        self.formatOptions = ['text/xml']
        parameters = []
        self.methods = []
        self.constraints = []

        for verb in elem.findall(util.nspath('DCP/HTTP/*', namespace)):
            url = util.testXMLAttribute(verb, util.nspath('href', XLINK_NAMESPACE))
            if url is not None:
                verb_constraints = [Constraint(conts, namespace) for conts in verb.findall(util.nspath('Constraint', namespace))]
                self.methods.append({'constraints' : verb_constraints, 'type' : util.xmltag_split(verb.tag), 'url': url})

        for parameter in elem.findall(util.nspath('Parameter', namespace)):
            if namespace == OWS_NAMESPACE_1_1_0:
                parameters.append((parameter.attrib['name'], {'values': [i.text for i in parameter.findall(util.nspath('AllowedValues/Value', namespace))]}))
            else:
                parameters.append((parameter.attrib['name'], {'values': [i.text for i in parameter.findall(util.nspath('Value', namespace))]}))
        self.parameters = dict(parameters)

        for constraint in elem.findall(util.nspath('Constraint', namespace)):
            self.constraints.append(Constraint(constraint, namespace))
コード例 #14
0
ファイル: ows.py プロジェクト: Jonathankaoma/QGIS
    def __init__(self, elem, namespace=DEFAULT_OWS_NAMESPACE):
        self.name = elem.attrib["name"]
        self.formatOptions = ["text/xml"]
        methods = []
        parameters = []
        constraints = []

        for verb in elem.findall(util.nspath("DCP/HTTP/*", namespace)):
            methods.append((util.xmltag_split(verb.tag), {"url": verb.attrib[util.nspath("href", XLINK_NAMESPACE)]}))
        self.methods = dict(methods)

        for parameter in elem.findall(util.nspath("Parameter", namespace)):
            if namespace == OWS_NAMESPACE_1_1_0:
                parameters.append(
                    (
                        parameter.attrib["name"],
                        {"values": [i.text for i in parameter.findall(util.nspath("AllowedValues/Value", namespace))]},
                    )
                )
            else:
                parameters.append(
                    (
                        parameter.attrib["name"],
                        {"values": [i.text for i in parameter.findall(util.nspath("Value", namespace))]},
                    )
                )
        self.parameters = dict(parameters)

        for constraint in elem.findall(util.nspath("Constraint", namespace)):
            constraints.append(
                (
                    constraint.attrib["name"],
                    {"values": [i.text for i in constraint.findall(util.nspath("Value", namespace))]},
                )
            )
        self.constraints = dict(constraints)
コード例 #15
0
ファイル: ows.py プロジェクト: bird-house/OWSLib
    def __init__(self, elem, namespace=DEFAULT_OWS_NAMESPACE):
        if "name" not in elem.attrib:  # This is not a valid element
            return
        self.name = elem.attrib["name"]
        self.formatOptions = ["text/xml"]
        parameters = []
        self.methods = []
        self.constraints = []

        for verb in elem.findall(util.nspath("DCP/HTTP/*", namespace)):
            url = util.testXMLAttribute(verb, util.nspath("href", XLINK_NAMESPACE))
            if url is not None:
                verb_constraints = [
                    Constraint(conts, namespace) for conts in verb.findall(util.nspath("Constraint", namespace))
                ]
                self.methods.append({"constraints": verb_constraints, "type": util.xmltag_split(verb.tag), "url": url})

        for parameter in elem.findall(util.nspath("Parameter", namespace)):
            if namespace == OWS_NAMESPACE_1_1_0:
                parameters.append(
                    (
                        parameter.attrib["name"],
                        {"values": [i.text for i in parameter.findall(util.nspath("AllowedValues/Value", namespace))]},
                    )
                )
            else:
                parameters.append(
                    (
                        parameter.attrib["name"],
                        {"values": [i.text for i in parameter.findall(util.nspath("Value", namespace))]},
                    )
                )
        self.parameters = dict(parameters)

        for constraint in elem.findall(util.nspath("Constraint", namespace)):
            self.constraints.append(Constraint(constraint, namespace))
コード例 #16
0
    def __init__(self,
                 elem,
                 parent=None,
                 children=None,
                 index=0,
                 parse_remote_metadata=False,
                 timeout=30):
        if xmltag_split(elem.tag) != 'Layer':
            raise ValueError('%s should be a Layer' % (elem, ))

        self.parent = parent
        if parent:
            self.index = "%s.%d" % (parent.index, index)
        else:
            self.index = str(index)

        self._children = children

        self.id = self.name = testXMLValue(
            elem.find(nspath('Name', WMS_NAMESPACE)))

        # layer attributes
        self.queryable = int(elem.attrib.get('queryable', 0))
        self.cascaded = int(elem.attrib.get('cascaded', 0))
        self.opaque = int(elem.attrib.get('opaque', 0))
        self.noSubsets = int(elem.attrib.get('noSubsets', 0))
        self.fixedWidth = int(elem.attrib.get('fixedWidth', 0))
        self.fixedHeight = int(elem.attrib.get('fixedHeight', 0))

        # title is mandatory property
        self.title = None
        title = testXMLValue(elem.find(nspath('Title', WMS_NAMESPACE)))
        if title is not None:
            self.title = title.strip()

        self.abstract = testXMLValue(
            elem.find(nspath('Abstract', WMS_NAMESPACE)))

        # TODO: what is the preferred response to esri's handling of custom projections
        #       in the spatial ref definitions? see http://resources.arcgis.com/en/help/main/10.1/index.html#//00sq000000m1000000
        #       and an example (20150812) http://maps.ngdc.noaa.gov/arcgis/services/firedetects/MapServer/WMSServer?request=GetCapabilities&service=WMS

        # bboxes
        b = elem.find(nspath('EX_GeographicBoundingBox', WMS_NAMESPACE))
        self.boundingBoxWGS84 = None
        if b is not None:
            minx = b.find(nspath('westBoundLongitude', WMS_NAMESPACE))
            miny = b.find(nspath('southBoundLatitude', WMS_NAMESPACE))
            maxx = b.find(nspath('eastBoundLongitude', WMS_NAMESPACE))
            maxy = b.find(nspath('northBoundLatitude', WMS_NAMESPACE))
            box = tuple(
                map(float, [
                    minx.text if minx is not None else None,
                    miny.text if miny is not None else None,
                    maxx.text if maxx is not None else None,
                    maxy.text if maxy is not None else None
                ]))

            self.boundingBoxWGS84 = tuple(box)
        elif self.parent:
            if hasattr(self.parent, 'boundingBoxWGS84'):
                self.boundingBoxWGS84 = self.parent.boundingBoxWGS84

        # make a bbox list (of tuples)
        crs_list = []
        for bb in elem.findall(nspath('BoundingBox', WMS_NAMESPACE)):
            srs_str = bb.attrib.get('CRS', None)
            srs = Crs(srs_str)

            box = tuple(
                map(float, [
                    bb.attrib['minx'], bb.attrib['miny'], bb.attrib['maxx'],
                    bb.attrib['maxy']
                ]))
            minx, miny, maxx, maxy = box[0], box[1], box[2], box[3]

            # handle the ordering so that it always
            # returns (minx, miny, maxx, maxy)
            if srs and srs.axisorder == 'yx':
                # reverse things
                minx, miny, maxx, maxy = box[1], box[0], box[3], box[2]

            crs_list.append((
                minx,
                miny,
                maxx,
                maxy,
                srs_str,
            ))
        self.crs_list = crs_list
        # and maintain the original boundingBox attribute (first in list)
        # or the wgs84 bbox (to handle cases of incomplete parentage)
        self.boundingBox = crs_list[0] if crs_list else self.boundingBoxWGS84

        # ScaleHint
        sh = elem.find(nspath('ScaleHint', WMS_NAMESPACE))
        self.scaleHint = None
        if sh is not None:
            if 'min' in sh.attrib and 'max' in sh.attrib:
                self.scaleHint = {
                    'min': sh.attrib['min'],
                    'max': sh.attrib['max']
                }

        attribution = elem.find(nspath('Attribution', WMS_NAMESPACE))
        if attribution is not None:
            self.attribution = dict()
            title = attribution.find(nspath('Title', WMS_NAMESPACE))
            url = attribution.find(nspath('OnlineResource', WMS_NAMESPACE))
            logo = attribution.find(nspath('LogoURL', WMS_NAMESPACE))
            if title is not None:
                self.attribution['title'] = title.text
            if url is not None:
                self.attribution['url'] = url.attrib[
                    '{http://www.w3.org/1999/xlink}href']
            if logo is not None:
                self.attribution['logo_size'] = (int(logo.attrib['width']),
                                                 int(logo.attrib['height']))
                self.attribution['logo_url'] = logo.find(
                    nspath('OnlineResource', WMS_NAMESPACE)
                ).attrib['{http://www.w3.org/1999/xlink}href']

        # TODO: get this from the bbox attributes instead (deal with parents)
        # SRS options
        self.crsOptions = []

        # Copy any parent SRS options (they are inheritable properties)
        if self.parent:
            self.crsOptions = list(self.parent.crsOptions)

        # Look for SRS option attached to this layer
        if elem.find(nspath('CRS', WMS_NAMESPACE)) is not None:
            # some servers found in the wild use a single SRS
            # tag containing a whitespace separated list of SRIDs
            # instead of several SRS tags. hence the inner loop
            for srslist in [
                    x.text for x in elem.findall(nspath('CRS', WMS_NAMESPACE))
            ]:
                if srslist:
                    for srs in srslist.split():
                        self.crsOptions.append(srs)

        # Get rid of duplicate entries
        self.crsOptions = list(set(self.crsOptions))

        # Set self.crsOptions to None if the layer (and parents) had no SRS options
        if len(self.crsOptions) == 0:
            # raise ValueError('%s no SRS available!?' % (elem,))
            # Comment by D Lowe.
            # Do not raise ValueError as it is possible that a layer is purely a parent layer and does not have SRS specified. Instead set crsOptions to None
            # Comment by Jachym:
            # Do not set it to None, but to [], which will make the code
            # work further. Fixed by anthonybaxter
            self.crsOptions = []

        # Styles
        self.styles = {}

        # Copy any parent styles (they are inheritable properties)
        if self.parent:
            self.styles = self.parent.styles.copy()

        # Get the styles for this layer (items with the same name are replaced)
        for s in elem.findall(nspath('Style', WMS_NAMESPACE)):
            name = s.find(nspath('Name', WMS_NAMESPACE))
            title = s.find(nspath('Title', WMS_NAMESPACE))
            if name is None or title is None:
                raise ValueError('%s missing name or title' % (s, ))
            style = {'title': title.text}
            # legend url
            legend = s.find(nspath('LegendURL/OnlineResource', WMS_NAMESPACE))
            if legend is not None:
                style['legend'] = legend.attrib[
                    '{http://www.w3.org/1999/xlink}href']

            lgd = s.find(nspath('LegendURL', WMS_NAMESPACE))
            if lgd is not None:
                if 'width' in list(lgd.attrib.keys()):
                    style['legend_width'] = lgd.attrib.get('width')
                if 'height' in list(lgd.attrib.keys()):
                    style['legend_height'] = lgd.attrib.get('height')

                lgd_format = lgd.find(nspath('Format', WMS_NAMESPACE))
                if lgd_format is not None:
                    style['legend_format'] = lgd_format.text.strip()
            self.styles[name.text] = style

        # keywords
        self.keywords = [
            f.text
            for f in elem.findall(nspath('KeywordList/Keyword', WMS_NAMESPACE))
        ]

        # extents replaced by dimensions of name
        # comment by Soren Scott
        # <Dimension name="elevation" units="meters" default="500" multipleValues="1"
        #    nearestValue="0" current="true" unitSymbol="m">500, 490, 480</Dimension>
        # it can be repeated with the same name so ? this assumes a single one to match 1.1.1

        self.timepositions = None
        self.defaulttimeposition = None
        time_dimension = None
        for dim in elem.findall(nspath('Dimension', WMS_NAMESPACE)):
            dim_name = dim.attrib.get('name')
            if dim_name is not None and dim_name.lower() == 'time':
                time_dimension = dim
        if time_dimension is not None:
            self.timepositions = time_dimension.text.split(
                ',') if time_dimension.text else None
            self.defaulttimeposition = time_dimension.attrib.get(
                'default', None)

        # Elevations - available vertical levels
        self.elevations = None
        elev_dimension = None
        for dim in elem.findall(nspath('Dimension', WMS_NAMESPACE)):
            if dim.attrib.get('elevation') is not None:
                elev_dimension = dim
        if elev_dimension is not None:
            self.elevations = [
                e.strip() for e in elev_dimension.text.split(',')
            ] if elev_dimension.text else None

        # and now capture the dimensions as more generic things (and custom things)
        self.dimensions = {}
        for dim in elem.findall(nspath('Dimension', WMS_NAMESPACE)):
            dim_name = dim.attrib.get('name')
            dim_data = {}
            for k, v in six.iteritems(dim.attrib):
                if k != 'name':
                    dim_data[k] = v
            # single values and ranges are not differentiated here
            dim_data['values'] = dim.text.strip().split(
                ',') if dim.text.strip() else None
            self.dimensions[dim_name] = dim_data

        # MetadataURLs
        self.metadataUrls = []
        for m in elem.findall(nspath('MetadataURL', WMS_NAMESPACE)):
            metadataUrl = {
                'type':
                testXMLValue(m.attrib['type'], attrib=True),
                'format':
                testXMLValue(m.find(nspath('Format', WMS_NAMESPACE))),
                'url':
                testXMLValue(m.find(nspath('OnlineResource', WMS_NAMESPACE)).
                             attrib['{http://www.w3.org/1999/xlink}href'],
                             attrib=True)
            }

            if metadataUrl[
                    'url'] is not None and parse_remote_metadata:  # download URL
                try:
                    content = openURL(metadataUrl['url'], timeout=timeout)
                    doc = etree.parse(content)
                    if metadataUrl['type'] is not None:
                        if metadataUrl['type'] == 'FGDC':
                            metadataUrl['metadata'] = Metadata(doc)
                        if metadataUrl['type'] == 'TC211':
                            metadataUrl['metadata'] = MD_Metadata(doc)
                except Exception:
                    metadataUrl['metadata'] = None

            self.metadataUrls.append(metadataUrl)

        # DataURLs
        self.dataUrls = []
        for m in elem.findall(nspath('DataURL', WMS_NAMESPACE)):
            dataUrl = {
                'format':
                m.find(nspath('Format', WMS_NAMESPACE)).text.strip(),
                'url':
                m.find(nspath('OnlineResource', WMS_NAMESPACE)).
                attrib['{http://www.w3.org/1999/xlink}href']
            }
            self.dataUrls.append(dataUrl)

        # FeatureListURLs
        self.featureListUrls = []
        for m in elem.findall(nspath('FeatureListURL', WMS_NAMESPACE)):
            featureUrl = {
                'format':
                m.find(nspath('Format', WMS_NAMESPACE)).text.strip(),
                'url':
                m.find(nspath('OnlineResource', WMS_NAMESPACE)).
                attrib['{http://www.w3.org/1999/xlink}href']
            }
            self.featureListUrls.append(featureUrl)

        self.layers = []
        for child in elem.findall(nspath('Layer', WMS_NAMESPACE)):
            self.layers.append(ContentMetadata(child, self))
コード例 #17
0
    def __init__(self,
                 elem,
                 parent=None,
                 children=None,
                 index=0,
                 parse_remote_metadata=False,
                 timeout=30):
        if xmltag_split(elem.tag) != 'Layer':
            raise ValueError('%s should be a Layer' % (elem, ))

        self.parent = parent
        if parent:
            self.index = "%s.%d" % (parent.index, index)
        else:
            self.index = str(index)

        self._children = children

        self.id = self.name = testXMLValue(
            elem.find(subcommon.nspath('Name', ns=WMS_NAMESPACE)))

        # layer attributes
        self.queryable = int(elem.attrib.get('queryable', 0))
        self.cascaded = int(elem.attrib.get('cascaded', 0))
        self.opaque = int(elem.attrib.get('opaque', 0))
        self.noSubsets = int(elem.attrib.get('noSubsets', 0))
        self.fixedWidth = int(elem.attrib.get('fixedWidth', 0))
        self.fixedHeight = int(elem.attrib.get('fixedHeight', 0))

        # title is mandatory property
        self.title = None
        title = testXMLValue(
            elem.find(subcommon.nspath('Title', ns=WMS_NAMESPACE)))
        if title is not None:
            self.title = title.strip()

        self.abstract = testXMLValue(
            elem.find(subcommon.nspath('Abstract', ns=WMS_NAMESPACE)))

        # keywords
        self.keywords = [
            f.text for f in elem.findall(
                subcommon.nspath('KeywordList/Keyword', ns=WMS_NAMESPACE))
        ]

        # ScaleHint
        sh = elem.find(subcommon.nspath('ScaleHint', WMS_NAMESPACE))
        if sh is not None:
            self.scaleHint = {}
            if 'min' in sh.attrib:
                self.scaleHint['min'] = sh.attrib['min']
            if 'max' in sh.attrib:
                self.scaleHint['max'] = sh.attrib['max']
        # If not exist, try to inherit it from its parent
        elif self.parent:
            self.scaleHint = self.parent.scaleHint
        else:
            self.scaleHint = None

        # Attribution
        attribution = elem.find(subcommon.nspath('Attribution', WMS_NAMESPACE))
        if attribution is not None:
            self.attribution = dict()
            self.attribution['title'] = self.attribution[
                'url'] = self.attribution['logo_size'] = self.attribution[
                    'logo_format'] = self.attribution['logo_url'] = None
            title = attribution.find(subcommon.nspath('Title', WMS_NAMESPACE))
            url = attribution.find(
                subcommon.nspath('OnlineResource', WMS_NAMESPACE))
            logo = attribution.find(subcommon.nspath('LogoURL', WMS_NAMESPACE))
            if title is not None:
                self.attribution['title'] = title.text
            if url is not None:
                self.attribution['url'] = url.attrib[
                    '{http://www.w3.org/1999/xlink}href']
            if logo is not None:
                self.attribution['logo_format'] = logo.find(
                    subcommon.nspath('Format', WMS_NAMESPACE))
                self.attribution['logo_size'] = (int(logo.attrib['width']),
                                                 int(logo.attrib['height']))
                self.attribution['logo_url'] = logo.find(
                    subcommon.nspath('OnlineResource', WMS_NAMESPACE)
                ).attrib['{http://www.w3.org/1999/xlink}href']
        # If not exist, try to inherit it from its parent
        elif self.parent:
            self.attribution = self.parent.attribution
        else:
            self.attribution = None

        # LatLonBoundingBox
        b = elem.find(subcommon.nspath('LatLonBoundingBox', ns=WMS_NAMESPACE))
        if b is not None:
            self.boundingBoxWGS84 = (
                float(b.attrib['minx']),
                float(b.attrib['miny']),
                float(b.attrib['maxx']),
                float(b.attrib['maxy']),
            )
        # If not exist, try to inherit it from its parent
        elif self.parent:
            self.boundingBoxWGS84 = self.parent.boundingBoxWGS84
        else:
            self.boundingBoxWGS84 = None

        # BoundingBox
        b = elem.find(subcommon.nspath('BoundingBox', ns=WMS_NAMESPACE))
        self.boundingBox = None
        if b is not None:
            try:  # sometimes the SRS attribute is (wrongly) not provided
                srs = b.attrib['SRS']
            except KeyError:
                srs = None
            self.boundingBox = (
                float(b.attrib['minx']),
                float(b.attrib['miny']),
                float(b.attrib['maxx']),
                float(b.attrib['maxy']),
                srs,
            )
        elif self.parent:
            if hasattr(self.parent, 'boundingBox'):
                self.boundingBox = self.parent.boundingBox

        # SRS options
        self.crsOptions = []

        # Copy any parent SRS options (they are inheritable properties)
        if self.parent:
            self.crsOptions = list(self.parent.crsOptions)

        # Look for SRS option attached to this layer
        if elem.find(subcommon.nspath('SRS', ns=WMS_NAMESPACE)) is not None:
            ## some servers found in the wild use a single SRS
            ## tag containing a whitespace separated list of SRIDs
            ## instead of several SRS tags. hence the inner loop
            for srslist in [
                    x.text for x in elem.findall(
                        subcommon.nspath('SRS', ns=WMS_NAMESPACE))
            ]:
                if srslist:
                    for srs in srslist.split():
                        self.crsOptions.append(srs)

        #Get rid of duplicate entries
        self.crsOptions = list(set(self.crsOptions))

        #Set self.crsOptions to None if the layer (and parents) had no SRS options
        if len(self.crsOptions) == 0:
            #raise ValueError('%s no SRS available!?' % (elem,))
            #Comment by D Lowe.
            #Do not raise ValueError as it is possible that a layer is purely a parent layer and does not have SRS specified. Instead set crsOptions to None
            # Comment by Jachym:
            # Do not set it to None, but to [], which will make the code
            # work further. Fixed by anthonybaxter
            self.crsOptions = []

        #Styles
        self.styles = {}

        #Copy any parent styles (they are inheritable properties)
        if self.parent:
            self.styles = self.parent.styles.copy()

        #Get the styles for this layer (items with the same name are replaced)
        for s in elem.findall(subcommon.nspath('Style', ns=WMS_NAMESPACE)):
            name = s.find(subcommon.nspath('Name', ns=WMS_NAMESPACE))
            title = s.find(subcommon.nspath('Title', ns=WMS_NAMESPACE))
            if name is None or title is None:
                raise ValueError('%s missing name or title' % (s, ))
            style = {'title': title.text}
            # legend url
            legend = s.find(
                subcommon.nspath('LegendURL/OnlineResource', ns=WMS_NAMESPACE))
            if legend is not None:
                style['legend'] = legend.attrib[
                    '{http://www.w3.org/1999/xlink}href']
            self.styles[name.text] = style

        # timepositions - times for which data is available.
        self.timepositions = None
        self.defaulttimeposition = None
        for extent in elem.findall(subcommon.nspath('Extent',
                                                    ns=WMS_NAMESPACE)):
            if extent.attrib.get("name").lower() == 'time':
                if extent.text:
                    self.timepositions = extent.text.split(',')
                    self.defaulttimeposition = extent.attrib.get("default")
                    break

        # Elevations - available vertical levels
        self.elevations = None
        for extent in elem.findall(subcommon.nspath('Extent',
                                                    ns=WMS_NAMESPACE)):
            if extent.attrib.get("name").lower() == 'elevation':
                if extent.text:
                    self.elevations = extent.text.split(',')
                    break

        # MetadataURLs
        self.metadataUrls = []
        for m in elem.findall(subcommon.nspath('MetadataURL',
                                               ns=WMS_NAMESPACE)):
            metadataUrl = {
                'type':
                testXMLValue(m.attrib['type'], attrib=True),
                'format':
                testXMLValue(
                    m.find(subcommon.nspath('Format', ns=WMS_NAMESPACE))),
                'url':
                testXMLValue(m.find(
                    subcommon.nspath('OnlineResource', ns=WMS_NAMESPACE)).
                             attrib['{http://www.w3.org/1999/xlink}href'],
                             attrib=True)
            }

            if metadataUrl[
                    'url'] is not None and parse_remote_metadata:  # download URL
                try:
                    content = openURL(metadataUrl['url'], timeout=timeout)
                    doc = etree.parse(content)
                    if metadataUrl['type'] is not None:
                        if metadataUrl['type'] == 'FGDC':
                            metadataUrl['metadata'] = Metadata(doc)
                        if metadataUrl['type'] == 'TC211':
                            metadataUrl['metadata'] = MD_Metadata(doc)
                except Exception:
                    metadataUrl['metadata'] = None

            self.metadataUrls.append(metadataUrl)

        # DataURLs
        self.dataUrls = []
        for m in elem.findall(subcommon.nspath('DataURL', ns=WMS_NAMESPACE)):
            dataUrl = {
                'format':
                m.find(subcommon.nspath('Format',
                                        ns=WMS_NAMESPACE)).text.strip(),
                'url':
                m.find(subcommon.nspath('OnlineResource', ns=WMS_NAMESPACE)).
                attrib['{http://www.w3.org/1999/xlink}href']
            }
            self.dataUrls.append(dataUrl)

        self.layers = []
        for child in elem.findall(subcommon.nspath('Layer', ns=WMS_NAMESPACE)):
            self.layers.append(ContentMetadata(child, self))
コード例 #18
0
ファイル: wms130.py プロジェクト: KeyproOy/OWSLib
    def __init__(self, elem, parent=None, children=None, index=0, parse_remote_metadata=False, timeout=30):
        if xmltag_split(elem.tag) != 'Layer':
            raise ValueError('%s should be a Layer' % (elem,))

        self.parent = parent
        if parent:
            self.index = "%s.%d" % (parent.index, index)
        else:
            self.index = str(index)

        self._children = children

        self.id = self.name = testXMLValue(elem.find(nspath('Name', WMS_NAMESPACE)))

        # layer attributes
        self.queryable = int(elem.attrib.get('queryable', 0))
        self.cascaded = int(elem.attrib.get('cascaded', 0))
        self.opaque = int(elem.attrib.get('opaque', 0))
        self.noSubsets = int(elem.attrib.get('noSubsets', 0))
        self.fixedWidth = int(elem.attrib.get('fixedWidth', 0))
        self.fixedHeight = int(elem.attrib.get('fixedHeight', 0))

        # title is mandatory property
        self.title = None
        title = testXMLValue(elem.find(nspath('Title', WMS_NAMESPACE)))
        if title is not None:
            self.title = title.strip()

        self.abstract = testXMLValue(elem.find(nspath('Abstract', WMS_NAMESPACE)))

        # TODO: what is the preferred response to esri's handling of custom projections
        #       in the spatial ref definitions? see http://resources.arcgis.com/en/help/main/10.1/index.html#//00sq000000m1000000
        #       and an example (20150812) http://maps.ngdc.noaa.gov/arcgis/services/firedetects/MapServer/WMSServer?request=GetCapabilities&service=WMS

        # bboxes
        b = elem.find(nspath('EX_GeographicBoundingBox', WMS_NAMESPACE))
        self.boundingBoxWGS84 = None
        if b is not None:
            minx = b.find(nspath('westBoundLongitude', WMS_NAMESPACE))
            miny = b.find(nspath('southBoundLatitude', WMS_NAMESPACE))
            maxx = b.find(nspath('eastBoundLongitude', WMS_NAMESPACE))
            maxy = b.find(nspath('northBoundLatitude', WMS_NAMESPACE))
            box = tuple(map(float, [minx.text if minx is not None else None,
                            miny.text if miny is not None else None,
                            maxx.text if maxx is not None else None,
                            maxy.text if maxy is not None else None]))

            self.boundingBoxWGS84 = tuple(box)
        elif self.parent:
            if hasattr(self.parent, 'boundingBoxWGS84'):
                self.boundingBoxWGS84 = self.parent.boundingBoxWGS84

        # make a bbox list (of tuples)
        crs_list = []
        for bb in elem.findall(nspath('BoundingBox', WMS_NAMESPACE)):
            srs_str = bb.attrib.get('CRS', None)
            srs = Crs(srs_str)

            box = tuple(map(float, [bb.attrib['minx'],
                        bb.attrib['miny'],
                        bb.attrib['maxx'],
                        bb.attrib['maxy']]
            ))
            minx, miny, maxx, maxy = box[0], box[1], box[2], box[3]

            # handle the ordering so that it always
            # returns (minx, miny, maxx, maxy)
            if srs and srs.axisorder == 'yx':
                # reverse things
                minx, miny, maxx, maxy = box[1], box[0], box[3], box[2]

            crs_list.append((
                minx, miny, maxx, maxy,
                srs_str,
            ))
        self.crs_list = crs_list
        # and maintain the original boundingBox attribute (first in list)
        # or the wgs84 bbox (to handle cases of incomplete parentage)
        self.boundingBox = crs_list[0] if crs_list else self.boundingBoxWGS84

        # ScaleHint
        sh = elem.find(nspath('ScaleHint', WMS_NAMESPACE))
        self.scaleHint = None
        if sh is not None:
            if 'min' in sh.attrib and 'max' in sh.attrib:
                self.scaleHint = {'min': sh.attrib['min'], 'max': sh.attrib['max']}

        attribution = elem.find(nspath('Attribution', WMS_NAMESPACE))
        if attribution is not None:
            self.attribution = dict()
            title = attribution.find(nspath('Title', WMS_NAMESPACE))
            url = attribution.find(nspath('OnlineResource', WMS_NAMESPACE))
            logo = attribution.find(nspath('LogoURL', WMS_NAMESPACE))
            if title is not None:
                self.attribution['title'] = title.text
            if url is not None:
                self.attribution['url'] = url.attrib['{http://www.w3.org/1999/xlink}href']
            if logo is not None:
                self.attribution['logo_size'] = (int(logo.attrib['width']), int(logo.attrib['height']))
                self.attribution['logo_url'] = logo.find(nspath('OnlineResource', WMS_NAMESPACE)).attrib['{http://www.w3.org/1999/xlink}href']

        # TODO: get this from the bbox attributes instead (deal with parents)
        # SRS options
        self.crsOptions = []

        # Copy any parent SRS options (they are inheritable properties)
        if self.parent:
            self.crsOptions = list(self.parent.crsOptions)

        # Look for SRS option attached to this layer
        if elem.find(nspath('CRS', WMS_NAMESPACE)) is not None:
            # some servers found in the wild use a single SRS
            # tag containing a whitespace separated list of SRIDs
            # instead of several SRS tags. hence the inner loop
            for srslist in map(lambda x: x.text, elem.findall(nspath('CRS', WMS_NAMESPACE))):
                if srslist:
                    for srs in srslist.split():
                        self.crsOptions.append(srs)

        # Get rid of duplicate entries
        self.crsOptions = list(set(self.crsOptions))

        # Set self.crsOptions to None if the layer (and parents) had no SRS options
        if len(self.crsOptions) == 0:
            # raise ValueError('%s no SRS available!?' % (elem,))
            # Comment by D Lowe.
            # Do not raise ValueError as it is possible that a layer is purely a parent layer and does not have SRS specified. Instead set crsOptions to None
            # Comment by Jachym:
            # Do not set it to None, but to [], which will make the code
            # work further. Fixed by anthonybaxter
            self.crsOptions = []

        # Styles
        self.styles = {}

        # Copy any parent styles (they are inheritable properties)
        if self.parent:
            self.styles = self.parent.styles.copy()

        # Get the styles for this layer (items with the same name are replaced)
        for s in elem.findall(nspath('Style', WMS_NAMESPACE)):
            name = s.find(nspath('Name', WMS_NAMESPACE))
            title = s.find(nspath('Title', WMS_NAMESPACE))
            if name is None or title is None:
                raise ValueError('%s missing name or title' % (s,))
            style = {'title': title.text}
            # legend url
            legend = s.find(nspath('LegendURL/OnlineResource', WMS_NAMESPACE))
            if legend is not None:
                style['legend'] = legend.attrib['{http://www.w3.org/1999/xlink}href']

            lgd = s.find(nspath('LegendURL', WMS_NAMESPACE))
            if lgd is not None:
                if 'width' in lgd.attrib.keys():
                    style['legend_width'] = lgd.attrib.get('width')
                if 'height' in lgd.attrib.keys():
                    style['legend_height'] = lgd.attrib.get('height')

                lgd_format = lgd.find(nspath('Format', WMS_NAMESPACE))
                if lgd_format is not None:
                    style['legend_format'] = lgd_format.text.strip()
            self.styles[name.text] = style

        # keywords
        self.keywords = [f.text for f in elem.findall(nspath('KeywordList/Keyword', WMS_NAMESPACE))]

        # extents replaced by dimensions of name
        # comment by Soren Scott
        # <Dimension name="elevation" units="meters" default="500" multipleValues="1"
        #    nearestValue="0" current="true" unitSymbol="m">500, 490, 480</Dimension>
        # it can be repeated with the same name so ? this assumes a single one to match 1.1.1

        self.timepositions = None
        self.defaulttimeposition = None
        time_dimension = None
        for dim in elem.findall(nspath('Dimension', WMS_NAMESPACE)):
            if dim.attrib.get('name') is not None:
                time_dimension = dim
        if time_dimension is not None:
            self.timepositions = time_dimension.text.split(',') if time_dimension.text else None
            self.defaulttimeposition = time_dimension.attrib.get('default', None)

        # Elevations - available vertical levels
        self.elevations = None
        elev_dimension = None
        for dim in elem.findall(nspath('Dimension', WMS_NAMESPACE)):
            if dim.attrib.get('elevation') is not None:
                elev_dimension = dim
        if elev_dimension is not None:
            self.elevations = [e.strip() for e in elev_dimension.text.split(',')] if elev_dimension.text else None

        # and now capture the dimensions as more generic things (and custom things)
        self.dimensions = {}
        for dim in elem.findall(nspath('Dimension', WMS_NAMESPACE)):
            dim_name = dim.attrib.get('name')
            dim_data = {}
            for k, v in six.iteritems(dim.attrib):
                if k != 'name':
                    dim_data[k] = v
            # single values and ranges are not differentiated here
            dim_data['values'] = dim.text.strip().split(',') if dim.text.strip() else None
            self.dimensions[dim_name] = dim_data

        # MetadataURLs
        self.metadataUrls = []
        for m in elem.findall(nspath('MetadataURL', WMS_NAMESPACE)):
            metadataUrl = {
                'type': testXMLValue(m.attrib['type'], attrib=True),
                'format': testXMLValue(m.find(nspath('Format', WMS_NAMESPACE))),
                'url': testXMLValue(m.find(nspath('OnlineResource', WMS_NAMESPACE)).attrib['{http://www.w3.org/1999/xlink}href'], attrib=True)
            }

            if metadataUrl['url'] is not None and parse_remote_metadata:  # download URL
                try:
                    content = openURL(metadataUrl['url'], timeout=timeout)
                    doc = etree.parse(content)
                    if metadataUrl['type'] is not None:
                        if metadataUrl['type'] == 'FGDC':
                            metadataUrl['metadata'] = Metadata(doc)
                        if metadataUrl['type'] == 'TC211':
                            metadataUrl['metadata'] = MD_Metadata(doc)
                except Exception:
                    metadataUrl['metadata'] = None

            self.metadataUrls.append(metadataUrl)

        # DataURLs
        self.dataUrls = []
        for m in elem.findall(nspath('DataURL', WMS_NAMESPACE)):
            dataUrl = {
                'format': m.find(nspath('Format', WMS_NAMESPACE)).text.strip(),
                'url': m.find(nspath('OnlineResource', WMS_NAMESPACE)).attrib['{http://www.w3.org/1999/xlink}href']
            }
            self.dataUrls.append(dataUrl)

        # FeatureListURLs
        self.featureListUrls = []
        for m in elem.findall(nspath('FeatureListURL', WMS_NAMESPACE)):
            featureUrl = {
                'format': m.find(nspath('Format', WMS_NAMESPACE)).text.strip(),
                'url': m.find(nspath('OnlineResource', WMS_NAMESPACE)).attrib['{http://www.w3.org/1999/xlink}href']
            }
            self.featureListUrls.append(featureUrl)

        self.layers = []
        for child in elem.findall(nspath('Layer', WMS_NAMESPACE)):
            self.layers.append(ContentMetadata(child, self))
コード例 #19
0
ファイル: iso.py プロジェクト: wsidl/OWSLib
    def __init__(self, md=None):

        if md is None:
            self.xml = None
            self.identifier = None
            self.parentidentifier = None
            self.language = None
            self.dataseturi = None
            self.languagecode = None
            self.datestamp = None
            self.charset = None
            self.hierarchy = None
            self.contact = []
            self.datetimestamp = None
            self.stdname = None
            self.stdver = None
            self.referencesystem = None
            self.identification = None
            self.serviceidentification = None
            self.identificationinfo = []
            self.distribution = None
            self.dataquality = None
        else:
            if hasattr(md, 'getroot'):  # standalone document
                self.xml = etree.tostring(md.getroot())
            else:  # part of a larger document
                self.xml = etree.tostring(md)

            val = md.find(util.nspath_eval('gmd:fileIdentifier/gco:CharacterString', namespaces))
            self.identifier = util.testXMLValue(val)

            val = md.find(util.nspath_eval('gmd:parentIdentifier/gco:CharacterString', namespaces))
            self.parentidentifier = util.testXMLValue(val)

            val = md.find(util.nspath_eval('gmd:language/gco:CharacterString', namespaces))
            self.language = util.testXMLValue(val)
            
            val = md.find(util.nspath_eval('gmd:dataSetURI/gco:CharacterString', namespaces))
            self.dataseturi = util.testXMLValue(val)

            val = md.find(util.nspath_eval('gmd:language/gmd:LanguageCode', namespaces))
            self.languagecode = util.testXMLValue(val)
            
            val = md.find(util.nspath_eval('gmd:dateStamp/gco:Date', namespaces))
            self.datestamp = util.testXMLValue(val)

            if not self.datestamp:
                val = md.find(util.nspath_eval('gmd:dateStamp/gco:DateTime', namespaces))
                self.datestamp = util.testXMLValue(val)

            self.charset = _testCodeListValue(md.find(util.nspath_eval('gmd:characterSet/gmd:MD_CharacterSetCode', namespaces)))
      
            self.hierarchy = _testCodeListValue(md.find(util.nspath_eval('gmd:hierarchyLevel/gmd:MD_ScopeCode', namespaces)))

            self.contact = []
            for i in md.findall(util.nspath_eval('gmd:contact/gmd:CI_ResponsibleParty', namespaces)):
                o = CI_ResponsibleParty(i)
                self.contact.append(o)
            
            val = md.find(util.nspath_eval('gmd:dateStamp/gco:DateTime', namespaces))
            self.datetimestamp = util.testXMLValue(val)
            
            val = md.find(util.nspath_eval('gmd:metadataStandardName/gco:CharacterString', namespaces))
            self.stdname = util.testXMLValue(val)

            val = md.find(util.nspath_eval('gmd:metadataStandardVersion/gco:CharacterString', namespaces))
            self.stdver = util.testXMLValue(val)

            val = md.find(util.nspath_eval('gmd:referenceSystemInfo/gmd:MD_ReferenceSystem', namespaces))
            if val is not None:
                self.referencesystem = MD_ReferenceSystem(val)
            else:
                self.referencesystem = None

            # TODO: merge .identificationinfo into .identification
            #warnings.warn(
            #    'the .identification and .serviceidentification properties will merge into '
            #    '.identification being a list of properties.  This is currently implemented '
            #    'in .identificationinfo.  '
            #    'Please see https://github.com/geopython/OWSLib/issues/38 for more information',
            #    FutureWarning)

            val = md.find(util.nspath_eval('gmd:identificationInfo/gmd:MD_DataIdentification', namespaces))
            val2 = md.find(util.nspath_eval('gmd:identificationInfo/srv:SV_ServiceIdentification', namespaces))

            if val is not None:
                self.identification = MD_DataIdentification(val, 'dataset')
                self.serviceidentification = None
            elif val2 is not None:
                self.identification = MD_DataIdentification(val2, 'service')
                self.serviceidentification = SV_ServiceIdentification(val2)
            else:
                self.identification = None
                self.serviceidentification = None

            self.identificationinfo = []
            for idinfo in md.findall(util.nspath_eval('gmd:identificationInfo', namespaces)):
                val = list(idinfo)[0]
                tagval = util.xmltag_split(val.tag)
                if tagval == 'MD_DataIdentification': 
                    self.identificationinfo.append(MD_DataIdentification(val, 'dataset'))
                elif tagval == 'MD_ServiceIdentification': 
                    self.identificationinfo.append(MD_DataIdentification(val, 'service'))
                elif tagval == 'SV_ServiceIdentification': 
                    self.identificationinfo.append(SV_ServiceIdentification(val))

            val = md.find(util.nspath_eval('gmd:distributionInfo/gmd:MD_Distribution', namespaces))

            if val is not None:
                self.distribution = MD_Distribution(val)
            else:
                self.distribution = None
            
            val = md.find(util.nspath_eval('gmd:dataQualityInfo/gmd:DQ_DataQuality', namespaces))
            if val is not None:
                self.dataquality = DQ_DataQuality(val)
            else:
                self.dataquality = None
コード例 #20
0
ファイル: iso.py プロジェクト: zhangmingda/OWSLib
    def __init__(self, md=None):

        if md is None:
            self.xml = None
            self.identifier = None
            self.parentidentifier = None
            self.language = None
            self.dataseturi = None
            self.languagecode = None
            self.datestamp = None
            self.charset = None
            self.hierarchy = None
            self.contact = []
            self.datetimestamp = None
            self.stdname = None
            self.stdver = None
            self.referencesystem = None
            self.identification = None
            self.serviceidentification = None
            self.identificationinfo = []
            self.distribution = None
            self.dataquality = None
        else:
            if hasattr(md, 'getroot'):  # standalone document
                self.xml = etree.tostring(md.getroot())
            else:  # part of a larger document
                self.xml = etree.tostring(md)

            val = md.find(
                util.nspath_eval('gmd:fileIdentifier/gco:CharacterString',
                                 namespaces))
            self.identifier = util.testXMLValue(val)

            val = md.find(
                util.nspath_eval('gmd:parentIdentifier/gco:CharacterString',
                                 namespaces))
            self.parentidentifier = util.testXMLValue(val)

            val = md.find(
                util.nspath_eval('gmd:language/gco:CharacterString',
                                 namespaces))
            self.language = util.testXMLValue(val)

            val = md.find(
                util.nspath_eval('gmd:dataSetURI/gco:CharacterString',
                                 namespaces))
            self.dataseturi = util.testXMLValue(val)

            val = md.find(
                util.nspath_eval('gmd:language/gmd:LanguageCode', namespaces))
            self.languagecode = util.testXMLAttribute(val, 'codeListValue')

            val = md.find(
                util.nspath_eval('gmd:dateStamp/gco:Date', namespaces))
            self.datestamp = util.testXMLValue(val)

            if not self.datestamp:
                val = md.find(
                    util.nspath_eval('gmd:dateStamp/gco:DateTime', namespaces))
                self.datestamp = util.testXMLValue(val)

            self.charset = _testCodeListValue(
                md.find(
                    util.nspath_eval(
                        'gmd:characterSet/gmd:MD_CharacterSetCode',
                        namespaces)))

            self.hierarchy = _testCodeListValue(
                md.find(
                    util.nspath_eval('gmd:hierarchyLevel/gmd:MD_ScopeCode',
                                     namespaces)))

            self.contact = []
            for i in md.findall(
                    util.nspath_eval('gmd:contact/gmd:CI_ResponsibleParty',
                                     namespaces)):
                o = CI_ResponsibleParty(i)
                self.contact.append(o)

            val = md.find(
                util.nspath_eval('gmd:dateStamp/gco:DateTime', namespaces))
            self.datetimestamp = util.testXMLValue(val)

            val = md.find(
                util.nspath_eval(
                    'gmd:metadataStandardName/gco:CharacterString',
                    namespaces))
            self.stdname = util.testXMLValue(val)

            val = md.find(
                util.nspath_eval(
                    'gmd:metadataStandardVersion/gco:CharacterString',
                    namespaces))
            self.stdver = util.testXMLValue(val)

            val = md.find(
                util.nspath_eval(
                    'gmd:referenceSystemInfo/gmd:MD_ReferenceSystem',
                    namespaces))
            if val is not None:
                self.referencesystem = MD_ReferenceSystem(val)
            else:
                self.referencesystem = None

            # TODO: merge .identificationinfo into .identification
            warnings.warn(
                'the .identification and .serviceidentification properties will merge into '
                '.identification being a list of properties.  This is currently implemented '
                'in .identificationinfo.  '
                'Please see https://github.com/geopython/OWSLib/issues/38 for more information',
                FutureWarning)

            val = md.find(
                util.nspath_eval(
                    'gmd:identificationInfo/gmd:MD_DataIdentification',
                    namespaces))
            val2 = md.find(
                util.nspath_eval(
                    'gmd:identificationInfo/srv:SV_ServiceIdentification',
                    namespaces))

            if val is not None:
                self.identification = MD_DataIdentification(val, 'dataset')
                self.serviceidentification = None
            elif val2 is not None:
                self.identification = MD_DataIdentification(val2, 'service')
                self.serviceidentification = SV_ServiceIdentification(val2)
            else:
                self.identification = None
                self.serviceidentification = None

            self.identificationinfo = []
            for idinfo in md.findall(
                    util.nspath_eval('gmd:identificationInfo', namespaces)):
                if len(idinfo) > 0:
                    val = list(idinfo)[0]
                    tagval = util.xmltag_split(val.tag)
                    if tagval == 'MD_DataIdentification':
                        self.identificationinfo.append(
                            MD_DataIdentification(val, 'dataset'))
                    elif tagval == 'MD_ServiceIdentification':
                        self.identificationinfo.append(
                            MD_DataIdentification(val, 'service'))
                    elif tagval == 'SV_ServiceIdentification':
                        self.identificationinfo.append(
                            SV_ServiceIdentification(val))

            val = md.find(
                util.nspath_eval('gmd:distributionInfo/gmd:MD_Distribution',
                                 namespaces))

            if val is not None:
                self.distribution = MD_Distribution(val)
            else:
                self.distribution = None

            val = md.find(
                util.nspath_eval('gmd:dataQualityInfo/gmd:DQ_DataQuality',
                                 namespaces))
            if val is not None:
                self.dataquality = DQ_DataQuality(val)
            else:
                self.dataquality = None
コード例 #21
0
    def __init__(self,
                 elem,
                 parent=None,
                 children=None,
                 index=0,
                 parse_remote_metadata=False,
                 timeout=30):
        if xmltag_split(elem.tag) != 'Layer':
            raise ValueError('%s should be a Layer' % (elem, ))

        self.parent = parent
        if parent:
            self.index = "%s.%d" % (parent.index, index)
        else:
            self.index = str(index)

        self._children = children

        self.id = self.name = testXMLValue(
            elem.find(subcommon.nspath('Name', ns=WMS_NAMESPACE)))

        # layer attributes
        self.queryable = int(elem.attrib.get('queryable', 0))
        self.cascaded = int(elem.attrib.get('cascaded', 0))
        self.opaque = int(elem.attrib.get('opaque', 0))
        self.noSubsets = int(elem.attrib.get('noSubsets', 0))
        self.fixedWidth = int(elem.attrib.get('fixedWidth', 0))
        self.fixedHeight = int(elem.attrib.get('fixedHeight', 0))

        # title is mandatory property
        self.title = None
        title = testXMLValue(
            elem.find(subcommon.nspath('Title', ns=WMS_NAMESPACE)))
        if title is not None:
            self.title = title.strip()

        self.abstract = testXMLValue(
            elem.find(subcommon.nspath('Abstract', ns=WMS_NAMESPACE)))
        # keywords
        self.keywords = [
            f.text for f in elem.findall(
                subcommon.nspath('KeywordList/Keyword', ns=WMS_NAMESPACE))
        ]

        # ScaleHint
        sh = elem.find(subcommon.nspath('ScaleHint', ns=WMS_NAMESPACE))
        self.scaleHint = None
        if sh is not None:
            if 'min' in sh.attrib and 'max' in sh.attrib:
                self.scaleHint = {
                    'min': sh.attrib['min'],
                    'max': sh.attrib['max']
                }

        attribution = elem.find(
            subcommon.nspath('Attribution', ns=WMS_NAMESPACE))
        if attribution is not None:
            self.attribution = dict()
            title = attribution.find(
                subcommon.nspath('Title', ns=WMS_NAMESPACE))
            url = attribution.find(
                subcommon.nspath('OnlineResource', ns=WMS_NAMESPACE))
            logo = attribution.find(
                subcommon.nspath('LogoURL', ns=WMS_NAMESPACE))
            if title is not None:
                self.attribution['title'] = title.text
            if url is not None:
                self.attribution['url'] = url.attrib[
                    '{http://www.w3.org/1999/xlink}href']
            if logo is not None:
                self.attribution['logo_size'] = (int(logo.attrib['width']),
                                                 int(logo.attrib['height']))
                self.attribution['logo_url'] = logo.find(
                    subcommon.nspath('OnlineResource', ns=WMS_NAMESPACE)
                ).attrib['{http://www.w3.org/1999/xlink}href']

        b = elem.find(subcommon.nspath('LatLonBoundingBox', ns=WMS_NAMESPACE))
        if b is not None:
            self.boundingBoxWGS84 = (
                float(b.attrib['minx']),
                float(b.attrib['miny']),
                float(b.attrib['maxx']),
                float(b.attrib['maxy']),
            )
        elif self.parent:
            self.boundingBoxWGS84 = self.parent.boundingBoxWGS84
        else:
            self.boundingBoxWGS84 = None

        # bboxes
        bbs = elem.findall(subcommon.nspath('BoundingBox', WMS_NAMESPACE))
        if not bbs:
            crs_list = []
            for bb in bbs:
                srs_str = bb.attrib.get('SRS', None)
                srs = Crs(srs_str)
                box = tuple(
                    map(float, [
                        bb.attrib['minx'], bb.attrib['miny'],
                        bb.attrib['maxx'], bb.attrib['maxy']
                    ]))
                minx, miny, maxx, maxy = box[0], box[1], box[2], box[3]
                # handle the ordering so that it always
                # returns (minx, miny, maxx, maxy)
                if srs and srs.axisorder == 'yx':
                    # reverse things
                    minx, miny, maxx, maxy = box[1], box[0], box[3], box[2]
                crs_list.append((minx, miny, maxx, maxy, srs_str))
            self.crs_list = crs_list

        elif self.parent:
            self.crs_list = self.parent.crs_list
        else:
            self.crs_list = None

        # and maintain the original boundingBox attribute (first in list)
        # or the wgs84 bbox (to handle cases of incomplete parentage)
        self.boundingBox = self.crs_list[
            0] if self.crs_list else self.boundingBoxWGS84

        # SRS options
        self.crsOptions = []
        # Copy any parent SRS options (they are inheritable properties)
        if self.parent:
            self.crsOptions = list(self.parent.crsOptions)
        # Look for SRS option attached to this layer
        if elem.find(subcommon.nspath('SRS', ns=WMS_NAMESPACE)) is not None:
            ## some servers found in the wild use a single SRS
            ## tag containing a whitespace separated list of SRIDs
            ## instead of several SRS tags. hence the inner loop
            for srslist in [
                    x.text for x in elem.findall(
                        subcommon.nspath('SRS', ns=WMS_NAMESPACE))
            ]:
                if srslist:
                    for srs in srslist.split():
                        self.crsOptions.append(srs)
        #Get rid of duplicate entries
        self.crsOptions = list(set(self.crsOptions))
        #Set self.crsOptions to None if the layer (and parents) had no SRS options
        if len(self.crsOptions) == 0:
            #raise ValueError('%s no SRS available!?' % (elem,))
            #Comment by D Lowe.
            #Do not raise ValueError as it is possible that a layer is purely a parent layer and does not have SRS specified. Instead set crsOptions to None
            # Comment by Jachym:
            # Do not set it to None, but to [], which will make the code
            # work further. Fixed by anthonybaxter
            self.crsOptions = None

        #Styles
        self.styles = {}
        #Copy any parent styles (they are inheritable properties)
        if self.parent:
            self.styles = self.parent.styles.copy()
        #Get the styles for this layer (items with the same name are replaced)
        for s in elem.findall(subcommon.nspath('Style', ns=WMS_NAMESPACE)):
            name = s.find(subcommon.nspath('Name', ns=WMS_NAMESPACE))
            title = s.find(subcommon.nspath('Title', ns=WMS_NAMESPACE))
            if not name:
                continue
            if title is None:
                style = {'title': None}
            else:
                style = {'title': title.text}


#             if name is None or title is None:
#                 raise ValueError('%s missing name or title' % (s,))
#             style = { 'title' : title.text }
# legend url
            legend = s.find(
                subcommon.nspath('LegendURL/OnlineResource', ns=WMS_NAMESPACE))
            if legend is not None:
                style['legend'] = legend.attrib[
                    '{http://www.w3.org/1999/xlink}href']

            lgd = s.find(subcommon.nspath('LegendURL', WMS_NAMESPACE))
            if lgd is not None:
                if 'width' in lgd.attrib.keys():
                    style['legend_width'] = lgd.attrib.get('width')
                if 'height' in lgd.attrib.keys():
                    style['legend_height'] = lgd.attrib.get('height')

                lgd_format = lgd.find(subcommon.nspath('Format',
                                                       WMS_NAMESPACE))
                if lgd_format is not None:
                    style['legend_format'] = lgd_format.text.strip()

            self.styles[name.text] = style

        # timepositions - times for which data is available.
        self.timepositions = None
        self.defaulttimeposition = None
        for extent in elem.findall(subcommon.nspath('Extent',
                                                    ns=WMS_NAMESPACE)):
            if extent.attrib.get("name").lower() == 'time':
                if extent.text:
                    self.timepositions = extent.text.split(',')
                    self.defaulttimeposition = extent.attrib.get("default")
                    break

        # Elevations - available vertical levels
        self.elevations = None
        for extent in elem.findall(subcommon.nspath('Extent',
                                                    ns=WMS_NAMESPACE)):
            if extent.attrib.get("name").lower() == 'elevation':
                if extent.text:
                    self.elevations = extent.text.split(',')
                    break

        # MetadataURLs
        self.metadataUrls = []
        for m in elem.findall(subcommon.nspath('MetadataURL',
                                               ns=WMS_NAMESPACE)):
            metadataUrl = {
                #                 'type': testXMLValue(m.attrib['type'], attrib=True),
                #                 'format': testXMLValue(m.find(subcommon.nspath('Format',ns=WMS_NAMESPACE))),
                #                 'url': testXMLValue(m.find(subcommon.nspath('OnlineResource',ns=WMS_NAMESPACE)).attrib['{http://www.w3.org/1999/xlink}href'], attrib=True)
                'type':
                testXMLValue(subcommon.attrib_extraction(m, 'type', None),
                             attrib=True),
                'format':
                testXMLValue(
                    m.find(subcommon.nspath('Format', ns=WMS_NAMESPACE))),
                'url':
                testXMLValue(subcommon.attrib_extraction(
                    m.find(subcommon.nspath('OnlineResource',
                                            ns=WMS_NAMESPACE)), 'href',
                    'xlink}'),
                             attrib=True)
            }

            if metadataUrl[
                    'url'] is not None and parse_remote_metadata:  # download URL
                try:
                    content = openURL(metadataUrl['url'], timeout=timeout)
                    doc = etree.parse(content)
                    if metadataUrl['type'] is not None:
                        if metadataUrl['type'] == 'FGDC':
                            metadataUrl['metadata'] = Metadata(doc)
                        if metadataUrl['type'] == 'TC211':
                            metadataUrl['metadata'] = MD_Metadata(doc)
                except Exception:
                    metadataUrl['metadata'] = None

            self.metadataUrls.append(metadataUrl)

        def str_strip(str_text):
            if str_text:
                return str_text.strip()
            else:
                return str_text

        # FeatureListURLs
        self.featureListUrls = []
        for m in elem.findall(
                subcommon.nspath('FeatureListURL', ns=WMS_NAMESPACE)):
            featureListUrl = {
                'format':
                str_strip(
                    m.find(subcommon.nspath('Format', ns=WMS_NAMESPACE)).text),
                'url':
                subcommon.attrib_extraction(
                    m.find(subcommon.nspath('OnlineResource',
                                            ns=WMS_NAMESPACE)), 'href',
                    'xlink')
            }
            self.featureListUrls.append(featureListUrl)

        # DataURLs
        self.dataUrls = []
        for m in elem.findall(subcommon.nspath('DataURL', ns=WMS_NAMESPACE)):
            dataUrl = {
                'format':
                str_strip(
                    m.find(subcommon.nspath('Format', ns=WMS_NAMESPACE)).text),
                'url':
                subcommon.attrib_extraction(
                    m.find(subcommon.nspath('OnlineResource',
                                            ns=WMS_NAMESPACE)), 'href',
                    'xlink')
            }
            self.dataUrls.append(dataUrl)

        self.layers = []
        for child in elem.findall(subcommon.nspath('Layer', ns=WMS_NAMESPACE)):
            self.layers.append(SubContentMetadata(child, self))