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

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

Create new model, Deployment, to hold deployments info - for easy use
with templates. Delete the moles deployments code and implement code
with the new model + add containers in Atom - to allow deployments data
specified in links to be looked up.

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