Exemple #1
0
    def __init__(self, elem, service):
        """Initialize. service is required so that describeCoverage requests may be made"""
        # TODO - examine the parent for bounding box info.

        # self._parent=parent
        self._elem = elem
        self._service = service
        self.id = elem.find(ns("name")).text
        self.title = testXMLValue(elem.find(ns("label")))
        self.abstract = testXMLValue(elem.find(ns("description")))
        self.keywords = [f.text for f in elem.findall(ns("keywords") + "/" + ns("keyword"))]
        self.boundingBox = None  # needed for iContentMetadata harmonisation
        self.boundingBoxWGS84 = None
        b = elem.find(ns("lonLatEnvelope"))
        if b is not None:
            gmlpositions = b.findall("{http://www.opengis.net/gml}pos")
            lc = gmlpositions[0].text
            uc = gmlpositions[1].text
            self.boundingBoxWGS84 = (
                float(lc.split()[0]),
                float(lc.split()[1]),
                float(uc.split()[0]),
                float(uc.split()[1]),
            )
        # others not used but needed for iContentMetadata harmonisation
        self.styles = None
        self.crsOptions = None
        self.defaulttimeposition = None
Exemple #2
0
 def _parserecords(self, outputschema, esn):
     if outputschema == namespaces["gmd"]:  # iso 19139
         for i in self._exml.findall("//" + util.nspath("MD_Metadata", namespaces["gmd"])):
             val = i.find(
                 util.nspath("fileIdentifier", namespaces["gmd"])
                 + "/"
                 + util.nspath("CharacterString", namespaces["gco"])
             )
             identifier = self._setidentifierkey(util.testXMLValue(val))
             self.records[identifier] = MD_Metadata(i)
     elif outputschema == namespaces["fgdc"]:  # fgdc csdgm
         for i in self._exml.findall("//metadata"):
             val = i.find("idinfo/datasetid")
             identifier = self._setidentifierkey(util.testXMLValue(val))
             self.records[identifier] = Metadata(i)
     # CSWs define the dif namespace with the trailing '/' as an
     # outputSchema, but actual responses indeed define it with '/' as an outputSchema
     # this is an interoperability issue to be resolved
     # [:-1] is a workaround for now
     elif outputschema == namespaces["dif"][:-1]:  # nasa dif, strip the trailing '/' for now
         for i in self._exml.findall("//" + util.nspath("DIF", namespaces["dif"])):
             val = i.find(util.nspath("Entry_ID", namespaces["dif"]))
             identifier = self._setidentifierkey(util.testXMLValue(val))
             self.records[identifier] = DIF(i)
     else:  # process default
         for i in self._exml.findall("//" + util.nspath(self._setesnel(esn), namespaces["csw"])):
             val = i.find(util.nspath("identifier", namespaces["dc"]))
             identifier = self._setidentifierkey(util.testXMLValue(val))
             self.records[identifier] = CswRecord(i)
Exemple #3
0
    def __init__(self, md):
        if md is not None:
            val = md.find('timeinfo/sngdate/caldate')
            self.caldate = util.testXMLValue(val)

            val = md.find('current')
            self.current = util.testXMLValue(val)
Exemple #4
0
 def __init__(self,elem):        
     self.service="WCS"
     self.version="1.1.0"
     self.title=testXMLValue(elem.find('{http://www.opengis.net/ows}Title'))
     if self.title is None:  #may have used the wcs ows namespace:
         self.title=testXMLValue(elem.find('{http://www.opengis.net/wcs/1.1/ows}Title'))
     
     self.abstract=testXMLValue(elem.find('{http://www.opengis.net/ows}Abstract'))
     if self.abstract is None:#may have used the wcs ows namespace:
         self.abstract=testXMLValue(elem.find('{http://www.opengis.net/wcs/1.1/ows}Abstract'))
     if elem.find('{http://www.opengis.net/ows}Abstract') is not None:
         self.abstract=elem.find('{http://www.opengis.net/ows}Abstract').text
     else:
         self.abstract = None
     self.keywords = [f.text for f in elem.findall('{http://www.opengis.net/ows}Keywords/{http://www.opengis.net/ows}Keyword')]
     #self.link = elem.find('{http://www.opengis.net/wcs/1.1}Service/{http://www.opengis.net/wcs/1.1}OnlineResource').attrib.get('{http://www.w3.org/1999/xlink}href', '')
            
     if elem.find('{http://www.opengis.net/wcs/1.1/ows}Fees') is not None:            
         self.fees=elem.find('{http://www.opengis.net/wcs/1.1/ows}Fees').text
     else:
         self.fees=None
     
     if  elem.find('{http://www.opengis.net/wcs/1.1/ows}AccessConstraints') is not None:
         self.accessConstraints=elem.find('{http://www.opengis.net/wcs/1.1/ows}AccessConstraints').text
     else:
         self.accessConstraints=None
Exemple #5
0
    def __init__(self, md):
        val = md.find(util.nspath('File', namespaces['dif']))
        self.file = util.testXMLValue(val)

        val = md.find(util.nspath('URL', namespaces['dif']))
        self.url = util.testXMLValue(val)

        val = md.find(util.nspath('Format', namespaces['dif']))
        self.format = util.testXMLValue(val)

        val = md.find(util.nspath('Caption', namespaces['dif']))
        self.caption = util.testXMLValue(val)

        val = md.find(util.nspath('Description', namespaces['dif']))
        self.description = util.testXMLValue(val)

        val = md.find(util.nspath('Visualization_URL', namespaces['dif']))
        self.vis_url = util.testXMLValue(val)

        val = md.find(util.nspath('Visualization_Type', namespaces['dif']))
        self.vis_type = util.testXMLValue(val)

        val = md.find(util.nspath('Visualization_Subtype', namespaces['dif']))
        self.vis_subtype = util.testXMLValue(val)

        val = md.find(util.nspath('Visualization_Duration', namespaces['dif']))
        self.vis_duration = util.testXMLValue(val)

        val = md.find(util.nspath('Visualization_File_Size', namespaces['dif']))
        self.file_size = util.testXMLValue(val)
Exemple #6
0
    def __init__(self, element):
        self._root = element

        self.id = testXMLValue(self._root.attrib.get(nspath_eval('gml:id', namespaces)), True)
        self.description = testXMLValue(self._root.find(nspath_eval('gml:description', namespaces)))
        self.keywords = extract_xml_list(self._root.findall(nspath_eval('sml:keywords/sml:KeywordList/sml:keyword', namespaces)))

        self.documents = []
        for document in self._root.findall(nspath_eval('sml:documentation', namespaces)):
            self.documents.append(DocumentationMetadata(document))

        self.identifiers = {}
        for identifier in self._root.findall(nspath_eval('sml:identification/sml:IdentifierList/sml:identifier', namespaces)):
            ident = IdentifierMetadata(identifier)
            self.identifiers[ident.name] = ident

        self.contacts = {}
        for contact in self._root.findall(nspath_eval('sml:contact', namespaces)):
            cont = ContactMetadata(contact)
            self.contacts[cont.role] = cont

        self.classifiers = {}
        for classifier in self._root.findall(nspath_eval('sml:classification/sml:ClassifierList/sml:classifier', namespaces)):
            classi = ClassifierMetadata(classifier)
            self.classifiers[classi.name] = classi

        self.history = {}
        for event_member in self._root.findall(nspath_eval('sml:history/sml:EventList/sml:member', namespaces)):
            emm = EventMemberMetadata(event_member)
            if self.history.get(emm.name) is None:
                self.history[emm.name] = []
            self.history[emm.name] += emm.events
    
        self.components = {}
Exemple #7
0
    def __init__(self, md):
        val = md.find(util.nspath_eval("dif:File", namespaces))
        self.file = util.testXMLValue(val)

        val = md.find(util.nspath_eval("dif:URL", namespaces))
        self.url = util.testXMLValue(val)

        val = md.find(util.nspath_eval("dif:Format", namespaces))
        self.format = util.testXMLValue(val)

        val = md.find(util.nspath_eval("dif:Caption", namespaces))
        self.caption = util.testXMLValue(val)

        val = md.find(util.nspath_eval("dif:Description", namespaces))
        self.description = util.testXMLValue(val)

        val = md.find(util.nspath_eval("dif:Visualization_URL", namespaces))
        self.vis_url = util.testXMLValue(val)

        val = md.find(util.nspath_eval("dif:Visualization_Type", namespaces))
        self.vis_type = util.testXMLValue(val)

        val = md.find(util.nspath_eval("dif:Visualization_Subtype", namespaces))
        self.vis_subtype = util.testXMLValue(val)

        val = md.find(util.nspath_eval("dif:Visualization_Duration", namespaces))
        self.vis_duration = util.testXMLValue(val)

        val = md.find(util.nspath_eval("dif:Visualization_File_Size", namespaces))
        self.file_size = util.testXMLValue(val)
Exemple #8
0
    def __init__(self, ct):
        val = ct.find(util.nspath('name', namespaces['gmx']) + '/' + util.nspath('CharacterString', namespaces['gco']))
        self.name = util.testXMLValue(val)
        val = ct.find(util.nspath('scope', namespaces['gmx']) + '/' + util.nspath('CharacterString', namespaces['gco']))
        self.scope = util.testXMLValue(val)
        val = ct.find(util.nspath('fieldOfApplication', namespaces['gmx']) + '/' + util.nspath('CharacterString', namespaces['gco']))
        self.fieldapp = util.testXMLValue(val)
        val = ct.find(util.nspath('versionNumber', namespaces['gmx']) + '/' + util.nspath('CharacterString', namespaces['gco']))
        self.version = util.testXMLValue(val)
        val = ct.find(util.nspath('versionDate', namespaces['gmx']) + '/' + util.nspath('Date', namespaces['gco']))
        self.date = util.testXMLValue(val)

        self.dictionaries = {}

        for i in ct.findall(util.nspath('codelistItem/CodeListDictionary', namespaces['gmx'])):
            id = i.attrib.get(util.nspath('id', namespaces['gml']))
            self.dictionaries[id] = {}
            val = i.find(util.nspath('description', namespaces['gml']))
            self.dictionaries[id]['description'] = util.testXMLValue(val)
            val = i.find(util.nspath('identifier', namespaces['gml']))
            self.dictionaries[id]['identifier'] = util.testXMLValue(val)
            self.dictionaries[id]['entries'] = {}

            for j in i.findall(util.nspath('codeEntry', namespaces['gmx'])):
                id2 = j.find(util.nspath('CodeDefinition', namespaces['gmx'])).attrib.get(util.nspath('id', namespaces['gml']))
                self.dictionaries[id]['entries'][id2] = {}
                val = j.find(util.nspath('CodeDefinition', namespaces['gmx'])+'/'+util.nspath('description', namespaces['gml']))
                self.dictionaries[id]['entries'][id2]['description'] = util.testXMLValue(val)

                val = j.find(util.nspath('CodeDefinition', namespaces['gmx'])+'/'+util.nspath('identifier', namespaces['gml']))
                self.dictionaries[id]['entries'][id2]['identifier'] = util.testXMLValue(val)

                val = j.find(util.nspath('CodeDefinition', namespaces['gmx'])).attrib.get('codeSpace')
                self.dictionaries[id]['entries'][id2]['codespace'] = util.testXMLValue(val, True)
Exemple #9
0
    def __init__(self, md=None):
        if md is None:
            self.keywords = []
            self.type = None
            self.thesaurus = None
            self.kwdtype_codeList = 'http://standards.iso.org/ittf/PubliclyAvailableStandards/ISO_19139_Schemas/resources/codelist/gmxCodelists.xml#MD_KeywordTypeCode'
        else:
            self.keywords = []
            val = md.findall(util.nspath_eval('gmd:keyword/gco:CharacterString', namespaces))
            for word in val:
                self.keywords.append(util.testXMLValue(word))

            self.type = None
            val = md.find(util.nspath_eval('gmd:type/gmd:MD_KeywordTypeCode', namespaces))
            self.type = util.testXMLAttribute(val, 'codeListValue')

            self.thesaurus = None
            val = md.find(util.nspath_eval('gmd:thesaurusName/gmd:CI_Citation', namespaces))
            if val is not None:
                self.thesaurus = {}

                thesaurus = val.find(util.nspath_eval('gmd:title/gco:CharacterString', namespaces))
                self.thesaurus['title'] = util.testXMLValue(thesaurus)

                thesaurus = val.find(util.nspath_eval('gmd:date/gmd:CI_Date/gmd:date/gco:Date', namespaces))
                self.thesaurus['date'] = util.testXMLValue(thesaurus)

                thesaurus = val.find(util.nspath_eval('gmd:date/gmd:CI_Date/gmd:dateType/gmd:CI_DateTypeCode', namespaces))
                self.thesaurus['datetype'] = util.testXMLAttribute(thesaurus, 'codeListValue')
Exemple #10
0
    def __init__(self, elem, namespace=DEFAULT_OWS_NAMESPACE): 
        self.minx = None
        self.miny = None
        self.maxx = None
        self.maxy = None

        val = elem.attrib.get('crs')
        self.crs = util.testXMLValue(val, True)

        val = elem.attrib.get('dimensions')
        self.dimensions = util.testXMLValue(val, True)

        val = elem.find(util.nspath('LowerCorner', namespace))
        tmp = util.testXMLValue(val)
        if tmp is not None:
            xy = tmp.split()
            if len(xy) > 1:
                self.minx, self.miny = xy[0], xy[1] 

        val = elem.find(util.nspath('UpperCorner', namespace))
        tmp = util.testXMLValue(val)
        if tmp is not None:
            xy = tmp.split()
            if len(xy) > 1:
                self.maxx, self.maxy = xy[0], xy[1]
Exemple #11
0
 def _parserecords(self, outputschema, esn):
     if outputschema == namespaces['gmd']: # iso 19139
         for i in self._records.findall('//'+util.nspath('MD_Metadata', namespaces['gmd'])):
             val = i.find(util.nspath('fileIdentifier', namespaces['gmd']) + '/' + util.nspath('CharacterString', namespaces['gco']))
             identifier = self._setidentifierkey(util.testXMLValue(val))
             self.records[identifier] = MD_Metadata(i)
     elif outputschema == namespaces['fgdc']: # fgdc csdgm
         for i in self._records.findall('//metadata'):
             val = i.find('idinfo/datasetid')
             identifier = self._setidentifierkey(util.testXMLValue(val))
             self.records[identifier] = Metadata(i)
     # CSWs define the dif namespace with the trailing '/' as an
     # outputSchema, but actual responses indeed define it with '/' as an outputSchema
     # this is an interoperability issue to be resolved
     # [:-1] is a workaround for now
     elif outputschema == namespaces['dif'][:-1]: # nasa dif, strip the trailing '/' for now
         for i in self._records.findall('//'+util.nspath('DIF', namespaces['dif'])):
             val = i.find(util.nspath('Entry_ID', namespaces['dif']))
             identifier = self._setidentifierkey(util.testXMLValue(val))
             self.records[identifier] = DIF(i)
     else: # process default
         for i in self._records.findall('//'+util.nspath(self._setesnel(esn), namespaces['csw'])):
             val = i.find(util.nspath('identifier', namespaces['dc']))
             identifier = self._setidentifierkey(util.testXMLValue(val))
             self.records[identifier] = CswRecord(i)
Exemple #12
0
 def _parserecords(self, outputschema, esn):
     if outputschema == namespaces['gmd']: # iso 19139
         for i in self._exml.findall('.//'+util.nspath_eval('gmd:MD_Metadata', namespaces)) or self._exml.findall('.//'+util.nspath_eval('gmi:MI_Metadata', namespaces)):
             val = i.find(util.nspath_eval('gmd:fileIdentifier/gco:CharacterString', namespaces))
             identifier = self._setidentifierkey(util.testXMLValue(val))
             self.records[identifier] = MD_Metadata(i)
     elif outputschema == namespaces['fgdc']: # fgdc csdgm
         for i in self._exml.findall('.//metadata'):
             val = i.find('idinfo/datasetid')
             identifier = self._setidentifierkey(util.testXMLValue(val))
             self.records[identifier] = Metadata(i)
     elif outputschema == namespaces['dif']: # nasa dif
         for i in self._exml.findall('.//'+util.nspath_eval('dif:DIF', namespaces)):
             val = i.find(util.nspath_eval('dif:Entry_ID', namespaces))
             identifier = self._setidentifierkey(util.testXMLValue(val))
             self.records[identifier] = DIF(i)
     elif outputschema == namespaces['gm03']: # GM03
         for i in self._exml.findall('.//'+util.nspath_eval('gm03:TRANSFER', namespaces)):
             val = i.find(util.nspath_eval('gm03:fileIdentifier', namespaces))
             identifier = self._setidentifierkey(util.testXMLValue(val))
             self.records[identifier] = GM03(i)
     else: # process default
         for i in self._exml.findall('.//'+util.nspath_eval('csw:%s' % self._setesnel(esn), namespaces)):
             val = i.find(util.nspath_eval('dc:identifier', namespaces))
             identifier = self._setidentifierkey(util.testXMLValue(val))
             self.records[identifier] = CswRecord(i)
Exemple #13
0
    def __init__(self, md):
        """constructor"""

        _GenericObject.__init__(self, md)

        self.name = util.testXMLValue(md.find(util.nspath_eval("gm03:name", namespaces)))
        self.version = util.testXMLValue(md.find(util.nspath_eval("gm03:version", versionspaces)))
Exemple #14
0
 def __init__(self, md):
     
     self.conformancetitle = []
     for i in md.findall(util.nspath_eval('gmd:report/gmd:DQ_DomainConsistency/gmd:result/gmd:DQ_ConformanceResult/gmd:specification/gmd:CI_Citation/gmd:title/gco:CharacterString', namespaces)):
         val = util.testXMLValue(i)
         if val is not None:
             self.conformancetitle.append(val)
     
     self.conformancedate = []
     for i in md.findall(util.nspath_eval('gmd:report/gmd:DQ_DomainConsistency/gmd:result/gmd:DQ_ConformanceResult/gmd:specification/gmd:CI_Citation/gmd:date/gmd:CI_Date/gmd:date/gco:Date', namespaces)):
         val = util.testXMLValue(i)
         if val is not None:
             self.conformancedate.append(val)
     
     self.conformancedatetype = []
     for i in md.findall(util.nspath_eval('gmd:report/gmd:DQ_DomainConsistency/gmd:result/gmd:DQ_ConformanceResult/gmd:specification/gmd:CI_Citation/gmd:date/gmd:CI_Date/gmd:dateType/gmd:CI_DateTypeCode', namespaces)):
         val = util.testXMLValue(i)
         if val is not None:
             self.conformancedatetype.append(val)
     
     self.conformancedegree = []
     for i in md.findall(util.nspath_eval('gmd:report/gmd:DQ_DomainConsistency/gmd:result/gmd:DQ_ConformanceResult/gmd:pass/gco:Boolean', namespaces)):
         val = util.testXMLValue(i)
         if val is not None:
             self.conformancedegree.append(val)
     
     val = md.find(util.nspath_eval('gmd:lineage/gmd:LI_Lineage/gmd:statement/gco:CharacterString', namespaces))
     self.lineage = util.testXMLValue(val)
Exemple #15
0
    def __init__(self, md):
        """constructor"""

        _GenericObject.__init__(self, md)

        self.extent_type_code = util.testXMLValue(md.find(util.nspath_eval("gm03:extentTypeCode", namespaces)))

        boundaries = []

        for boundary in md.findall(util.nspath_eval("gm03:SURFACE/gm03:BOUNDARY", namespaces)):
            polylines = []
            for polyline in boundary.findall(util.nspath_eval("gm03:POLYLINE", namespaces)):
                coords = []
                arcs = []
                for coord in polyline.findall(util.nspath_eval("gm03:COORD", namespaces)):
                    c1 = util.testXMLValue(coord.find(util.nspath_eval("gm03:C1", namespaces)))
                    c2 = util.testXMLValue(coord.find(util.nspath_eval("gm03:C2", namespaces)))
                    c3 = util.testXMLValue(coord.find(util.nspath_eval("gm03:C3", namespaces)))
                    coordvalue = {"c1": c1, "c2": c2, "c3": c3}
                    coords.append(coordvalue)
                for arc in polyline.findall(util.nspath_eval("gm03:ARC", namespaces)):
                    c1 = util.testXMLValue(coord.find(util.nspath_eval("gm03:C1", namespaces)))
                    c2 = util.testXMLValue(coord.find(util.nspath_eval("gm03:C2", namespaces)))
                    c3 = util.testXMLValue(coord.find(util.nspath_eval("gm03:C3", namespaces)))
                    a1 = util.testXMLValue(coord.find(util.nspath_eval("gm03:A1", namespaces)))
                    a2 = util.testXMLValue(coord.find(util.nspath_eval("gm03:A2", namespaces)))
                    r = util.testXMLValue(coord.find(util.nspath_eval("gm03:R", namespaces)))
                    arcpoint = {"c1": c1, "c2": c2, "c3": c3, "a1": a1, "a2": a2, "r": r}
                    arcs.append(arcpoint)
                polylines.append(coords)
                polylines.append(arcs)
            boundaries.append(polylines)
        self.boundary = boundaries
Exemple #16
0
    def __init__(self, ct):
        val = ct.find(util.nspath_eval('gmx:name/gco:CharacterString', namespaces))
        self.name = util.testXMLValue(val)
        val = ct.find(util.nspath_eval('gmx:scope/gco:CharacterString', namespaces))
        self.scope = util.testXMLValue(val)
        val = ct.find(util.nspath_eval('gmx:fieldOfApplication/gco:CharacterString', namespaces))
        self.fieldapp = util.testXMLValue(val)
        val = ct.find(util.nspath_eval('gmx:versionNumber/gco:CharacterString', namespaces))
        self.version = util.testXMLValue(val)
        val = ct.find(util.nspath_eval('gmx:versionDate/gco:Date', namespaces))
        self.date = util.testXMLValue(val)

        self.dictionaries = {}

        for i in ct.findall(util.nspath_eval('gmx:codelistItem/gmx:CodeListDictionary', namespaces)):
            id = i.attrib.get(util.nspath_eval('gml32:id', namespaces))
            self.dictionaries[id] = {}
            val = i.find(util.nspath_eval('gml32:description', namespaces))
            self.dictionaries[id]['description'] = util.testXMLValue(val)
            val = i.find(util.nspath_eval('gml32:identifier', namespaces))
            self.dictionaries[id]['identifier'] = util.testXMLValue(val)
            self.dictionaries[id]['entries'] = {}

            for j in i.findall(util.nspath_eval('gmx:codeEntry', namespaces)):
                id2 = j.find(util.nspath_eval('gmx:CodeDefinition', namespaces)).attrib.get(util.nspath_eval('gml32:id', namespaces))
                self.dictionaries[id]['entries'][id2] = {}
                val = j.find(util.nspath_eval('gmx:CodeDefinition/gml32:description', namespaces))
                self.dictionaries[id]['entries'][id2]['description'] = util.testXMLValue(val)

                val = j.find(util.nspath_eval('gmx:CodeDefinition/gml32:identifier', namespaces))
                self.dictionaries[id]['entries'][id2]['identifier'] = util.testXMLValue(val)

                val = j.find(util.nspath_eval('gmx:CodeDefinition', namespaces)).attrib.get('codeSpace')
                self.dictionaries[id]['entries'][id2]['codespace'] = util.testXMLValue(val, True)
Exemple #17
0
    def __init__(self, element, name):
        self._root = element

        self.name = name
        # All dates are UTC
        self.date = testXMLValue(self._root.find(nsp('sml:date')))
        self.description = testXMLValue(self._root.find(nsp('gml:description')))
        self.documentation_url = testXMLAttribute(self._root.find(nsp('sml:documentation')), nsp('xlink:href'))
Exemple #18
0
    def __init__(self, md):
        """constructor"""

        self.language = util.testXMLValue(md.find(util.nspath_eval("gm03:language", namespaces)))
        self.country = util.testXMLValue(md.find(util.nspath_eval("gm03:country", namespaces)))
        self.character_set_code = util.testXMLValue(md.find(util.nspath_eval("gm03:characterSetCode", namespaces)))
        self.plain_text = util.testXMLValue(md.find(util.nspath_eval("gm03:plainText", namespaces)))
        self.plain_url = util.testXMLValue(md.find(util.nspath_eval("gm03:plainURL", namespaces)))
Exemple #19
0
 def get_point(element, srs):
     name  = testXMLValue(element.find(nspv("gml311:name")))
     point = testXMLValue(element.find(nspv("gml311:pos"))).split(" ")
     if srs.axisorder == "yx":
         point = Point(float(point[1]), float(point[0]))
     else:
         point = Point(float(point[0]), float(point[1]))
     return name, point
Exemple #20
0
    def __init__(self, md=None):
        if md is None:
            self.identtype = 'service'
            self.type = None
            self.version = None
            self.fees = None
            self.bbox = None
            self.couplingtype = None
            self.operations = []
            self.operateson = []
        else:
            val=md.find(util.nspath_eval('gmd:citation/gmd:CI_Citation/gmd:title/gco:CharacterString', namespaces))
            self.title=util.testXMLValue(val)
            self.identtype = 'service'
            val = md.find(util.nspath_eval('srv:serviceType/gco:LocalName', namespaces))
            self.type = util.testXMLValue(val)
          
            val = md.find(util.nspath_eval('srv:serviceTypeVersion/gco:CharacterString', namespaces))
            self.version = util.testXMLValue(val)

            val = md.find(util.nspath_eval('srv:accessProperties/gmd:MD_StandardOrderProcess/gmd:fees/gco:CharacterString', namespaces))
            self.fees = util.testXMLValue(val)

            val = md.find(util.nspath_eval('srv:extent/gmd:EX_Extent', namespaces))

            if val is not None:
                self.bbox = EX_Extent(val)
            else:
                self.bbox = None

            self.couplingtype = _testCodeListValue(md.find(util.nspath_eval('gmd:couplingType/gmd:SV_CouplingType', namespaces)))

            self.operations = []

            for i in md.findall(util.nspath_eval('srv:containsOperations', namespaces)):
                tmp = {}
                val = i.find(util.nspath_eval('srv:SV_OperationMetadata/srv:operationName/gco:CharacterString', namespaces))
                tmp['name'] = util.testXMLValue(val)
                tmp['dcplist'] = []
                for d in i.findall(util.nspath_eval('srv:SV_OperationMetadata/srv:DCP', namespaces)):
                    tmp2 = _testCodeListValue(d.find(util.nspath_eval('srv:DCPList', namespaces)))
                    tmp['dcplist'].append(tmp2)
             
                tmp['connectpoint'] = []
     
                for d in i.findall(util.nspath_eval('srv:SV_OperationMetadata/srv:connectPoint', namespaces)):
                    tmp3 = d.find(util.nspath_eval('gmd:CI_OnlineResource', namespaces))
                    tmp['connectpoint'].append(CI_OnlineResource(tmp3))
                self.operations.append(tmp)

            self.operateson = []
             
            for i in md.findall(util.nspath_eval('srv:operatesOn', namespaces)):
                tmp = {}
                tmp['uuidref'] = i.attrib.get('uuidref')
                tmp['href'] = i.attrib.get(util.nspath_eval('xlink:href', namespaces))
                tmp['title'] = i.attrib.get(util.nspath_eval('xlink:title', namespaces))
                self.operateson.append(tmp)
Exemple #21
0
 def __init__(self, infoset, version):
     self._root=infoset
     self.type = testXMLValue(self._root.find(nspath('Name')))
     self.version = version
     self.title = testXMLValue(self._root.find(nspath('Title')))
     self.abstract = testXMLValue(self._root.find(nspath('Abstract')))
     self.keywords = [f.text for f in self._root.findall(nspath('Keywords'))]
     self.fees = testXMLValue(self._root.find(nspath('Fees')))
     self.accessconstraints = testXMLValue(self._root.find(nspath('AccessConstraints')))
Exemple #22
0
 def __init__(self, infoset, version):
     self._root=infoset
     self.type = testXMLValue(self._root.find(wfs_ns('Name')))
     self.version = version
     self.title = testXMLValue(self._root.find(wfs_ns('Title')))
     self.abstract = testXMLValue(self._root.find(wfs_ns('Abstract')))
     self.keywords = extract_xml_list(self._root.findall(wfs_ns('Keywords')))
     self.fees = testXMLValue(self._root.find(wfs_ns('Fees')))
     self.accessconstraints = testXMLValue(self._root.find(wfs_ns('AccessConstraints')))
Exemple #23
0
    def harvest(self, source, resourcetype, resourceformat=None, harvestinterval=None, responsehandler=None):
        """

        Construct and process a Harvest request

        Parameters
        ----------

        - source: a URI to harvest
        - resourcetype: namespace identifying the type of resource
        - resourceformat: MIME type of the resource
        - harvestinterval: frequency of harvesting, in ISO8601
        - responsehandler: endpoint that CSW should responsd to with response

        """

        # construct request
        node0 = etree.Element(util.nspath('Harvest', namespaces['csw']))
        node0.set('version', self.version)
        node0.set('service', self.service)
        node0.set(util.nspath('schemaLocation', namespaces['xsi']), schema_location)
        etree.SubElement(node0, util.nspath('Source', namespaces['csw'])).text = source
        etree.SubElement(node0, util.nspath('ResourceType', namespaces['csw'])).text = resourcetype
        if resourceformat is not None:
            etree.SubElement(node0, util.nspath('ResourceFormat', namespaces['csw'])).text = resourceformat
        if harvestinterval is not None:
            etree.SubElement(node0, util.nspath('HarvestInterval', namespaces['csw'])).text = harvestinterval
        if responsehandler is not None:
            etree.SubElement(node0, util.nspath('ResponseHandler', namespaces['csw'])).text = responsehandler
       
        self.request = util.xml2string(etree.tostring(node0))

        self.response = util.http_post(self.url, self.request, self.lang)

        # parse result
        self._response = etree.parse(StringIO.StringIO(self.response))

        # check for exceptions
        self._isexception(self._response, self.owscommon.namespace)

        self.results = {}

        if self.exceptionreport is None:
            val = self._response.find(util.nspath('Acknowledgement', namespaces['csw']))
            if util.testXMLValue(val) is not None:
                ts = val.attrib.get('timeStamp')
                self.timestamp = util.testXMLValue(ts, True)
                id = val.find(util.nspath('RequestId', namespaces['csw']))
                self.id = util.testXMLValue(id) 
            else:
                self._parsetransactionsummary()

            self.results['inserted'] = []

            for i in self._response.findall(util.nspath('TransactionResponse/InsertResult', namespaces['csw'])):
                for j in i.findall(util.nspath('BriefRecord', namespaces['csw']) + '/' + util.nspath('identifier', namespaces['dc'])):
                    self.results['inserted'].append(util.testXMLValue(j))
Exemple #24
0
    def __init__(self, md):
        val = md.find('abstract')
        self.abstract = util.testXMLValue(val)
        
        val = md.find('purpose')
        self.abstract = util.testXMLValue(val)

        val = md.find('supplinf')
        self.supplinf = util.testXMLValue(val)
Exemple #25
0
    def __init__(self, element, wqx_ns):
        self._root = element

        self.id = testXMLValue(
            self._root.find(nsp("OrganizationIdentifier", wqx_ns))
        )
        self.name = testXMLValue(
            self._root.find(nsp("OrganizationFormalName", wqx_ns))
        )
Exemple #26
0
 def __init__(self, md):
     val = md.find(util.nspath('geographicElement/EX_GeographicBoundingBox/westBoundLongitude', namespaces['gmd']) + '/' + util.nspath('Decimal', namespaces['gco']))
     self.minx = util.testXMLValue(val)
     val = md.find(util.nspath('geographicElement/EX_GeographicBoundingBox/eastBoundLongitude', namespaces['gmd']) + '/' + util.nspath('Decimal', namespaces['gco']))
     self.maxx = util.testXMLValue(val)
     val = md.find(util.nspath('geographicElement/EX_GeographicBoundingBox/southBoundLatitude', namespaces['gmd']) + '/' + util.nspath('Decimal', namespaces['gco']))
     self.miny = util.testXMLValue(val)
     val = md.find(util.nspath('geographicElement/EX_GeographicBoundingBox/northBoundLatitude', namespaces['gmd']) + '/' + util.nspath('Decimal', namespaces['gco']))
     self.maxy = util.testXMLValue(val)
Exemple #27
0
 def __init__(self, md):
     val = md.find(util.nspath_eval('gmd:EX_GeographicBoundingBox/gmd:westBoundLongitude/gco:Decimal', namespaces))
     self.minx = util.testXMLValue(val)
     val = md.find(util.nspath_eval('gmd:EX_GeographicBoundingBox/gmd:eastBoundLongitude/gco:Decimal', namespaces))
     self.maxx = util.testXMLValue(val)
     val = md.find(util.nspath_eval('gmd:EX_GeographicBoundingBox/gmd:southBoundLatitude/gco:Decimal', namespaces))
     self.miny = util.testXMLValue(val)
     val = md.find(util.nspath_eval('gmd:EX_GeographicBoundingBox/gmd:northBoundLatitude/gco:Decimal', namespaces))
     self.maxy = util.testXMLValue(val)
Exemple #28
0
 def __init__(self, infoset, version):
     self._root = infoset
     self.type = testXMLValue(self._root.find(nspath('Name', WMS_NAMESPACE)))
     self.version = version
     self.title = testXMLValue(self._root.find(nspath('Title', WMS_NAMESPACE)))
     self.abstract = testXMLValue(self._root.find(nspath('Abstract', WMS_NAMESPACE)))
     self.keywords = extract_xml_list(self._root.findall(nspath('KeywordList/Keyword', WMS_NAMESPACE)))
     self.accessconstraints = testXMLValue(self._root.find(nspath('AccessConstraints', WMS_NAMESPACE)))
     self.fees = testXMLValue(self._root.find(nspath('Fees', WMS_NAMESPACE)))
Exemple #29
0
 def __init__(self, infoset, version):
     self._root = infoset
     self.type = testXMLValue(self._root.find(wfs_ns("Name")))
     self.version = version
     self.title = testXMLValue(self._root.find(wfs_ns("Title")))
     self.abstract = testXMLValue(self._root.find(wfs_ns("Abstract")))
     self.keywords = extract_xml_list(self._root.findall(wfs_ns("Keywords")))
     self.fees = testXMLValue(self._root.find(wfs_ns("Fees")))
     self.accessconstraints = testXMLValue(self._root.find(wfs_ns("AccessConstraints")))
Exemple #30
0
 def __init__(self, md):
     val = md.find(util.nspath_eval('gmd:westBoundLongitude/gco:Decimal'))
     self.minx = util.testXMLValue(val)
     val = md.find(util.nspath_eval('gmd:eastBoundLongitude/gco:Decimal'))
     self.maxx = util.testXMLValue(val)
     val = md.find(util.nspath_eval('gmd:southBoundLatitude/gco:Decimal'))
     self.miny = util.testXMLValue(val)
     val = md.find(util.nspath_eval('gmd:northBoundLatitude/gco:Decimal'))
     self.maxy = util.testXMLValue(val)
Exemple #31
0
    def __init__(self, element, wqx_ns):
        self._root = element

        des = self._root.find(nsp("ResultDescription", wqx_ns))
        self.name = None
        self.short_name = None
        self.status = None
        self.stastistical_base_code = None
        self.value_type = None
        self.weight_basis = None
        self.time_basis = None
        self.temperature_basis = None
        if des is not None:
            self.name = testXMLValue(
                des.find(nsp("CharacteristicName", wqx_ns)))
            self.short_name = testXMLValue(
                des.find(nsp("ResultSampleFractionText", wqx_ns)))
            self.status = testXMLValue(
                des.find(nsp("ResultStatusIdentifier", wqx_ns)))
            self.stastistical_base_code = testXMLValue(
                des.find(nsp("StatisticalBaseCode", wqx_ns)))
            self.value_type = testXMLValue(
                des.find(nsp("ResultValueTypeName", wqx_ns)))
            self.weight_basis = testXMLValue(
                des.find(nsp("ResultWeightBasisText", wqx_ns)))
            self.time_basis = testXMLValue(
                des.find(nsp("ResultTimeBasisText", wqx_ns)))
            self.temperature_basis = testXMLValue(
                des.find(nsp("ResultTemperatureBasisText", wqx_ns)))

        rm = des.find(nsp("ResultMeasure", wqx_ns))
        self.value = None
        self.units = None
        if rm is not None:
            self.value = testXMLValue(
                rm.find(nsp("ResultMeasureValue", wqx_ns)))
            self.units = testXMLValue(rm.find(nsp("MeasureUnitCode", wqx_ns)))

        qu = des.find(nsp("DataQuality", wqx_ns))
        self.quality = None
        if qu is not None:
            self.quality = testXMLValue(qu.find(nsp("PrecisionValue", wqx_ns)))

        am = self._root.find(nsp("ResultAnalyticalMethod", wqx_ns))
        self.analytical_method_id = None
        self.analytical_method_id_context = None
        if am is not None:
            self.analytical_method_id = testXMLValue(
                am.find(nsp("MethodIdentifier", wqx_ns)))
            self.analytical_method_id_context = testXMLValue(
                am.find(nsp("MethodIdentifierContext", wqx_ns)))
Exemple #32
0
    def __init__(self, md=None, identtype=None):
        if md is None:
            self.identtype = None
            self.title = None
            self.alternatetitle = None
            self.aggregationinfo = None
            self.uricode = []
            self.uricodespace = []
            self.date = []
            self.datetype = []
            self.uselimitation = []
            self.accessconstraints = []
            self.classification = []
            self.otherconstraints = []
            self.securityconstraints = []
            self.useconstraints = []
            self.denominators = []
            self.distance = []
            self.uom = []
            self.resourcelanguage = []
            self.creator = []
            self.publisher = []
            self.contributor = []
            self.edition = None
            self.abstract = None
            self.purpose = None
            self.status = None
            self.contact = []
            self.keywords = []
            self.topiccategory = []
            self.supplementalinformation = None
            self.extent = None
            self.bbox = None
            self.temporalextent_start = None
            self.temporalextent_end = None
        else:
            self.identtype = identtype
            val = md.find(util.nspath_eval('gmd:citation/gmd:CI_Citation/gmd:title/gco:CharacterString', namespaces))
            self.title = util.testXMLValue(val)
            
            val = md.find(util.nspath_eval('gmd:citation/gmd:CI_Citation/gmd:alternateTitle/gco:CharacterString', namespaces))
            self.alternatetitle = util.testXMLValue(val)

            val = md.find(util.nspath_eval('gmd:aggregationInfo', namespaces))
            self.aggregationinfo = util.testXMLValue(val)

            self.uricode = []
            for i in md.findall(util.nspath_eval('gmd:citation/gmd:CI_Citation/gmd:identifier/gmd:RS_Identifier/gmd:code/gco:CharacterString', namespaces)):
                val = util.testXMLValue(i)
                if val is not None:
                    self.uricode.append(val)

            self.uricodespace = []
            for i in md.findall(util.nspath_eval('gmd:citation/gmd:CI_Citation/gmd:identifier/gmd:RS_Identifier/gmd:codeSpace/gco:CharacterString', namespaces)):
                val = util.testXMLValue(i)
                if val is not None:
                    self.uricodespace.append(val)

            self.date = []
            self.datetype = []
            
            for i in md.findall(util.nspath_eval('gmd:citation/gmd:CI_Citation/gmd:date/gmd:CI_Date', namespaces)):
                self.date.append(CI_Date(i))
            
            self.uselimitation = []
            for i in md.findall(util.nspath_eval('gmd:resourceConstraints/gmd:MD_Constraints/gmd:useLimitation/gco:CharacterString', namespaces)):
                val = util.testXMLValue(i)
                if val is not None:
                    self.uselimitation.append(val)
            
            self.accessconstraints = []
            for i in md.findall(util.nspath_eval('gmd:resourceConstraints/gmd:MD_LegalConstraints/gmd:accessConstraints/gmd:MD_RestrictionCode', namespaces)):
                val = _testCodeListValue(i)
                if val is not None:
                    self.accessconstraints.append(val)
            
            self.classification = []
            for i in md.findall(util.nspath_eval('gmd:resourceConstraints/gmd:MD_LegalConstraints/gmd:accessConstraints/gmd:MD_ClassificationCode', namespaces)):
                val = _testCodeListValue(i)
                if val is not None:
                    self.classification.append(val)
            
            self.otherconstraints = []
            for i in md.findall(util.nspath_eval('gmd:resourceConstraints/gmd:MD_LegalConstraints/gmd:otherConstraints/gco:CharacterString', namespaces)):
                val = util.testXMLValue(i)
                if val is not None:
                    self.otherconstraints.append(val)

            self.securityconstraints = []
            for i in md.findall(util.nspath_eval('gmd:resourceConstraints/gmd:MD_SecurityConstraints/gmd:useLimitation', namespaces)):
                val = util.testXMLValue(i)
                if val is not None:
                    self.securityconstraints.append(val)

            self.useconstraints = []
            for i in md.findall(util.nspath_eval('gmd:resourceConstraints/gmd:MD_LegalConstraints/gmd:useConstraints/gmd:MD_RestrictionCode', namespaces)):
                val = _testCodeListValue(i)
                if val is not None:
                    self.useconstraints.append(val)
            
            self.denominators = []
            for i in md.findall(util.nspath_eval('gmd:spatialResolution/gmd:MD_Resolution/gmd:equivalentScale/gmd:MD_RepresentativeFraction/gmd:denominator/gco:Integer', namespaces)):
                val = util.testXMLValue(i)
                if val is not None:
                    self.denominators.append(val)
            
            self.distance = []
            self.uom = []
            for i in md.findall(util.nspath_eval('gmd:spatialResolution/gmd:MD_Resolution/gmd:distance/gco:Distance', namespaces)):
                val = util.testXMLValue(i)
                if val is not None:
                    self.distance.append(val)
                self.uom.append(i.get("uom"))
            
            self.resourcelanguage = []
            for i in md.findall(util.nspath_eval('gmd:language/gmd:LanguageCode', namespaces)):
                val = _testCodeListValue(i)
                if val is not None:
                    self.resourcelanguage.append(val)

            self.creator = []
            self.publisher = []
            self.contributor = []
            for val in md.findall(util.nspath_eval('gmd:pointOfContact/gmd:CI_ResponsibleParty', namespaces)):
                role = val.find(util.nspath_eval('gmd:role/gmd:CI_RoleCode', namespaces))
                if role is not None:
                    clv = _testCodeListValue(role)
                    rp = CI_ResponsibleParty(val)
                    if clv == 'originator':
                        self.creator.append(rp)
                    elif clv == 'publisher':
                        self.publisher.append(rp)
                    elif clv == 'author':
                        self.contributor.append(rp)

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

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

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

            self.status = _testCodeListValue(md.find(util.nspath_eval('gmd:status/gmd:MD_ProgressCode', namespaces)))

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

            for i in md.findall(util.nspath_eval('gmd:descriptiveKeywords', namespaces)):
                mdkw = {}
                mdkw['type'] = _testCodeListValue(i.find(util.nspath_eval('gmd:MD_Keywords/gmd:type/gmd:MD_KeywordTypeCode', namespaces)))

                mdkw['thesaurus'] = {}

                val = i.find(util.nspath_eval('gmd:MD_Keywords/gmd:thesaurusName/gmd:CI_Citation/gmd:title/gco:CharacterString', namespaces))
                mdkw['thesaurus']['title'] = util.testXMLValue(val)

                val = i.find(util.nspath_eval('gmd:MD_Keywords/gmd:thesaurusName/gmd:CI_Citation/gmd:date/gmd:CI_Date/gmd:date/gco:Date', namespaces))
                mdkw['thesaurus']['date'] = util.testXMLValue(val)

                val = i.find(util.nspath_eval('gmd:MD_Keywords/gmd:thesaurusName/gmd:CI_Citation/gmd:date/gmd:CI_Date/gmd:dateType/gmd:CI_DateTypeCode', namespaces))
                mdkw['thesaurus']['datetype'] = util.testXMLValue(val)

                mdkw['keywords'] = []

                for k in i.findall(util.nspath_eval('gmd:MD_Keywords/gmd:keyword', namespaces)):
                    val = k.find(util.nspath_eval('gco:CharacterString', namespaces))
                    if val is not None:
                        val2 = util.testXMLValue(val) 
                        if val2 is not None:
                            mdkw['keywords'].append(val2)

                self.keywords.append(mdkw)

            self.topiccategory = []
            for i in md.findall(util.nspath_eval('gmd:topicCategory/gmd:MD_TopicCategoryCode', namespaces)):
                val = util.testXMLValue(i)
                if val is not None:
                    self.topiccategory.append(val)
            
            val = md.find(util.nspath_eval('gmd:supplementalInformation/gco:CharacterString', namespaces))
            self.supplementalinformation = util.testXMLValue(val)
            
            # There may be multiple geographicElement, create an extent
            # from the one containing either an EX_GeographicBoundingBox or EX_BoundingPolygon.
            # The schema also specifies an EX_GeographicDescription. This is not implemented yet.
            val = None
            val2 = None
            val3 = None
            extents = md.findall(util.nspath_eval('gmd:extent', namespaces))
            extents.extend(md.findall(util.nspath_eval('srv:extent', namespaces)))
            for extent in extents:
                if val is None:
                    for e in extent.findall(util.nspath_eval('gmd:EX_Extent/gmd:geographicElement', namespaces)):
                        if e.find(util.nspath_eval('gmd:EX_GeographicBoundingBox', namespaces)) is not None or e.find(util.nspath_eval('gmd:EX_BoundingPolygon', namespaces)) is not None:
                            val = e
                            break
                    self.extent = EX_Extent(val)
                    self.bbox = self.extent.boundingBox  # for backwards compatibility

                if val2 is None:
                    val2 = extent.find(util.nspath_eval('gmd:EX_Extent/gmd:temporalElement/gmd:EX_TemporalExtent/gmd:extent/gml:TimePeriod/gml:beginPosition', namespaces))
                    if val2 is None:
                        val2 = extent.find(util.nspath_eval('gmd:EX_Extent/gmd:temporalElement/gmd:EX_TemporalExtent/gmd:extent/gml32:TimePeriod/gml32:beginPosition', namespaces))
                    self.temporalextent_start = util.testXMLValue(val2)

                if val3 is None:
                    val3 = extent.find(util.nspath_eval('gmd:EX_Extent/gmd:temporalElement/gmd:EX_TemporalExtent/gmd:extent/gml:TimePeriod/gml:endPosition', namespaces))
                    if val3 is None:
                        val3 = extent.find(util.nspath_eval('gmd:EX_Extent/gmd:temporalElement/gmd:EX_TemporalExtent/gmd:extent/gml32:TimePeriod/gml32:endPosition', namespaces))
                    self.temporalextent_end = util.testXMLValue(val3)
Exemple #33
0
 def __init__(self, root):
     self.latitude = float(testXMLValue(root.find("Latitude")))
     self.longitude = float(testXMLValue(root.find("Longitude")))
     self.state = testXMLValue(root.find("State"))
     if len(self.state) < 3:  # upper case if state initials
         self.state = self.state.upper()
Exemple #34
0
    def __init__(self, md=None):
        if md is None:
            self.title = None
            self.abstract = None
            self.contact = None
            self.identtype = 'service'
            self.type = None
            self.version = None
            self.fees = None
            self.bbox = None
            self.couplingtype = None
            self.operations = []
            self.operateson = []
        else:
            val=md.find(util.nspath_eval('gmd:citation/gmd:CI_Citation/gmd:title/gco:CharacterString', namespaces))
            self.title=util.testXMLValue(val)
            
            val=md.find(util.nspath_eval('gmd:abstract/gco:CharacterString', namespaces))
            self.abstract=util.testXMLValue(val)
            
            self.contact = None
            val = md.find(util.nspath_eval('gmd:citation/gmd:CI_Citation/gmd:citedResponsibleParty/gmd:CI_ResponsibleParty', namespaces))
            if val is not None:
                self.contact = CI_ResponsibleParty(val)
            
            self.identtype = 'service'
            val = md.find(util.nspath_eval('srv:serviceType/gco:LocalName', namespaces))
            self.type = util.testXMLValue(val)
          
            val = md.find(util.nspath_eval('srv:serviceTypeVersion/gco:CharacterString', namespaces))
            self.version = util.testXMLValue(val)

            val = md.find(util.nspath_eval('srv:accessProperties/gmd:MD_StandardOrderProcess/gmd:fees/gco:CharacterString', namespaces))
            self.fees = util.testXMLValue(val)

            val = md.find(util.nspath_eval('srv:extent/gmd:EX_Extent', namespaces))

            if val is not None:
                self.bbox = EX_Extent(val)
            else:
                self.bbox = None

            self.couplingtype = _testCodeListValue(md.find(util.nspath_eval('gmd:couplingType/gmd:SV_CouplingType', namespaces)))

            self.operations = []

            for i in md.findall(util.nspath_eval('srv:containsOperations', namespaces)):
                tmp = {}
                val = i.find(util.nspath_eval('srv:SV_OperationMetadata/srv:operationName/gco:CharacterString', namespaces))
                tmp['name'] = util.testXMLValue(val)
                tmp['dcplist'] = []
                for d in i.findall(util.nspath_eval('srv:SV_OperationMetadata/srv:DCP', namespaces)):
                    tmp2 = _testCodeListValue(d.find(util.nspath_eval('srv:DCPList', namespaces)))
                    tmp['dcplist'].append(tmp2)
             
                tmp['connectpoint'] = []
     
                for d in i.findall(util.nspath_eval('srv:SV_OperationMetadata/srv:connectPoint', namespaces)):
                    tmp3 = d.find(util.nspath_eval('gmd:CI_OnlineResource', namespaces))
                    tmp['connectpoint'].append(CI_OnlineResource(tmp3))
                self.operations.append(tmp)

            self.operateson = []
             
            for i in md.findall(util.nspath_eval('srv:operatesOn', namespaces)):
                tmp = {}
                tmp['uuidref'] = i.attrib.get('uuidref')
                tmp['href'] = i.attrib.get(util.nspath_eval('xlink:href', namespaces))
                tmp['title'] = i.attrib.get(util.nspath_eval('xlink:title', namespaces))
                self.operateson.append(tmp)
Exemple #35
0
    def __init__(self, record):

        if hasattr(record, 'getroot'):  # standalone document
            self.xml = etree.tostring(record.getroot())
        else:  # part of a larger document
            self.xml = etree.tostring(record)

        # check to see if Dublin Core record comes from
        # rdf:RDF/rdf:Description container
        # (child content model is identical)
        self.rdf = False
        rdf = record.find(util.nspath_eval('rdf:Description', namespaces))
        if rdf is not None:
            self.rdf = True
            record = rdf

        # some CSWs return records with multiple identifiers based on
        # different schemes.  Use the first dc:identifier value to set
        # self.identifier, and set self.identifiers as a list of dicts
        val = record.find(util.nspath_eval('dc:identifier', namespaces))
        self.identifier = util.testXMLValue(val)

        self.identifiers = []
        for i in record.findall(util.nspath_eval('dc:identifier', namespaces)):
            d = {}
            d['scheme'] = i.attrib.get('scheme')
            d['identifier'] = i.text
            self.identifiers.append(d)

        val = record.find(util.nspath_eval('dc:type', namespaces))
        self.type = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dc:title', namespaces))
        self.title = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dct:alternative', namespaces))
        self.alternative = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dct:isPartOf', namespaces))
        self.ispartof = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dct:abstract', namespaces))
        self.abstract = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dc:date', namespaces))
        self.date = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dct:created', namespaces))
        self.created = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dct:issued', namespaces))
        self.issued = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dc:relation', namespaces))
        self.relation = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dct:temporal', namespaces))
        self.temporal = util.testXMLValue(val)

        self.uris = []  # list of dicts
        for i in record.findall(util.nspath_eval('dc:URI', namespaces)):
            uri = {}
            uri['protocol'] = util.testXMLValue(i.attrib.get('protocol'), True)
            uri['name'] = util.testXMLValue(i.attrib.get('name'), True)
            uri['description'] = util.testXMLValue(i.attrib.get('description'),
                                                   True)
            uri['url'] = util.testXMLValue(i)

            self.uris.append(uri)

        self.references = []  # list of dicts
        for i in record.findall(util.nspath_eval('dct:references',
                                                 namespaces)):
            ref = {}
            ref['scheme'] = util.testXMLValue(i.attrib.get('scheme'), True)
            ref['url'] = util.testXMLValue(i)

            self.references.append(ref)

        val = record.find(util.nspath_eval('dct:modified', namespaces))
        self.modified = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dc:creator', namespaces))
        self.creator = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dc:publisher', namespaces))
        self.publisher = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dc:coverage', namespaces))
        self.coverage = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dc:contributor', namespaces))
        self.contributor = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dc:language', namespaces))
        self.language = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dc:source', namespaces))
        self.source = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dct:rightsHolder', namespaces))
        self.rightsholder = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dct:accessRights', namespaces))
        self.accessrights = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dct:license', namespaces))
        self.license = util.testXMLValue(val)

        val = record.find(util.nspath_eval('dc:format', namespaces))
        self.format = util.testXMLValue(val)

        self.subjects = []
        for i in record.findall(util.nspath_eval('dc:subject', namespaces)):
            self.subjects.append(util.testXMLValue(i))

        self.rights = []
        for i in record.findall(util.nspath_eval('dc:rights', namespaces)):
            self.rights.append(util.testXMLValue(i))

        val = record.find(util.nspath_eval('dct:spatial', namespaces))
        self.spatial = util.testXMLValue(val)

        val = record.find(util.nspath_eval('ows:BoundingBox', namespaces))
        if val is not None:
            self.bbox = ows.BoundingBox(val, namespaces['ows'])
        else:
            self.bbox = None

        val = record.find(util.nspath_eval('ows:WGS84BoundingBox', namespaces))
        if val is not None:
            self.bbox_wgs84 = ows.WGS84BoundingBox(val, namespaces['ows'])
        else:
            self.bbox_wgs84 = None
Exemple #36
0
class SosObservationOffering(object):
    def __init__(self, element):
        self._root = element

        self.id = testXMLValue(
            self._root.find(nspath_eval('swes:identifier', namespaces)))
        if self.id is None:
            self.id = testXMLValue(
                self._root.attrib.get(nspath_eval('swes:id', namespaces)),
                True)
        self.description = testXMLValue(
            self._root.find(nspath_eval('swes:description', namespaces)))
        self.name = testXMLValue(
            self._root.find(nspath_eval('swes:name', namespaces)))

        # sos:observedArea
        try:
            envelope = self._root.find(
                nspath_eval('sos:observedArea/gml32:Envelope', namespaces))
            lower_left_corner = testXMLValue(
                envelope.find(nspath_eval('gml32:lowerCorner',
                                          namespaces))).split()
            upper_right_corner = testXMLValue(
                envelope.find(nspath_eval('gml32:upperCorner',
                                          namespaces))).split()
            # (left, bottom, right, top) in self.bbox_srs units
            self.bbox = (float(lower_left_corner[1]),
                         float(lower_left_corner[0]),
                         float(upper_right_corner[1]),
                         float(upper_right_corner[0]))
            self.bbox_srs = Crs(
                testXMLValue(envelope.attrib.get('srsName'), True))
        except Exception, err:
            self.bbox = None
            self.bbox_srs = None

        # LOOK: Support all gml:TimeGeometricPrimitivePropertyType
        # Right now we are just supporting gml:TimePeriod
        # sos:Time
        begin_position_element = self._root.find(
            nspath_eval(
                'sos:phenomenonTime/gml32:TimePeriod/gml32:beginPosition',
                namespaces))
        self.begin_position = extract_time(begin_position_element)
        end_position_element = self._root.find(
            nspath_eval(
                'sos:phenomenonTime/gml32:TimePeriod/gml32:endPosition',
                namespaces))
        self.end_position = extract_time(end_position_element)

        self.procedures = []
        for proc in self._root.findall(
                nspath_eval('swes:procedure', namespaces)):
            self.procedures.append(testXMLValue(proc))

        self.procedure_description_formats = []
        for proc in self._root.findall(
                nspath_eval('swes:procedureDescriptionFormat', namespaces)):
            self.procedure_description_formats.append(testXMLValue(proc))

        # LOOK: Support swe:Phenomenon here
        # this includes compound properties
        self.observed_properties = []
        for op in self._root.findall(
                nspath_eval('swes:observableProperty', namespaces)):
            self.observed_properties.append(testXMLValue(op))

        self.features_of_interest = []
        for fot in self._root.findall(
                nspath_eval('sos:featureOfInterest', namespaces)):
            self.features_of_interest.append(
                testXMLValue(
                    fot.attrib.get(nspath_eval('xlink:href', namespaces)),
                    True))

        self.response_formats = []
        for rf in self._root.findall(
                nspath_eval('sos:responseFormat', namespaces)):
            self.response_formats.append(testXMLValue(rf))

        self.observation_models = []
        for om in self._root.findall(
                nspath_eval('sos:observationType', namespaces)):
            self.observation_models.append(testXMLValue(om))
Exemple #37
0
    def __init__(self, elem, parent=None, children=None, index=0,
                 parse_remote_metadata=False, timeout=30, auth=None):
        super(ContentMetadata, self).__init__(auth)
        if 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('Name'))

        # 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('Title'))
        if title is not None:
            self.title = title.strip()

        self.abstract = testXMLValue(elem.find('Abstract'))

        # bboxes
        b = elem.find('BoundingBox')
        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

        # ScaleHint
        sh = elem.find('ScaleHint')
        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('Attribution')
        if attribution is not None:
            self.attribution = dict()
            title = attribution.find('Title')
            url = attribution.find('OnlineResource')
            logo = attribution.find('LogoURL')
            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('OnlineResource').attrib['{http://www.w3.org/1999/xlink}href']

        b = elem.find('LatLonBoundingBox')
        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

        # 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('SRS') 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('SRS')]:
                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('Style'):
            name = s.find('Name')
            title = s.find('Title')
            if name is None and title is None:
                raise ValueError('%s missing name and title' % (s,))
            if name is None or title is None:
                warnings.warn('%s missing name or title' % (s,))
            title_ = title.text if title is not None else name.text
            name_ = name.text if name is not None else title.text
            style = {'title': title_}
            # legend url
            legend = s.find('LegendURL/OnlineResource')
            if legend is not None:
                style['legend'] = legend.attrib['{http://www.w3.org/1999/xlink}href']
            self.styles[name_] = style

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

        # timepositions - times for which data is available.
        self.timepositions = None
        self.defaulttimeposition = None
        for extent in elem.findall('Extent'):
            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('Extent'):
            if extent.attrib.get("name").lower() == 'elevation':
                if extent.text:
                    self.elevations = extent.text.split(',')
                    break

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

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

        self.layers = []
        for child in elem.findall('Layer'):
            self.layers.append(ContentMetadata(child, self))
Exemple #38
0
 def __init__(self, infoset):
     self._root = infoset
     self.name = testXMLValue(self._root.find(nspath('Name')))
     self.url = testXMLValue(self._root.find(nspath('OnlineResource')))
     self.keywords = extract_xml_list(self._root.find(nspath('Keywords')))
Exemple #39
0
    def __init__(self,
                 elem,
                 parent,
                 parse_remote_metadata=False,
                 timeout=30,
                 auth=None):
        """."""
        super(ContentMetadata, self).__init__(auth)
        self.id = testXMLValue(elem.find(nspath('Name')))
        self.title = testXMLValue(elem.find(nspath('Title')))
        self.abstract = testXMLValue(elem.find(nspath('Abstract')))
        self.keywords = [f.text for f in elem.findall(nspath('Keywords'))]

        # bboxes
        self.boundingBox = None
        b = elem.find(nspath('LatLongBoundingBox'))
        srs = elem.find(nspath('SRS'))

        if b is not None:
            self.boundingBox = (float(b.attrib['minx']), float(
                b.attrib['miny']), float(b.attrib['maxx']),
                                float(b.attrib['maxy']), Crs(srs.text))

        # transform wgs84 bbox from given default bboxt
        self.boundingBoxWGS84 = None

        if b is not None and srs is not None:
            wgs84 = pyproj.Proj(init="epsg:4326")
            try:
                src_srs = pyproj.Proj(init=srs.text)
                mincorner = pyproj.transform(src_srs, wgs84, b.attrib['minx'],
                                             b.attrib['miny'])
                maxcorner = pyproj.transform(src_srs, wgs84, b.attrib['maxx'],
                                             b.attrib['maxy'])

                self.boundingBoxWGS84 = (mincorner[0], mincorner[1],
                                         maxcorner[0], maxcorner[1])
            except RuntimeError as e:
                pass

        # crs options
        self.crsOptions = [
            Crs(srs.text) for srs in elem.findall(nspath('SRS'))
        ]

        # verbs
        self.verbOptions = [op.tag for op \
            in parent.findall(nspath('Operations/*'))]
        self.verbOptions + [op.tag for op \
            in elem.findall(nspath('Operations/*')) \
            if op.tag not in self.verbOptions]

        #others not used but needed for iContentMetadata harmonisation
        self.styles = None
        self.timepositions = None
        self.defaulttimeposition = None

        # MetadataURLs
        self.metadataUrls = []
        for m in elem.findall(nspath('MetadataURL')):
            metadataUrl = {
                'type': testXMLValue(m.attrib['type'], attrib=True),
                'format': testXMLValue(m.attrib['format'], attrib=True),
                'url': testXMLValue(m)
            }
            self.metadataUrls.append(metadataUrl)
Exemple #40
0
 def __init__(self, md):
     val = md.find(util.nspath_eval('dif:Start_Date', namespaces))
     self.start_date = util.testXMLValue(val)
     
     val = md.find(util.nspath_eval('dif:End_Date', namespaces))
     self.end_date = util.testXMLValue(val)
Exemple #41
0
 def __init__(self, md):
     if md is None:
         pass
     else:
         val = md.find(util.nspath_eval('gmd:referenceSystemIdentifier/gmd:RS_Identifier/gmd:code/gco:CharacterString', namespaces))
         self.code = util.testXMLValue(val)
Exemple #42
0
    def harvest(self,
                source,
                resourcetype,
                resourceformat=None,
                harvestinterval=None,
                responsehandler=None):
        """

        Construct and process a Harvest request

        Parameters
        ----------

        - source: a URI to harvest
        - resourcetype: namespace identifying the type of resource
        - resourceformat: MIME type of the resource
        - harvestinterval: frequency of harvesting, in ISO8601
        - responsehandler: endpoint that CSW should responsd to with response

        """

        # construct request
        node0 = self._setrootelement('csw:Harvest')
        node0.set('version', self.version)
        node0.set('service', self.service)
        node0.set(util.nspath_eval('xsi:schemaLocation', namespaces),
                  schema_location)
        etree.SubElement(node0, util.nspath_eval('csw:Source',
                                                 namespaces)).text = source
        etree.SubElement(node0,
                         util.nspath_eval('csw:ResourceType',
                                          namespaces)).text = resourcetype
        if resourceformat is not None:
            etree.SubElement(
                node0, util.nspath_eval('csw:ResourceFormat',
                                        namespaces)).text = resourceformat
        if harvestinterval is not None:
            etree.SubElement(
                node0, util.nspath_eval('csw:HarvestInterval',
                                        namespaces)).text = harvestinterval
        if responsehandler is not None:
            etree.SubElement(
                node0, util.nspath_eval('csw:ResponseHandler',
                                        namespaces)).text = responsehandler

        self.request = node0

        self._invoke()
        self.results = {}

        if self.exceptionreport is None:
            val = self._exml.find(
                util.nspath_eval('csw:Acknowledgement', namespaces))
            if util.testXMLValue(val) is not None:
                ts = val.attrib.get('timeStamp')
                self.timestamp = util.testXMLValue(ts, True)
                id = val.find(util.nspath_eval('csw:RequestId', namespaces))
                self.id = util.testXMLValue(id)
            else:
                self._parsetransactionsummary()
                self._parseinsertresult()
Exemple #43
0
    def __init__(self, element, wqx_ns):
        self._root = element

        des = self._root.find(nsp("ActivityDescription", wqx_ns))
        if des is not None:
            self.id = testXMLValue(des.find(nsp("ActivityIdentifier", wqx_ns)))
            self.type = testXMLValue(des.find(nsp("ActivityTypeCode", wqx_ns)))
            self.media = testXMLValue(
                des.find(nsp("ActivityMediaName", wqx_ns)))

        # Date/Time
        sd = testXMLValue(des.find(nsp("ActivityStartDate",
                                       wqx_ns)))  # YYYY-MM-DD
        parse_string = "%s" % sd

        st = des.find(nsp("ActivityStartTime", wqx_ns))
        # If no time is defined, skip trying to pull it out and just use the date
        if st is not None:
            t = testXMLValue(st.find(nsp("Time", wqx_ns)))
            tz = testXMLValue(st.find(nsp("TimeZoneCode", wqx_ns)))

            parse_string = "%s %s" % (parse_string, t)
            if tz is not None:
                parse_string = "%s %s" % (parse_string, tz)

        self.start_time = AsaTime.parse(parse_string)
        if self.start_time.tzinfo is None:
            self.start_time = self.start_time.replace(tzinfo=pytz.utc)

        self.project = testXMLValue(des.find(nsp("ProjectIdentifier", wqx_ns)))
        self.location_id = testXMLValue(
            des.find(nsp("MonitoringLocationIdentifier", wqx_ns)))
        self.comment = testXMLValue(
            des.find(nsp("ActivityCommentText", wqx_ns)))

        self.method_id = None
        self.method_name = None
        self.method_context = None
        # Method
        smpl = self._root.find(nsp("SampleDescription", wqx_ns))
        if smpl is not None:
            self.sample_collection_equipment_name = testXMLValue(
                smpl.find(nsp("SampleCollectionEquipmentName", wqx_ns)))
            smplcol = smpl.find(nsp("SampleCollectionMethod", wqx_ns))
            if smplcol is not None:
                self.method_id = testXMLValue(
                    smplcol.find(nsp("MethodIdentifier", wqx_ns)))
                self.method_context = testXMLValue(
                    smplcol.find(nsp("MethodIdentifierContext", wqx_ns)))
                self.method_name = testXMLValue(
                    smplcol.find(nsp("MethodName", wqx_ns)))

        self.results = []
        for res in self._root.findall(nsp("Result", wqx_ns)):
            self.results.append(WqxResult(res, wqx_ns))
Exemple #44
0
    def getrecords(self,
                   qtype=None,
                   keywords=[],
                   typenames='csw:Record',
                   propertyname='csw:AnyText',
                   bbox=None,
                   esn='summary',
                   sortby=None,
                   outputschema=namespaces['csw'],
                   format=outputformat,
                   startposition=0,
                   maxrecords=10,
                   cql=None,
                   xml=None,
                   resulttype='results'):
        """

        Construct and process a  GetRecords request

        Parameters
        ----------

        - qtype: type of resource to query (i.e. service, dataset)
        - keywords: list of keywords
        - typenames: the typeNames to query against (default is csw:Record)
        - propertyname: the PropertyName to Filter against
        - bbox: the bounding box of the spatial query in the form [minx,miny,maxx,maxy]
        - esn: the ElementSetName 'full', 'brief' or 'summary' (default is 'summary')
        - sortby: property to sort results on
        - outputschema: the outputSchema (default is 'http://www.opengis.net/cat/csw/2.0.2')
        - format: the outputFormat (default is 'application/xml')
        - startposition: requests a slice of the result set, starting at this position (default is 0)
        - maxrecords: the maximum number of records to return. No records are returned if 0 (default is 10)
        - cql: common query language text.  Note this overrides bbox, qtype, keywords
        - xml: raw XML request.  Note this overrides all other options
        - resulttype: the resultType 'hits', 'results', 'validate' (default is 'results')

        """

        warnings.warn(
            """Please use the updated 'getrecords2' method instead of 'getrecords'.
        The 'getrecords' method will be upgraded to use the 'getrecords2' parameters
        in a future version of OWSLib.""")

        if xml is not None:
            self.request = etree.fromstring(xml)
            val = self.request.find(
                util.nspath_eval('csw:Query/csw:ElementSetName', namespaces))
            if val is not None:
                esn = util.testXMLValue(val)
        else:
            # construct request
            node0 = self._setrootelement('csw:GetRecords')
            if etree.__name__ != 'lxml.etree':  # apply nsmap manually
                node0.set('xmlns:ows', namespaces['ows'])
                node0.set('xmlns:gmd', namespaces['gmd'])
                node0.set('xmlns:dif', namespaces['dif'])
                node0.set('xmlns:fgdc', namespaces['fgdc'])
            node0.set('outputSchema', outputschema)
            node0.set('outputFormat', format)
            node0.set('version', self.version)
            node0.set('resultType', resulttype)
            node0.set('service', self.service)
            if startposition > 0:
                node0.set('startPosition', str(startposition))
            node0.set('maxRecords', str(maxrecords))
            node0.set(util.nspath_eval('xsi:schemaLocation', namespaces),
                      schema_location)

            node1 = etree.SubElement(node0,
                                     util.nspath_eval('csw:Query', namespaces))
            node1.set('typeNames', typenames)

            etree.SubElement(
                node1, util.nspath_eval('csw:ElementSetName',
                                        namespaces)).text = esn

            self._setconstraint(node1, qtype, propertyname, keywords, bbox,
                                cql, None)

            if sortby is not None:
                fes.setsortby(node1, sortby)

            self.request = node0

        self._invoke()

        if self.exceptionreport is None:
            self.results = {}

            # process search results attributes
            val = self._exml.find(
                util.nspath_eval(
                    'csw:SearchResults',
                    namespaces)).attrib.get('numberOfRecordsMatched')
            self.results['matches'] = int(util.testXMLValue(val, True))
            val = self._exml.find(
                util.nspath_eval(
                    'csw:SearchResults',
                    namespaces)).attrib.get('numberOfRecordsReturned')
            self.results['returned'] = int(util.testXMLValue(val, True))
            val = self._exml.find(
                util.nspath_eval('csw:SearchResults',
                                 namespaces)).attrib.get('nextRecord')
            self.results['nextrecord'] = int(util.testXMLValue(val, True))

            # process list of matching records
            self.records = OrderedDict()

            self._parserecords(outputschema, esn)
Exemple #45
0
    def __init__(self,
                 elem,
                 parent=None,
                 children=None,
                 index=0,
                 parse_remote_metadata=False,
                 timeout=30,
                 auth=None):
        super(ContentMetadata, self).__init__(auth)

        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
        self.scaleHint = None
        self.min_scale_denominator = elem.find(
            nspath('MinScaleDenominator', WMS_NAMESPACE))
        min_scale_hint = 0 if self.min_scale_denominator is None else \
            float(self.min_scale_denominator.text) * SCALEDENOM_TO_RESOLUTION
        self.max_scale_denominator = elem.find(
            nspath('MaxScaleDenominator', WMS_NAMESPACE))
        max_scale_hint = 0 if self.max_scale_denominator is None else \
            float(self.max_scale_denominator.text) * SCALEDENOM_TO_RESOLUTION
        if self.min_scale_denominator is not None or self.max_scale_denominator is not None:
            self.scaleHint = {'min': min_scale_hint, 'max': max_scale_hint}

        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 and title is None:
                raise ValueError('%s missing name and title' % (s, ))
            if name is None or title is None:
                warnings.warn('%s missing name or title' % (s, ))
            title_ = title.text if title is not None else name.text
            name_ = name.text if name is not None else title.text
            style = {'title': title_}
            # 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_] = 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('name') == 'elevation':
                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 list(dim.attrib.items()):
                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)
            }
            self.metadataUrls.append(metadataUrl)

        if parse_remote_metadata:
            self.parse_remote_metadata(timeout)

        # DataURLs
        self.dataUrls = []
        for m in elem.findall(nspath('DataURL', WMS_NAMESPACE)):
            dataUrl = {
                'format':
                m.find(nspath('Format', WMS_NAMESPACE)).text,
                'url':
                m.find(nspath('OnlineResource', WMS_NAMESPACE)).
                attrib['{http://www.w3.org/1999/xlink}href']
            }
            if dataUrl['format'] is not None:
                dataUrl['format'] = dataUrl['format'].strip()
            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))
Exemple #46
0
    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
Exemple #47
0
    def getrecords2(self,
                    constraints=[],
                    sortby=None,
                    typenames='csw:Record',
                    esn='summary',
                    outputschema=namespaces['csw'],
                    format=outputformat,
                    startposition=0,
                    maxrecords=10,
                    cql=None,
                    xml=None,
                    resulttype='results',
                    distributedsearch=False,
                    hopcount=1):
        """

        Construct and process a  GetRecords request

        Parameters
        ----------

        - constraints: the list of constraints (OgcExpression from owslib.fes module)
        - sortby: an OGC SortBy object (SortBy from owslib.fes module)
        - typenames: the typeNames to query against (default is csw:Record)
        - esn: the ElementSetName 'full', 'brief' or 'summary' (default is 'summary')
        - outputschema: the outputSchema (default is 'http://www.opengis.net/cat/csw/2.0.2')
        - format: the outputFormat (default is 'application/xml')
        - startposition: requests a slice of the result set, starting at this position (default is 0)
        - maxrecords: the maximum number of records to return. No records are returned if 0 (default is 10)
        - cql: common query language text.  Note this overrides bbox, qtype, keywords
        - xml: raw XML request.  Note this overrides all other options
        - resulttype: the resultType 'hits', 'results', 'validate' (default is 'results')
        - distributedsearch: `bool` of whether to trigger distributed search
        - hopcount: number of message hops before search is terminated (default is 1)

        """

        if xml is not None:
            if xml.startswith(b'<'):
                self.request = etree.fromstring(xml)
                val = self.request.find(
                    util.nspath_eval('csw:Query/csw:ElementSetName',
                                     namespaces))
                if val is not None:
                    esn = util.testXMLValue(val)
                val = self.request.attrib.get('outputSchema')
                if val is not None:
                    outputschema = util.testXMLValue(val, True)
            else:
                self.request = xml
        else:
            # construct request
            node0 = self._setrootelement('csw:GetRecords')
            if etree.__name__ != 'lxml.etree':  # apply nsmap manually
                node0.set('xmlns:ows', namespaces['ows'])
                node0.set('xmlns:gmd', namespaces['gmd'])
                node0.set('xmlns:dif', namespaces['dif'])
                node0.set('xmlns:fgdc', namespaces['fgdc'])
            node0.set('outputSchema', outputschema)
            node0.set('outputFormat', format)
            node0.set('version', self.version)
            node0.set('service', self.service)
            node0.set('resultType', resulttype)
            if startposition > 0:
                node0.set('startPosition', str(startposition))
            node0.set('maxRecords', str(maxrecords))
            node0.set(util.nspath_eval('xsi:schemaLocation', namespaces),
                      schema_location)

            if distributedsearch:
                etree.SubElement(node0,
                                 util.nspath_eval('csw:DistributedSearch',
                                                  namespaces),
                                 hopCount=str(hopcount))

            node1 = etree.SubElement(node0,
                                     util.nspath_eval('csw:Query', namespaces))
            node1.set('typeNames', typenames)

            etree.SubElement(
                node1, util.nspath_eval('csw:ElementSetName',
                                        namespaces)).text = esn

            if any([len(constraints) > 0, cql is not None]):
                node2 = etree.SubElement(
                    node1, util.nspath_eval('csw:Constraint', namespaces))
                node2.set('version', '1.1.0')
                flt = fes.FilterRequest()
                if len(constraints) > 0:
                    node2.append(flt.setConstraintList(constraints))
                # Now add a CQL filter if passed in
                elif cql is not None:
                    etree.SubElement(
                        node2, util.nspath_eval('csw:CqlText',
                                                namespaces)).text = cql

            if sortby is not None and isinstance(sortby, fes.SortBy):
                node1.append(sortby.toXML())

            self.request = node0

        self._invoke()

        if self.exceptionreport is None:
            self.results = {}

            # process search results attributes
            val = self._exml.find(
                util.nspath_eval(
                    'csw:SearchResults',
                    namespaces)).attrib.get('numberOfRecordsMatched')
            self.results['matches'] = int(util.testXMLValue(val, True))
            val = self._exml.find(
                util.nspath_eval(
                    'csw:SearchResults',
                    namespaces)).attrib.get('numberOfRecordsReturned')
            self.results['returned'] = int(util.testXMLValue(val, True))
            val = self._exml.find(
                util.nspath_eval('csw:SearchResults',
                                 namespaces)).attrib.get('nextRecord')
            if val is not None:
                self.results['nextrecord'] = int(util.testXMLValue(val, True))
            else:
                warnings.warn(
                    """CSW Server did not supply a nextRecord value (it is optional), so the client
                should page through the results in another way.""")
                # For more info, see:
                # https://github.com/geopython/OWSLib/issues/100
                self.results['nextrecord'] = None

            # process list of matching records
            self.records = OrderedDict()

            self._parserecords(outputschema, esn)
Exemple #48
0
    def __init__(self, md):
        """constructor"""

        _GenericObject.__init__(self, md)

        self.denominator = util.testXMLValue(md.find(util.nspath_eval('gm03:denominator', namespaces)))
Exemple #49
0
    def __init__(self, md=None):
        if md is None:
            self.conformancetitle = []
            self.conformancedate = []
            self.conformancedatetype = []
            self.conformancedegree = []
            self.lineage = None
            self.specificationtitle = None
            self.specificationdate = []
        else:
            self.conformancetitle = []
            for i in md.findall(
                    util.nspath_eval(
                        'gmd:report/gmd:DQ_DomainConsistency/gmd:result/gmd:DQ_ConformanceResult/gmd:specification/gmd:CI_Citation/gmd:title/gco:CharacterString',
                        namespaces)):
                val = util.testXMLValue(i)
                if val is not None:
                    self.conformancetitle.append(val)

            self.conformancedate = []
            for i in md.findall(
                    util.nspath_eval(
                        'gmd:report/gmd:DQ_DomainConsistency/gmd:result/gmd:DQ_ConformanceResult/gmd:specification/gmd:CI_Citation/gmd:date/gmd:CI_Date/gmd:date/gco:Date',
                        namespaces)):
                val = util.testXMLValue(i)
                if val is not None:
                    self.conformancedate.append(val)

            self.conformancedatetype = []
            for i in md.findall(
                    util.nspath_eval(
                        'gmd:report/gmd:DQ_DomainConsistency/gmd:result/gmd:DQ_ConformanceResult/gmd:specification/gmd:CI_Citation/gmd:date/gmd:CI_Date/gmd:dateType/gmd:CI_DateTypeCode',
                        namespaces)):
                val = _testCodeListValue(i)
                if val is not None:
                    self.conformancedatetype.append(val)

            self.conformancedegree = []
            for i in md.findall(
                    util.nspath_eval(
                        'gmd:report/gmd:DQ_DomainConsistency/gmd:result/gmd:DQ_ConformanceResult/gmd:pass/gco:Boolean',
                        namespaces)):
                val = util.testXMLValue(i)
                if val is not None:
                    self.conformancedegree.append(val)

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

            val = md.find(
                util.nspath_eval(
                    'gmd:report/gmd:DQ_DomainConsistency/gmd:result/gmd:DQ_ConformanceResult/gmd:specification/gmd:CI_Citation/gmd:title/gco:CharacterString',
                    namespaces))
            self.specificationtitle = util.testXMLValue(val)

            self.specificationdate = []
            for i in md.findall(
                    util.nspath_eval(
                        'gmd:report/gmd:DQ_DomainConsistency/gmd:result/gmd:DQ_ConformanceResult/gmd:specification/gmd:CI_Citation/gmd:date/gmd:CI_Date',
                        namespaces)):
                val = util.testXMLValue(i)
                if val is not None:
                    self.specificationdate.append(val)
Exemple #50
0
    def __init__(self, element, wqx_ns):
        self._root = element

        self.id = None
        self.name = None
        self.type = None
        self.description = None
        self.huc = None
        identity = self._root.find(nsp("MonitoringLocationIdentity", wqx_ns))
        if identity is not None:
            self.id = testXMLValue(
                identity.find(nsp("MonitoringLocationIdentifier", wqx_ns)))
            self.name = testXMLValue(
                identity.find(nsp("MonitoringLocationName", wqx_ns)))
            self.type = testXMLValue(
                identity.find(nsp("MonitoringLocationTypeName", wqx_ns)))
            self.description = testXMLValue(
                identity.find(nsp("MonitoringLocationDescriptionText",
                                  wqx_ns)))
            self.huc = testXMLValue(
                identity.find(nsp("HUCEightDigitCode", wqx_ns)))

        self.latitude = None
        self.longitude = None
        self.map_scale = None
        self.horizontal_collection_method = None
        self.horizontal_crs_name = None
        self.horizontal_crs = None
        self.vertical_crs_name = None
        self.vertical_crs = None
        geo = self._root.find(nsp("MonitoringLocationGeospatial", wqx_ns))
        if geo is not None:
            self.latitude = testXMLValue(
                geo.find(nsp("LatitudeMeasure", wqx_ns)))
            self.longitude = testXMLValue(
                geo.find(nsp("LongitudeMeasure", wqx_ns)))
            self.map_scale = testXMLValue(
                geo.find(nsp("SourceMapScaleNumeric", wqx_ns)))
            self.horizontal_collection_method = testXMLValue(
                geo.find(nsp("HorizontalCollectionMethodName", wqx_ns)))
            self.horizontal_crs_name = testXMLValue(
                geo.find(
                    nsp("HorizontalCoordinateReferenceSystemDatumName",
                        wqx_ns)))
            # self.horizontal_crs = Crs("EPSG:" + testXMLValue(geo.find(nsp("HorizontalCoordinateReferenceSystemDatumName", wqx_ns))))
            self.vertical_crs_name = testXMLValue(
                geo.find(nsp("VerticalCollectionMethodName", wqx_ns)))
            # self.vertical_crs = Crs(testXMLValue("EPSG:" + geo.find(nsp("VerticalCoordinateReferenceSystemDatumName", wqx_ns))))

        self.vertical_measure_value = None
        self.vertical_measure_units = None
        vm = geo.find(nsp("VerticalMeasure", wqx_ns))
        if vm is not None:
            self.vertical_measure_value = testXMLValue(
                vm.find(nsp("MeasureValue", wqx_ns)))
            self.vertical_measure_units = testXMLValue(
                vm.find(nsp("MeasureUnitCode", wqx_ns)))

        self.country = testXMLValue(geo.find(nsp("CountryCode", wqx_ns)))
        self.state = testXMLValue(geo.find(nsp("StateCode", wqx_ns)))
        self.county = testXMLValue(geo.find(nsp("CountyCode", wqx_ns)))
Exemple #51
0
 def _parseinsertresult(self):
     self.results['insertresults'] = []
     for i in self._exml.findall('.//'+util.nspath_eval('csw:InsertResult', namespaces)):
         for j in i.findall(util.nspath_eval('csw:BriefRecord/dc:identifier', namespaces)):
             self.results['insertresults'].append(util.testXMLValue(j))
Exemple #52
0
    def __init__(self, infoset, namespace=DEFAULT_OWS_NAMESPACE):
        self._root = infoset
        val = self._root.find(util.nspath('ProviderName', namespace))
        self.name = util.testXMLValue(val)

        self.organization = util.testXMLValue(
            self._root.find(
                util.nspath('ContactPersonPrimary/ContactOrganization',
                            namespace)))

        val = self._root.find(util.nspath('ProviderSite', namespace))
        if val is not None:
            self.site = util.testXMLValue(
                val.attrib.get(util.nspath('href', XLINK_NAMESPACE)), True)
        else:
            self.site = None

        val = self._root.find(util.nspath('ServiceContact/Role', namespace))
        self.role = util.testXMLValue(val)

        val = self._root.find(
            util.nspath('ServiceContact/IndividualName', namespace))
        self.name = util.testXMLValue(val)

        val = self._root.find(
            util.nspath('ServiceContact/PositionName', namespace))
        self.position = util.testXMLValue(val)

        val = self._root.find(
            util.nspath('ServiceContact/ContactInfo/Phone/Voice', namespace))
        self.phone = util.testXMLValue(val)

        val = self._root.find(
            util.nspath('ServiceContact/ContactInfo/Phone/Facsimile',
                        namespace))
        self.fax = util.testXMLValue(val)

        val = self._root.find(
            util.nspath('ServiceContact/ContactInfo/Address/DeliveryPoint',
                        namespace))
        self.address = util.testXMLValue(val)

        val = self._root.find(
            util.nspath('ServiceContact/ContactInfo/Address/City', namespace))
        self.city = util.testXMLValue(val)

        val = self._root.find(
            util.nspath(
                'ServiceContact/ContactInfo/Address/AdministrativeArea',
                namespace))
        self.region = util.testXMLValue(val)

        val = self._root.find(
            util.nspath('ServiceContact/ContactInfo/Address/PostalCode',
                        namespace))
        self.postcode = util.testXMLValue(val)

        val = self._root.find(
            util.nspath('ServiceContact/ContactInfo/Address/Country',
                        namespace))
        self.country = util.testXMLValue(val)

        val = self._root.find(
            util.nspath(
                'ServiceContact/ContactInfo/Address/ElectronicMailAddress',
                namespace))
        self.email = util.testXMLValue(val)

        val = self._root.find(
            util.nspath('ServiceContact/ContactInfo/OnlineResource',
                        namespace))
        if val is not None:
            self.url = util.testXMLValue(
                val.attrib.get(util.nspath('href', XLINK_NAMESPACE)), True)
        else:
            self.url = None

        val = self._root.find(
            util.nspath('ServiceContact/ContactInfo/HoursOfService',
                        namespace))
        self.hours = util.testXMLValue(val)

        val = self._root.find(
            util.nspath('ServiceContact/ContactInfo/ContactInstructions',
                        namespace))
        self.instructions = util.testXMLValue(val)
Exemple #53
0
    def __init__(self, elem, parent, parse_remote_metadata=False, timeout=30):
        """."""
        self.id = elem.find(nspath('Name',ns=WFS_NAMESPACE)).text
        self.title = elem.find(nspath('Title',ns=WFS_NAMESPACE)).text
        abstract = elem.find(nspath('Abstract',ns=WFS_NAMESPACE))
        if abstract is not None:
            self.abstract = abstract.text
        else:
            self.abstract = None
        self.keywords = [f.text for f in elem.findall(nspath('Keywords',ns=WFS_NAMESPACE))]

        # bboxes
        self.boundingBoxWGS84 = None
        b = elem.find(nspath('WGS84BoundingBox',ns=OWS_NAMESPACE))
        if b is not None:
            lc = b.find(nspath("LowerCorner",ns=OWS_NAMESPACE))
            uc = b.find(nspath("UpperCorner",ns=OWS_NAMESPACE))
            ll = [float(s) for s in lc.text.split()]
            ur = [float(s) for s in uc.text.split()]
            self.boundingBoxWGS84 = (ll[0],ll[1],ur[0],ur[1])

        # there is no such think as bounding box
        # make copy of the WGS84BoundingBox
        self.boundingBox = (self.boundingBoxWGS84[0],
                            self.boundingBoxWGS84[1],
                            self.boundingBoxWGS84[2],
                            self.boundingBoxWGS84[3],
                            Crs("epsg:4326"))
        # crs options
        self.crsOptions = [Crs(srs.text) for srs in elem.findall(nspath('OtherCRS',ns=WFS_NAMESPACE))]
        defaultCrs =  elem.findall(nspath('DefaultCRS',ns=WFS_NAMESPACE))
        if len(defaultCrs) > 0:
            self.crsOptions.insert(0,Crs(defaultCrs[0].text))


        # verbs
        self.verbOptions = [op.tag for op \
            in parent.findall(nspath('Operations/*',ns=WFS_NAMESPACE))]
        self.verbOptions + [op.tag for op \
            in elem.findall(nspath('Operations/*',ns=WFS_NAMESPACE)) \
            if op.tag not in self.verbOptions]
        
        #others not used but needed for iContentMetadata harmonisation
        self.styles=None
        self.timepositions=None
        self.defaulttimeposition=None

        # MetadataURLs
        self.metadataUrls = []
        for m in elem.findall('MetadataURL'):
            metadataUrl = {
                'type': testXMLValue(m.attrib['type'], attrib=True),
                'format': m.find('Format').text.strip(),
                'url': testXMLValue(m.find('OnlineResource').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)
                    try:  # FGDC
                        metadataUrl['metadata'] = Metadata(doc)
                    except:  # ISO
                        metadataUrl['metadata'] = MD_Metadata(doc)
                except Exception:
                    metadataUrl['metadata'] = None

            self.metadataUrls.append(metadataUrl)
Exemple #54
0
 def __init__(self, element):
     super(QuantityRange, self).__init__(element)
     # Elements
     value = testXMLValue(element.find(nspv("swe20:value")))
     self.value = make_pair(value, float) if value is not None else None
Exemple #55
0
 def __init__(self, element):
     self.reason = testXMLAttribute(element, "reason")
     self.value = testXMLValue(element)
Exemple #56
0
    def __init__(self, md=None):

        if md is None:
            self.name = None
            self.organization = None
            self.position = None
            self.phone = None
            self.fax = None
            self.address = None
            self.city = None
            self.region = None
            self.postcode = None
            self.country = None
            self.email = None
            self.onlineresource = None
            self.role = None
        else:
            val = md.find(util.nspath_eval('gmd:individualName/gco:CharacterString', namespaces))
            self.name = util.testXMLValue(val)

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

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

            val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:phone/gmd:CI_Telephone/gmd:voice/gco:CharacterString', namespaces))

            self.phone = util.testXMLValue(val)

            val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:phone/gmd:CI_Telephone/gmd:facsimile/gco:CharacterString', namespaces))
            self.fax = util.testXMLValue(val)

            val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:address/gmd:CI_Address/gmd:deliveryPoint/gco:CharacterString', namespaces))
            self.address = util.testXMLValue(val)

            val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:address/gmd:CI_Address/gmd:city/gco:CharacterString', namespaces))
            self.city = util.testXMLValue(val)

            val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:address/gmd:CI_Address/gmd:administrativeArea/gco:CharacterString', namespaces))
            self.region = util.testXMLValue(val)

            val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:address/gmd:CI_Address/gmd:postalCode/gco:CharacterString', namespaces))
            self.postcode = util.testXMLValue(val)

            val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:address/gmd:CI_Address/gmd:country/gco:CharacterString', namespaces))
            self.country = util.testXMLValue(val)

            val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:address/gmd:CI_Address/gmd:electronicMailAddress/gco:CharacterString', namespaces))
            self.email = util.testXMLValue(val)

            val = md.find(util.nspath_eval('gmd:contactInfo/gmd:CI_Contact/gmd:onlineResource/gmd:CI_OnlineResource', namespaces))
            if val is not None:
              self.onlineresource = CI_OnlineResource(val)
            else:
              self.onlineresource = None
          
            self.role = _testCodeListValue(md.find(util.nspath_eval('gmd:role/gmd:CI_RoleCode', namespaces)))
Exemple #57
0
    def __init__(self, md):
        val = md.find(util.nspath_eval('dif:Type', namespaces))
        self.type = util.testXMLValue(val)

        val = md.find(util.nspath_eval('dif:SubType', namespaces))
        self.subtype = util.testXMLValue(val)
Exemple #58
0
 def __init__(self, element):
     super(CategoryRange, self).__init__(element)
     # Elements
     value = testXMLValue(element.find(nspv("swe20:value")))
     self.values = make_pair(value) if value is not None else None
Exemple #59
0
    def __init__(self, elem, parse_remote_metadata=False, timeout=30):
        """."""
        self.id = testXMLValue(elem.find(nspath_eval('wfs:Name', namespaces)))
        self.title = testXMLValue(
            elem.find(nspath_eval('wfs:Title', namespaces)))
        self.abstract = testXMLValue(
            elem.find(nspath_eval('wfs:Abstract', namespaces)))
        self.keywords = [
            f.text for f in elem.findall(
                nspath_eval('ows:Keywords/ows:Keyword', namespaces))
        ]

        # bbox
        self.boundingBoxWGS84 = None
        b = BoundingBox(
            elem.find(nspath_eval('ows:WGS84BoundingBox', namespaces)),
            namespaces['ows'])
        if b is not None:
            self.boundingBoxWGS84 = (
                float(b.minx),
                float(b.miny),
                float(b.maxx),
                float(b.maxy),
            )
        # crs options
        self.crsOptions = [
            Crs(srs.text)
            for srs in elem.findall(nspath_eval('wfs:OtherSRS', namespaces))
        ]
        dsrs = testXMLValue(
            elem.find(nspath_eval('wfs:DefaultSRS', namespaces)))
        if dsrs is not None:  # first element is default srs
            self.crsOptions.insert(0, Crs(dsrs))

        # verbs
        self.verbOptions = [
            op.text for op in elem.findall(
                nspath_eval('wfs:Operations/wfs:Operation', namespaces))
        ]

        # output formats
        self.outputFormats = [
            op.text for op in elem.findall(
                nspath_eval('wfs:OutputFormats/wfs:Format', namespaces))
        ]

        # MetadataURLs
        self.metadataUrls = []
        for m in elem.findall(nspath_eval('wfs:MetadataURL', namespaces)):
            metadataUrl = {
                'type': testXMLValue(m.attrib['type'], attrib=True),
                'format': testXMLValue(m.find('Format')),
                'url': testXMLValue(m)
            }

            if metadataUrl[
                    'url'] is not None and parse_remote_metadata:  # download URL
                try:
                    content = urlopen(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'] in ['TC211', '19115', '19139']:
                            metadataUrl['metadata'] = MD_Metadata(doc)
                except Exception, err:
                    metadataUrl['metadata'] = None

            self.metadataUrls.append(metadataUrl)
Exemple #60
0
    def __init__(self,
                 elem,
                 parent,
                 parse_remote_metadata=False,
                 timeout=30,
                 headers=None,
                 auth=None):
        """."""
        super(ContentMetadata, self).__init__(headers=headers, auth=auth)
        self.id = elem.find(nspath("Name", ns=WFS_NAMESPACE)).text
        self.title = elem.find(nspath("Title", ns=WFS_NAMESPACE)).text
        abstract = elem.find(nspath("Abstract", ns=WFS_NAMESPACE))
        if abstract is not None:
            self.abstract = abstract.text
        else:
            self.abstract = None
        self.keywords = [
            f.text for f in elem.findall(nspath("Keywords", ns=WFS_NAMESPACE))
        ]

        # bboxes
        self.boundingBoxWGS84 = None
        b = elem.find(nspath("WGS84BoundingBox", ns=OWS_NAMESPACE))
        if b is not None:
            try:
                lc = b.find(nspath("LowerCorner", ns=OWS_NAMESPACE))
                uc = b.find(nspath("UpperCorner", ns=OWS_NAMESPACE))
                ll = [float(s) for s in lc.text.split()]
                ur = [float(s) for s in uc.text.split()]
                self.boundingBoxWGS84 = (ll[0], ll[1], ur[0], ur[1])

                # there is no such think as bounding box
                # make copy of the WGS84BoundingBox
                self.boundingBox = (
                    self.boundingBoxWGS84[0],
                    self.boundingBoxWGS84[1],
                    self.boundingBoxWGS84[2],
                    self.boundingBoxWGS84[3],
                    Crs("epsg:4326"),
                )
            except AttributeError:
                self.boundingBoxWGS84 = None
        # crs options
        self.crsOptions = [
            Crs(srs.text)
            for srs in elem.findall(nspath("OtherCRS", ns=WFS_NAMESPACE))
        ]
        defaultCrs = elem.findall(nspath("DefaultCRS", ns=WFS_NAMESPACE))
        if len(defaultCrs) > 0:
            self.crsOptions.insert(0, Crs(defaultCrs[0].text))

        # verbs
        self.verbOptions = [
            op.tag
            for op in parent.findall(nspath("Operations/*", ns=WFS_NAMESPACE))
        ]
        self.verbOptions + [
            op.tag
            for op in elem.findall(nspath("Operations/*", ns=WFS_NAMESPACE))
            if op.tag not in self.verbOptions
        ]

        # others not used but needed for iContentMetadata harmonisation
        self.styles = None
        self.timepositions = None
        self.defaulttimeposition = None

        # MetadataURLs
        self.metadataUrls = []
        for m in elem.findall(nspath("MetadataURL", ns=WFS_NAMESPACE)):
            metadataUrl = {
                "url":
                testXMLValue(m.attrib["{http://www.w3.org/1999/xlink}href"],
                             attrib=True)
            }
            self.metadataUrls.append(metadataUrl)

        if parse_remote_metadata:
            self.parse_remote_metadata(timeout)