source: exist/trunk/python/ndgUtils/models/MolesEntity.py @ 4490

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/exist/trunk/python/ndgUtils/models/MolesEntity.py@4490
Revision 4490, 6.7 KB checked in by cbyrom, 11 years ago (diff)

Add methods to the eXist DB client to ingest the required atom xsd docs + to allow validation of atoms against these schemae. Add ability to validate docs already in eXist and also to temporarily ingest them to allow validation.

Line 
1'''
2 Class representing moles data that is too structured to be included in the basic Atom elements
3 
4 @author: C Byrom, Tessella Jun 2008
5'''
6try: #python 2.5
7    from xml.etree import cElementTree as ET
8except ImportError:
9    try:
10        # if you've installed it yourself it comes this way
11        import cElementTree as ET
12    except ImportError:
13        # if you've egged it this is the way it comes
14        from ndgUtils.elementtree import cElementTree as ET
15import logging, datetime
16from ndgUtils.lib.utilities import escapeSpecialCharacters
17       
18
19class MolesEntity(object):
20   
21    # URL which points to the browse service - NB ensure this is properly defined
22    BROWSE_URL = "http://ndg.badc.rl.ac.uk:8080/view"
23   
24    def __init__(self):
25        '''
26        Constructor - initialise the atom variables
27        '''
28        logging.info("Initialising MolesEntity")
29
30        # an array of Atom.Person objects
31        self.responsibleParties = []
32        self.deployments = {}
33        self.abbreviation = None
34        self.providerID = None
35        self.createdDate = None
36               
37        self.datasetLanguage = 'English'
38        self.metadataLanguage = 'English'
39       
40        # helper arrays to produce summary info for atom in templates
41        self.activities = []
42        self.obs = []
43        self.dpts = []
44        logging.info("MolesEntity initialised")     
45
46
47    def addResponsibleParty(self, partyVals):
48        '''
49        Add a responsible party - using the input string format,
50        ' name | uri | role '
51        '''
52        logging.debug("Adding responsible party data")
53        from ndgUtils.models.Atom import Person
54        if type(partyVals) is not list:
55            partyVals = [partyVals]
56       
57        for vals in partyVals:
58            rp = Person(personType = Person.RESPONSIBLE_PARTY_TYPE)
59            rp.fromString(vals)
60            self.responsibleParties.append(rp)
61        logging.debug("Finished adding responsible party data")
62
63       
64    def toXML(self):
65        '''
66        Convert the atom into XML representation and return this
67        @return: xml version of atom
68        '''
69        logging.info("Creating formatted XML version of MolesEntity")
70        molesEntity = ET.Element("moles:entity")
71        molesEntity.attrib["xmlns:moles"] = "http://ndg.nerc.ac.uk/schema/moles2beta"
72       
73        molesISO = ET.SubElement(molesEntity, "moles:molesISO")
74        datasetLanguage = ET.SubElement(molesISO, "moles:datasetLanguage")
75        datasetLanguage.text = self.datasetLanguage
76        metadataLanguage = ET.SubElement(molesISO, "moles:metadataLanguage")
77        metadataLanguage.text = self.metadataLanguage
78
79        if self.responsibleParties:
80            rpElement = ET.SubElement(molesISO, "moles:responsibleParties")
81            logging.info("Adding responsible parties info")
82            for party in self.responsibleParties:
83                rpElement.append(party.toXML())
84
85        if self.abbreviation:
86            logging.info("Adding abbreviation element")
87            abbreviationElement = ET.SubElement(molesISO, "moles:abbreviation")
88            abbreviationElement.text = self.abbreviation
89
90        if self.providerID:
91            logging.info("Adding providerID element")
92            subElement = ET.SubElement(molesISO, "moles:providerID")
93            subElement.text = self.providerID
94           
95        # if there's a created date already defined, use this, otherwise assume this is the creation point
96        # so use current time
97        if not self.createdDate:
98            self.createdDate = datetime.datetime.today().strftime("%Y-%m-%dT%H:%M:%SZ")
99
100        createdElement = ET.SubElement(molesISO, "moles:created")
101        createdElement.text = self.createdDate
102
103        logging.info("XML version of MolesEntity created")
104        return molesEntity
105
106
107    def fromET(self, tree):
108        '''
109        Initialise MolesEntity object using an elementtree
110        @param tree: ElementTree with moles entity data
111        '''
112        logging.info("Ingesting data from ElementTree object")
113       
114        authorElements = tree.findall('molesISO/responsibleParties/responsibleParty')
115        from ndgUtils.models.Atom import Person
116        for authorElement in authorElements:
117            logging.debug("Adding atom author data")
118            author = Person(personType = Person.RESPONSIBLE_PARTY_TYPE)
119            author.fromETElement(authorElement)
120            self.responsibleParties.append(author)
121               
122        self.abbreviation = tree.findtext('molesISO/abbreviation')
123
124        self.providerID = tree.findtext('molesISO/providerID')
125
126        self.datasetLanguage = tree.findtext('molesISO/datasetLanguage')
127        self.metadataLanguage = tree.findtext('molesISO/metadataLanguage')
128
129        createdDate = tree.findtext('molesISO/created')
130        if createdDate:
131            logging.debug("Adding created date")
132            self.createdDate = createdDate
133           
134        logging.info("Data ingested from tree")
135           
136           
137    def fromString(self, xmlString):
138        '''
139        Initialise MolesEntity object using an xmlString
140        @param xmlString: representation of atom as an XML string
141        '''
142        logging.info("Ingesting data from XML string")
143       
144        # firstly, remove any namespaces used - to avoid problems with elementtree
145        logging.debug("Stripping moles namespace from string to allow easy handling with elementtree")
146        xmlString = xmlString.replace('moles:', '')
147
148        # now create elementtree with the XML string
149        logging.debug("Create elementtree instance with XML string")
150        tree = ET.fromstring(xmlString)
151        self.fromET(tree)
152        logging.info("Completed data ingest from XML string")
153
154       
155    def setAttribute(self, attributeName, attributeValue):
156        '''
157        Set the value of an atom attribute - and do some basic tidying up of the string content
158        - to escape any XML unfriendly characters
159        @param attributeName: name of the attribute whose value to set
160        @param attributeValue: value to set the attribute to 
161        '''
162        logging.debug("Setting attribute, %s, to %s" %(attributeName, attributeValue))
163        origValue = attributeValue
164       
165        # escape any special characters if a value has been specified
166        # NB, need to cope with both single values and arrays
167        if attributeValue:
168            if type(attributeValue) is list:
169                newVals = []
170                for val in attributeValue:
171                    newVals.append(escapeSpecialCharacters(val))
172                attributeValue = newVals
173            else:
174                attributeValue = escapeSpecialCharacters(attributeValue) 
175        setattr(self, attributeName, attributeValue)
Note: See TracBrowser for help on using the repository browser.