source: mauRepo/MolesManager/trunk/src/libs/migration/processor/commons.py @ 8265

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/mauRepo/MolesManager/trunk/src/libs/migration/processor/commons.py@8265
Revision 8265, 33.9 KB checked in by mnagni, 9 years ago (diff)

Complete - # 22409: CEDA Observation - resultTime
 http://team.ceda.ac.uk/trac/ceda/ticket/22409

Line 
1'''
2Created on 15 Nov 2011
3
4@author: mnagni
5'''
6from ea_model.moles3_4.utilities.mo_responsiblepartyinfo import MO_ResponsiblePartyInfo
7from ea_model.iso_19115_2006_metadata_corrigendum.reference_system_information.md_identifier import MD_Identifier
8from httplib import HTTPConnection
9from xml.etree.ElementTree import XML, tostring
10import time, datetime
11from ea_model.upcomingiso.ci_organisation import CI_Organisation
12from ea_model.upcomingiso.ci_party import CI_Party
13from ea_model.upcomingiso.ci_individual import CI_Individual
14from libs.migration.exception.exceptions import NoDataLineage
15from ea_model.iso_19115_2006_metadata_corrigendum.citation_and_responsible_party_information.ci_citation import CI_Citation
16from ea_model.iso_19115_2006_metadata_corrigendum.data_quality_information.dq_element import DQ_Element
17from ea_model.iso_19115_2006_metadata_corrigendum.data_quality_information.dq_conformanceresult import DQ_ConformanceResult
18from hashlib import md5
19from xml.sax.saxutils import unescape, escape
20import html5lib
21from html5lib import treebuilders
22from ea_model.ceda_metadatamodel.ceda_result.ceda_result import CEDA_Result
23from ea_model.moles3_4.result.mo_onlineresource import MO_OnlineResource
24from ea_model.iso_19115_2006_metadata_corrigendum.citation_and_responsible_party_information.url import URL
25from ea_model.iso_19115_2006_metadata_corrigendum.extent_information.ex_geographicboundingbox import EX_GeographicBoundingBox
26from ea_model.ceda_metadatamodel.ceda_computation.ceda_processing import CEDA_Processing
27from ea_model.ceda_metadatamodel.ceda_acquisition.ceda_instrument import CEDA_Instrument
28from ea_model.ceda_metadatamodel.ceda_observationprocess.ceda_compositeprocess import CEDA_CompositeProcess
29from ea_model.ceda_metadatamodel.ceda_acquisition.ceda_acquisition import CEDA_Acquisition
30from ea_model.iso_19115_2006_metadata_corrigendum.citation_and_responsible_party_information.ci_date import CI_Date
31from ea_model.iso_19103_2005_schema_language.basic_types.primitive.date_and_time.datetime import DateTime
32from ea_model.iso_19103_2005_schema_language.basic_types.primitive.date_and_time.date import Date
33from ea_model.iso_19108_2006_temporal_schema.temporal_reference_system.tm_position import TM_Position
34from ea_model.iso_19108_2006_temporal_schema.temporal_objects.tm_instant import TM_Instant
35from ea_model.iso_19115_2006_metadata_corrigendum.citation_and_responsible_party_information.ci_contact import CI_Contact
36from ea_model.iso_19115_2006_metadata_corrigendum.citation_and_responsible_party_information.ci_address import CI_Address
37from ea_model.iso_19115_2006_metadata_corrigendum.citation_and_responsible_party_information.ci_onlineresource import CI_OnlineResource
38from ea_model.iso_19115_2006_metadata_corrigendum.citation_and_responsible_party_information.ci_telephone import CI_Telephone
39from ea_model.iso_19108_2006_temporal_schema.temporal_objects.tm_period import TM_Period
40from ea_model.iso_19115_2006_metadata_corrigendum.constraint_information.md_constraints import MD_Constraints
41from ea_model.iso_19115_2006_metadata_corrigendum.constraint_information.md_legalconstraints import MD_LegalConstraints
42from ea_model.ceda_metadatamodel.ceda_project.ceda_project import CEDA_Project
43from ea_model.iso_19115_2006_metadata_corrigendum.metadata_entity_set_information.md_metadata import MD_Metadata
44from ea_model.ceda_metadatamodel.ceda_utilities.ceda_review import CEDA_Review
45from ea_model.iso_19115_2006_metadata_corrigendum.citation_and_responsible_party_information.ci_responsibleparty import CI_ResponsibleParty
46from ea_model.iso_19115_2006_metadata_corrigendum.maintenance_information.md_maintenancefrequencycode import MD_MaintenanceFrequencyCode
47
48base = '/exist/rest/atoms'
49
50DS_pUBLISHED = 'published'
51DS_WORKING = 'working'
52DS_PUBLISHED = 'Published'
53docStatus = (DS_pUBLISHED, DS_WORKING, DS_PUBLISHED)
54
55DT_DEPLOYMENTS = 'deployments'
56DT_DATA_ENTITIES = 'data_entities'
57DT_DEPLOYMENT_DATA = 'deployment_data'
58DT_DATA_GRANULES = 'data_granules'
59docTypes = (DT_DEPLOYMENTS, DT_DATA_ENTITIES, DT_DEPLOYMENT_DATA, DT_DATA_GRANULES)
60
61DO_BADC = 'badc.nerc.ac.uk'
62DO_NEODC = 'neodc.nerc.ac.uk'
63DO_UKSSDC = 'ukssdc.ac.uk'
64
65CEDA = 'Centre for Environmental Data Archive'
66docOwners = (DO_BADC, DO_NEODC, DO_UKSSDC)
67
68atomNS = "{http://www.w3.org/2005/Atom}"
69existNS = "{http://exist.sourceforge.net/NS/exist}"
70molesNS = "{http://ndg.nerc.ac.uk/schema/moles2beta}"
71htmlNS = "{http://www.w3.org/1999/xhtml}"
72georssNS="{http://www.georss.org/georss/10}"
73gmlNS="{http://www.opengis.net/gml}"
74date_format = '%Y-%m-%d'
75datetime_format = date_format + 'T%H:%M:%SZ'
76ihost = 'bora.badc.rl.ac.uk'
77iport = '8080'
78
79linkMarkers = ['Deployment', 'DOWNLOAD', 'DOCUMENTATION', 'ACCESS', 'LOGO', 'ACTIVITY', 'DPT', 'OBS']
80
81#MD_Identifier codes
82MD_CODE_MOLES2_CITATION = 'ceda_moles2_citation'
83
84htmlParser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("etree"), namespaceHTMLElements=False)
85
86def calculateHash(text):
87    """
88        Returns an md5 hexadecimal representation of the given text
89        @param text: the string to encode
90        @return: the hexadecimal md5 value of the given text
91    """
92    encoder = md5()
93    encoder.update(text)
94    return encoder.hexdigest()
95
96def buildExistDocPath(docStatus, docType, docOwner, docName):
97    '''
98        @param docStatus: one value from commons.docStatus
99        @param docType: one value from commons.docTypes
100        @param docOwner: one value from commons.docOwners
101        @param docName: one value from commons.docOwners       
102    '''       
103    return '%s/%s' % (buildExistOwnerPath(docStatus, docType, docOwner), docName)
104
105def buildExistOwnerPath(docStatus, docType, docOwner):
106    '''
107        @param docStatus: one value from commons.docStatus
108        @param docType: one value from commons.docCollections
109        @param docOwner: one value from commons.docOwners
110    '''       
111    return '%s/%s' % (buildExistTypePath(docStatus, docType), docOwner)
112
113def buildExistTypePath(docStatus, docType):
114    '''
115        @param docStatus: one value from commons.docStatus
116        @param docType: one value from commons.docCollections
117    '''       
118    return '%s/%s' % (buildExistStatusPath(docStatus), docType)
119
120def buildExistStatusPath(docStatus):
121    '''
122        @param docStatus: one value from commons.docStatus
123    '''       
124    return '/exist/rest/atoms/%s' % (docStatus)
125
126def getAtomDocumentByMO(migrationObject):
127    if migrationObject is None:
128        raise Exception("migrationObject is None")
129    mo_typeDict = {'DeploymentsMigration': DT_DEPLOYMENTS, 'DataEntityMigration': DT_DATA_ENTITIES, 'DeploymentDataMigration': DT_DEPLOYMENT_DATA}     
130    return getAtomDocumentAsElementtree(migrationObject.doc_status, mo_typeDict[type(migrationObject).__name__], migrationObject.doc_owner, migrationObject.doc_name)
131
132def getAtomDocumentHashByMO(migrationObject):
133    if migrationObject is None:
134        raise Exception("migrationObject is None")   
135    mo_typeDict = {'DeploymentsMigration': DT_DEPLOYMENTS, 'DataEntityMigration': DT_DATA_ENTITIES, 'DeploymentDataMigration': DT_DEPLOYMENT_DATA}     
136    text = _getAtomDocumentAsText(migrationObject.doc_status, mo_typeDict[type(migrationObject).__name__], migrationObject.doc_owner, migrationObject.doc_name)
137    return calculateHash(text)
138
139def getAtomDocumentHash(docStatus, docType, docOwner, docName):
140    source = buildExistDocPath(docStatus, docType, docOwner, docName)
141    text = _getDocument(source)
142    return calculateHash(text)
143
144def hasAtomDocumentSameHash(migrationObject):
145    return getAtomDocumentHashByMO(migrationObject) == migrationObject.doc_hash
146
147def getAtomDocumentByType(migrationObject, docType):
148    if migrationObject is None:
149        raise Exception("migrationObject is None")   
150    return getAtomDocumentAsElementtree(migrationObject.doc_status, docType, migrationObject.doc_owner, migrationObject.doc_name)
151
152def _getAtomDocumentAsText(docStatus, docType, docOwner, docName):
153    source = buildExistDocPath(docStatus, docType, docOwner, docName)
154    return _getDocument(source)
155
156def getAtomDocumentAsElementtree(docStatus, docType, docOwner, docName):
157    source = buildExistDocPath(docStatus, docType, docOwner, docName)
158    return _getXMLDocument(source)
159
160def _getXMLDocument(source):
161    return XML(_getDocument(source))
162
163def stringToTimestamp(timestring):
164    '''
165        Return a timestamp such as is returned by time.time().
166        @param timestring: a time string formatted as '%Y-%m-%dT%H:%M:%SZ'
167    '''   
168    return datetime.datetime.fromtimestamp(time.mktime(time.strptime(timestring, datetime_format)))
169
170def isoDateStringToTimeDate(datestring):
171    '''
172        Return a datatime.datatime instance.
173        @param datestring: a date string formatted as '%Y-%m-%d'
174    '''
175    return datetime.datetime.strptime(datestring, date_format)
176
177def isoDateTimeStringToTimeDate(timestring):
178    '''
179        Return a datatime.datatime instance.
180        @param timestring: a time string formatted as '%Y-%m-%dT%H:%M:%SZ'
181    '''
182    return datetime.datetime.strptime(timestring, datetime_format)
183
184def _getDocument(source):
185    conn = HTTPConnection(host = ihost, port = iport)
186    conn.connect()
187    req = conn.request('GET', source)
188    res = conn.getresponse()
189    xmlDoc = res.read()
190    '''
191    print (xmlDoc)
192    '''
193    conn.close()
194    return xmlDoc
195
196def _returnNotNoneText(element):
197    if element is None:
198        return None
199    return element.text
200
201def findMolesCreationDate(resourceXML):
202    creationDate = resourceXML.find('%sentity/%smolesISO/%screated' % (molesNS, molesNS, molesNS))
203    return _returnNotNoneText(creationDate)
204
205def findMolesPublishedDate(resourceXML):
206    creationDate = resourceXML.find('%sentity/%smolesISO/%spublished' % (molesNS, molesNS, molesNS))
207    return _returnNotNoneText(creationDate)
208
209def findMolesLineage(dataEntityMigration):
210    resourceXML = getAtomDocumentByMO(dataEntityMigration)
211    lineage = resourceXML.find('%sentity/%smolesISO/%slineage' % (molesNS, molesNS, molesNS))
212    if lineage is None:
213        raise NoDataLineage(dataEntityMigration)
214    return lineage.text
215
216def extractMolesProviderID(migrationObject):
217    resourceXML = getAtomDocumentByMO(migrationObject)
218    provider_id = resourceXML.find('%sentity/%smolesISO/%sproviderID' % (molesNS, molesNS, molesNS))
219    return _returnNotNoneText(provider_id)
220
221def extractMolesQuality(migrationObject):
222    resourceXML = getAtomDocumentByMO(migrationObject)
223    quality = resourceXML.find('%sentity/%smolesISO/%squality' % (molesNS, molesNS, molesNS))
224    return _returnNotNoneText(quality)
225
226def extractMolesTemporalRange(migrationObject):
227    resourceXML = getAtomDocumentByMO(migrationObject)
228    temporal_range = resourceXML.find('%stemporalRange' % (molesNS))
229    return _returnNotNoneText(temporal_range)
230
231def extractMolesCreationDate(migrationObject):
232    resourceXML = getAtomDocumentByMO(migrationObject)
233    return findMolesCreationDate(resourceXML)
234
235def extractMolesPublishedDate(migrationObject):
236    resourceXML = getAtomDocumentByMO(migrationObject)
237    return findMolesPublishedDate(resourceXML)
238
239def extractQuality(dataEntityMigration):
240    resourceXML = getAtomDocumentByMO(dataEntityMigration)
241    quality = resourceXML.find('%sentity/%smolesISO/%squality' % (molesNS, molesNS, molesNS))
242    return _returnNotNoneText(quality)
243
244def extractUpdateFrequency(dataEntityMigration):
245    resourceXML = getAtomDocumentByMO(dataEntityMigration)
246    update_frequency = resourceXML.find('%sentity/%smolesISO/%supdateFrequency' % (molesNS, molesNS, molesNS))
247    return _returnNotNoneText(update_frequency)
248
249def extractContent(dataEntityMigration):
250    """
251        Returns a dictionary containing the div composing the
252        <content> element in a dataentity document.
253    """
254    resourceXML = getAtomDocumentByMO(dataEntityMigration)
255    content = resourceXML.find('%scontent' % (atomNS))
256    text = _returnNotNoneText(content)
257    contentDict = {}
258    if text:
259        doc = htmlParser.parse(unescape(text))
260        for el in doc.findall('body//div'):   
261            prop = el.get('property')
262            if prop:
263                if prop.startswith('cedacat'):
264                    contentDict[prop.split(':')[1]] = escape(tostring(el))
265    return contentDict
266
267def _extractAuthors(authorsCSV):
268    if authorsCSV is None:
269        return []
270    authors = authorsCSV.split(',')
271    for index in range(len(authors)):
272        authors[index] = authors[index].strip()
273        if len(authors[index]) == 0:
274            authors.remove(authors[index])
275    return authors
276
277def findAuthorsInResource(resourceMigration):
278    '''
279        Returns a dictionary with the following keys:
280        'authors': a list of string representing the authors
281        'contributors': a list of string representing the contributors
282    '''
283    ret = {}   
284    resourceXML = getAtomDocumentByMO(resourceMigration)
285    ret['authors'] = findAuthorInResource(resourceXML)
286    ret['contributors'] = findContributorInResource(resourceXML)
287    return ret
288
289def findAuthorInResource(resourceXML): 
290    author = resourceXML.find('%sauthor/%sname' % (atomNS, atomNS))
291    return _returnNotNoneText(author)
292
293def findContributorInResource(resourceXML): 
294    contributors = resourceXML.find('%scontributor/%sname' % (atomNS, atomNS))
295    return _returnNotNoneText(contributors)
296
297def findPublishedDate(resourceMigration):
298    resourceXML = getAtomDocumentByMO(resourceMigration)
299    publishedDate = resourceXML.find('%spublished' % (atomNS))
300    return _returnNotNoneText(publishedDate)
301
302def findUpdatedDate(resourceMigration):
303    resourceXML = getAtomDocumentByMO(resourceMigration)
304    publishedDate = resourceXML.find('%supdated' % (atomNS))
305    return _returnNotNoneText(publishedDate)
306
307def findSummary(resourceMigration):
308    """
309        Returns the <entry><summary> tag of an atom document
310        @param resourceMigration: a MigrationObject instance
311        @return: the <summary> value or None if empty
312    """
313    resourceXML = getAtomDocumentByMO(resourceMigration)
314    summary = resourceXML.find('%ssummary' % (atomNS))
315    return _returnNotNoneText(summary)
316
317def findID(dataEntXML):
318    ent_id = dataEntXML.find('%sid' % (atomNS))
319    return _returnNotNoneText(ent_id)
320
321def _updateLinksDict(linksDict, link, linkMarker):
322    if not linksDict.has_key(linkMarker):
323        linksDict[linkMarker] = []
324    rel = link.get('rel')
325    if rel and rel.endswith('/' + linkMarker):
326        linksDict[linkMarker].append({'href': link.get('href'), 'title': link.get('title')}) 
327
328def _extractLinks(dataEntXML, markers):
329    linksDict = {}
330    links = dataEntXML.findall('%slink' % (atomNS))
331    for link in links:
332        for marker in markers:
333            _updateLinksDict(linksDict, link, marker)       
334    return linksDict
335
336def findLinksInMigrationDocument(dataEntityMigration):
337    dataEntXML = getAtomDocumentByMO(dataEntityMigration)
338    linksDict = _extractLinks(dataEntXML, linkMarkers)
339    return linksDict
340
341
342
343def findDownloadLinksInMigrationDocument(migrationObject):
344    """
345        Return a list of dictionaries describing a <link rel="...DOWNLOAD..."> tag type
346        Each dictionary has two keys: 'href' and 'title'
347        @param migrationObject: the migration instance to retrieve and parse
348        @return: a list of dictionaries
349    """
350    linksDict = findLinksInMigrationDocument(migrationObject)
351    if linksDict.has_key('DOWNLOAD'):
352        return linksDict['DOWNLOAD']   
353    return {}       
354
355def findAccessLinksInMigrationDocument(migrationObject):
356    """
357        Return a list of dictionaries describing a <link rel="...ACCESS..."> tag type
358        Each dictionary has two keys: 'href' and 'title'
359        @param migrationObject: the migration instance to retrieve and parse
360        @return: a list of dictionaries
361    """
362    linksDict = findLinksInMigrationDocument(migrationObject)
363    if linksDict.has_key('ACCESS'):
364        return linksDict['ACCESS']     
365    return {}   
366
367def findDocumentationInMigrationDocument(migrationObject):
368    """
369        Return a list of dictionaries describing a <link rel="...DOCUMENTATION..."> tag type
370        Each dictionary has two keys: 'href' and 'title'
371        @param migrationObject: the migration instance to retrieve and parse
372        @return: a list of dictionaries
373    """
374    linksDict = findLinksInMigrationDocument(migrationObject)
375    if linksDict.has_key('DOCUMENTATION'):
376        return linksDict['DOCUMENTATION']     
377    return {}
378
379def findDOIInMigrationDocument(migrationObject):
380    """
381        Return a dictionary describing a <link rel="...DOCUMENTATION..."> tag type
382        The dictionary has two keys: 'href' and 'title'
383        @param migrationObject: the migration instance to retrieve and parse
384        @return: a dictionary relative to the DOI, None otherwise
385    """
386    for link in findDocumentationInMigrationDocument(migrationObject):
387        if link['href'].startswith('doi:'):
388            return link
389    return None
390
391def findDeploymentsInDE(dataEntityMigration):
392    linksDict = findLinksInMigrationDocument(dataEntityMigration)
393    links = _extractLinksByMarker(linksDict, 'Deployment')
394    return [depName + '.atom' for depName in links]
395
396def findSubTypeInDPT(resourceMigration):
397    resourceXML = getAtomDocumentByMO(resourceMigration)
398    categories = resourceXML.findall('%scategory' % (atomNS))
399    for category in categories:
400        if category.get("term") == "ATOM_SUBTYPE":
401            return category.get("label")   
402       
403def extractTitle(deploymentMigration):
404    resourceXML = getAtomDocumentByMO(deploymentMigration)
405    title = resourceXML.find('%stitle' % (atomNS))
406    return _returnNotNoneText(title)
407
408def extractSummary(deploymentMigration, dataEntityMigration):
409    resourceXML = getAtomDocumentByMO(deploymentMigration)
410    summary = resourceXML.find('%ssummary' % (atomNS))
411    ret = _returnNotNoneText(summary)
412    if ret:
413        return ret
414    resourceXML = getAtomDocumentByMO(dataEntityMigration)
415    summary = resourceXML.find('%ssummary' % (atomNS))
416    return _returnNotNoneText(summary)
417
418def extractGeographicExtentInMigrationDocument(migrationObject):
419    """
420        Extracts if existing the georss:where/gel:Enveloper/upper-lowerCorner elements.
421        @param migrationObject: a migration object to retrieve to parse for data
422        @return: None if no data are found, otherwise a dictionary with keys: 'east', 'north', 'west', 'south' where
423        the values are float
424    """
425    resourceXML = getAtomDocumentByMO(migrationObject)
426    upperCorner = resourceXML.find('%swhere/%sEnvelope/%supperCorner' % (georssNS, gmlNS, gmlNS))
427    lowerCorner = resourceXML.find('%swhere/%sEnvelope/%slowerCorner' % (georssNS, gmlNS, gmlNS))
428    ret = None
429    if upperCorner != None and lowerCorner != None:
430        upperCornerData = upperCorner.text.split()
431        lowerCornerData = lowerCorner.text.split()
432        ret = {'east': float(upperCornerData[0]), 'north': float(upperCornerData[1]), 'west': float(lowerCornerData[0]), 'south': float(lowerCornerData[1])}
433    return ret
434
435def findLinksInDeployment(migrationObject):
436    """
437        Returns a dictionary of links owned by the given dataEntity document
438        @param deploymentMigration: a MigrationObject instance
439        @return: a dictionary of links.
440    """
441    links = {}
442    linksDict = findLinksInMigrationDocument(migrationObject)
443    for marker in linkMarkers:   
444        links[marker] = _extractLinksByMarker(linksDict, marker)
445    return links
446
447def _extractLinksByMarker(linksDict, marker):
448    dpt = []
449    if linksDict.has_key(marker):
450        for link in linksDict[marker]:
451            try:
452                linkLongName = link['href'].split('/')[-1]
453                linkName = linkLongName.rsplit('__ATOM__')[1]
454                dpt.append(linkName)
455            except Exception as ex:
456                print "WARN - Cannot extractLinksByMarker %s" % (link)
457    return dpt
458
459
460def getResourceRefs(deploymentRefs):
461    '''
462        Returns a list of Elements representing the inner resource reference items
463        @param resourceRefs: the name of the eXist collection name below the 'deployments' one
464    ''' 
465    XMLDepl = _getXMLDocument(deploymentRefs)
466    return XMLDepl.findall('%scollection/%sresource' % (existNS, existNS))
467
468def getOwnerRefs(docStatus, docType, docOwner):
469    '''
470        Returns a list of Elements representing the inner resource reference items
471        @param resourceRefs: the name of the eXist collection name below the 'deployments' one
472    '''     
473    XMLDepl = _getXMLDocument(buildExistOwnerPath(docStatus, docType, docOwner))
474    return XMLDepl.findall('%scollection/%sresource' % (existNS, existNS))
475
476def getTypeRefs(docStatus, docType):
477    '''
478        Returns a list of Elements representing the inner resource reference items
479        @param resourceRefs: the name of the eXist collection name below the 'deployments' one
480    '''     
481    XMLDepl = _getXMLDocument(buildExistTypePath(docStatus, docType))
482    return XMLDepl.findall('%scollection/%sresource' % (existNS, existNS))
483
484
485
486def getCollectionRefs(publishedRefs):
487    '''
488        Returns a list of Elements representing the inner deployment reference items
489        @param basePublished: the name of the eXist collection name below the 'published' one
490    ''' 
491    XMLPubl = _getXMLDocument(publishedRefs)
492    return XMLPubl.findall('%scollection/%scollection' % (existNS, existNS))
493
494def getResource(source, resourceName):
495    resourceSource = '%s/%s' % (source, resourceName)
496    resourceDoc = _getDocument(resourceSource)
497    return XML(resourceDoc)
498
499def createDateTime(datetime):
500    '''
501        Creates a new DateTime instance.
502        @param datetime: a datetime.datetime instance       
503    '''
504    dateTime = DateTime()
505    dateTime.century = (datetime.year / 100) + 1
506    dateTime.year = datetime.year
507    dateTime.month = datetime.month       
508    dateTime.day = datetime.day
509    dateTime.hour = datetime.hour
510    dateTime.minute = datetime.minute
511    dateTime.second = datetime.second
512    dateTime.timeZone = datetime.tzinfo       
513    return dateTime       
514       
515def createDate(date):
516    '''
517        Creates a new Date instance.
518        @param date: a datetime.datetime instance
519    '''
520    idate = Date()
521    idate.century = (date.year / 100) + 1
522    idate.year = date.year
523    idate.month = date.month       
524    idate.day = date.day       
525    return idate       
526       
527def createTM_Position(anyOther = None, date8601 = None, dateTime8601 = None, time8601 = None):
528    '''
529        Creates a new TM_Position instance
530        @param anyOther: a TM_TemporalPosition instance
531        @param date8601: a Date instance
532        @param dateTime8601:a DateTime instance
533        @param time8601: a Time instance   
534    '''
535    tm_position = TM_Position()
536    if anyOther:
537        tm_position.anyOther = anyOther
538    if date8601:
539        tm_position.date8601 = date8601 
540    if dateTime8601:
541        tm_position.dateTime8601 = dateTime8601
542    if time8601:
543        tm_position.time8601 = time8601
544    return tm_position           
545
546def createTM_Instant(position):
547    '''
548        Creates a new TM_Position instance
549        @param position: a TM_Position instance
550    '''
551    tm_instant = TM_Instant()
552    tm_instant.position = position
553    return tm_instant
554
555def createTM_Period(begin, end):
556    '''
557        Creates a new TM_Position instance
558        @param position: a TM_Position instance
559    '''
560    tm_period = TM_Period()
561    tm_period.begin = begin
562    tm_period.end = end   
563    return tm_period
564
565def createCI_Address(deliveryPoint = None, electronicMailAddress = None, city = None, country = None, postalCode = None):
566    '''
567        Creates a new CI_Address instance
568        @param deliveryPoint: an array of Strings
569        @param electronicMailAddress: an array of Strings
570        @param city: a string
571        @param country: a string               
572        @param postalCode: a string       
573    '''
574    ci_address = CI_Address()
575    if deliveryPoint:
576        ci_address.deliveryPoint = deliveryPoint
577    if electronicMailAddress:
578        ci_address.electronicMailAddress = electronicMailAddress       
579    if postalCode:
580        ci_address.postalCode = postalCode       
581    if city:
582        ci_address.city = city       
583    if country:
584        ci_address.country = country       
585    if postalCode:
586        ci_address.postalCode = postalCode       
587    return ci_address
588
589def createCI_OnlineResource(linkage, name=None):
590    '''
591        Creates a new CI_OnlineResource instance
592        @param linkage: a string (the URL class is associated with a String)
593        @param name: a String
594    '''
595    ci_online_resource = CI_OnlineResource()
596    ci_online_resource.linkage = linkage
597    if name:
598        ci_online_resource.name = name
599    return ci_online_resource
600
601def createCI_Telephone(voice=None, facsimile=None):
602    '''
603        Creates a new CI_Telephone instance
604        @param voice: an array of strings       
605        @param facsimile: an array of strings
606    '''
607    ci_telephone = CI_Telephone()
608    if voice:
609        ci_telephone.voice = voice
610    if facsimile:
611        ci_telephone.facsimile = voice       
612    return ci_telephone
613
614def createCI_Contact(phone, address = None, onlineResource = None):
615    '''
616        Creates a new CI_Contact instance
617        @param phone: a CI_Telephone instance       
618        @param address: a CI_Address instance
619        @param onlineResource: a CI_OnlineResource instance
620    '''
621    ci_contact = CI_Contact()
622    ci_contact.phone = phone
623    if address:
624        ci_contact.address = address
625    if onlineResource:
626        ci_contact.onlineResource = onlineResource       
627    return ci_contact
628
629def createCI_Individual(name = None, contactInfo = None):
630    '''
631        Creates a new CI_Individual instance
632        @param name: a String
633        @param contactInfo: an array of CI_Contact       
634    '''   
635    ci_party = CI_Individual()
636    if name:
637        ci_party.name = name
638    if contactInfo:
639        ci_party.contactInfo = contactInfo       
640    return ci_party
641
642def createCI_Organization(name = None, contactInfo = None):
643    '''
644        Creates a new CI_Individual instance
645        @param name: a String
646        @param contactInfo: an array of CI_Contact       
647    '''   
648    ci_party = CI_Organisation()
649    if name:
650        ci_party.name = name
651    if contactInfo:
652        ci_party.contactInfo = contactInfo       
653    return ci_party
654
655def createMO_Organization(name = None, contactInfo = None):
656    '''
657        Creates a new MO_Organization instance.
658        TEMPORARILY RETURNS A CI_ORGANIZATION BECAUSE A DB SCHEMA PROBLEM!!!!
659        @param name: a String
660        @param contactInfo: an array of CI_Contact       
661    '''       
662    ci_party = CI_Organisation()
663    if name:
664        ci_party.name = name
665    if contactInfo:
666        ci_party.contactInfo = contactInfo         
667    return ci_party
668
669def createMO_ResponsiblePartyInfo(role, i_party):
670    """
671        @param role: a CI_RoleCode/MO_RoleValue assigned to this ResponsibleParty
672        @param party: a list of MO_Organization/CI_Individual instances
673    """
674    mo_responsableInfo = MO_ResponsiblePartyInfo()
675    mo_responsableInfo.role = role
676    mo_responsableInfo.party.extend(i_party)
677    return mo_responsableInfo
678
679
680def createCI_Date(dateType, date = None):
681    """
682        Creates a new CI_Date
683        @param dateType: a CI_DateTypeCode value
684        @param date: a DateTime instance
685    """
686    ci_date = CI_Date()
687    ci_date.dateType = dateType
688    if date:
689        ci_date.date = date
690    return ci_date
691
692def createCI_Citation(title, date = None, citedResponsibleParty = None):
693    """
694        Creates a new CI_Citation
695        @param title: the CI_Citation title
696        @param date: an array of CI_Date instances
697        @param citedResponsibleParty: a list of CI_ResponsibleParty instances
698    """   
699    ci_citation = CI_Citation()
700    ci_citation.title = title
701    if date and type(date) == list:
702        ci_citation.date = date
703    if citedResponsibleParty:
704        ci_citation.extend(citedResponsibleParty)
705    return ci_citation
706
707def createMD_Constraints(useLimitation = None):
708    """
709        Creates a new MD_Constrains
710        @param useLimitation: a string array
711    """ 
712    md_constraints = MD_Constraints()
713    if useLimitation and type(useLimitation) == list:
714        md_constraints.useLimitation = useLimitation
715    return md_constraints
716
717def createMD_LegalConstraints(useLimitation = None, accessConstrains = None):
718    """
719        Creates a new MD_LegalConstrains
720        @param useLimitation: a string array
721        @param accessConstrains: an MD_RestrictionCode array
722    """ 
723    md_legalconstraints = MD_LegalConstraints()
724    if useLimitation and type(useLimitation) == list:
725        md_legalconstraints.useLimitation = useLimitation
726    if accessConstrains and type(accessConstrains) == list:
727        md_legalconstraints.accessConstrains = accessConstrains       
728    return md_legalconstraints
729
730def createMD_Identifier(code, authority = None):
731    """
732        Creates a new MD_Identifier
733        @param code: a String
734        @param authority: a CI_Citation instance
735    """
736    md_identifier = MD_Identifier()
737    md_identifier.code = code
738    if authority:
739        md_identifier.authority = authority
740    return md_identifier
741
742def createCI_ResponsibleParty(role, organizationName = None, individualName = None):
743    """
744        Creates a new CI_ResponsibeParty
745        @param role: a CI_RoleCode
746    """
747    ci_responsible_party = CI_ResponsibleParty()
748    ci_responsible_party.role = role
749    if organizationName:
750        ci_responsible_party.organisationName = organizationName
751    if individualName:
752        ci_responsible_party.individualName = individualName   
753    return ci_responsible_party
754
755def createMD_Metadata(date_stamp, contact, language = None):
756    """
757        Creates a new MD_Metadata
758        @param date_stamp: a Date instance
759        @param contacts: a CI_ResponsibleParty array instances
760        @param language: a string
761    """   
762    md_metadata = MD_Metadata()
763    md_metadata.dateStamp = date_stamp
764    for item in contact:
765        md_metadata.contact.append(item)
766    if language:
767        md_metadata.language = language   
768    return md_metadata
769
770def createMO_OnlineResource(linkage, name = None, function = None, description = None, applicationProfile = None):
771    """
772        Creates a new CEDA_Result
773        @param linkage: the MO_OnlineResource.linkage.url.??? field
774        @param name: the MO_OnlineResource.linkage.name field
775        @param function: the MO_OnlineResource.function field
776        @param description: the MO_OnlineResource.description field
777        @param applicationProfile: the MO_OnlineResource.applicationProfile field
778    """
779    on_line_resource = MO_OnlineResource()   
780    on_line_resource.linkage = linkage
781    if name: 
782        on_line_resource.name = name
783    if function:
784        on_line_resource.function = function
785    if description:
786        on_line_resource.description = description
787    if applicationProfile:
788        on_line_resource.applicationProfile = applicationProfile
789    return on_line_resource       
790
791def createCEDA_Result(curation_category, internal_path, source = None):
792    """
793        Creates a new CEDA_Result
794        @param curation_category: a CEDA_CurationValue instance
795        @param internal_path: a String
796        @param source: an array of MO_OnlineResource instances
797    """
798    ceda_result = CEDA_Result()
799    ceda_result.curationCategory = curation_category
800    ceda_result.internalPath = internal_path           
801    if source: 
802        ceda_result.source = source
803    return ceda_result
804
805
806
807def createDQ_ConformanceResult(explanation, pass_, specification):
808    """
809        Creates a DQ_ConformanceResult instance
810        @param explanation: a String
811        @param pass_: a boolean value
812        @param specification: a CI_Citation instance 
813    """
814    dq_conformanceResult = DQ_ConformanceResult()
815    dq_conformanceResult.explanation = explanation
816    dq_conformanceResult.pass_ = pass_
817    dq_conformanceResult.specification = specification
818    return dq_conformanceResult
819
820def createDQ_Element(result):
821    """
822        Creates a DQ_Element instance
823        @param result: a DQ_Result array (mix 1, max 2 items)
824    """
825    dq_element = DQ_Element()
826    if result and (type(result) == list) and (len(result) >= 1 and len(result) <= 2):
827        dq_element.result = result
828    return dq_element
829
830def createEX_GeographicBoundingBox(east, north, west, south):
831    """
832        Creates an EX_GeographicBoundingBox instance
833        @param east: the eastBoundLongitude attribute as float
834        @param north: the northBoundLongitude attribute as float
835        @param west: the westBoundLongitude attribute as float
836        @param south: the southBoundLongitude attribute as float               
837    """
838    ex_geographic_bb = EX_GeographicBoundingBox()
839    ex_geographic_bb.eastBoundLongitude = east
840    ex_geographic_bb.northBoundLatitude = north
841    ex_geographic_bb.westBoundLongitude = west
842    ex_geographic_bb.southBoundLatitude = south
843    return ex_geographic_bb
844   
845def createCEDA_Processing():
846    ceda_processing = CEDA_Processing()
847    return ceda_processing
848
849
850def createCEDA_Instrument():
851    ceda_instrument = CEDA_Instrument()
852    return ceda_instrument
853
854def createCEDA_CompositeProcess():
855    ceda_cp = CEDA_CompositeProcess()
856    return ceda_cp
857
858def createCEDA_Acquisition():
859    ceda_acquisition = CEDA_Acquisition()
860    return ceda_acquisition
861
862def createCEDA_Review(reviewer, reviewFrequency, reviewStatus):
863    """
864        Returns a new CEDA_Review
865        @param reviewer: an MO_ResponsibilityPartyInfo
866        @param reviewFrequency: a CEDA_ReviewFrequencyValue
867        @param reviewStatus: a CEDA_ReviewStatusValue
868    """
869    ceda_review = CEDA_Review()
870    ceda_review.reviewer = reviewer
871    ceda_review.reviewFrequency = reviewFrequency
872    ceda_review.reviewStatus = reviewStatus           
873    return ceda_review
874
875def createCEDA_Project(abstract = None, publication_state = None, documentation = None, project_resource=None):
876    ceda_project = CEDA_Project()
877    if abstract:
878        ceda_project.abstract = abstract
879    if publication_state:
880        ceda_project.publicationState = publication_state       
881    if documentation and type(documentation) == list:
882        ceda_project.documentation = documentation
883    if project_resource and type(project_resource) == list:
884        ceda_project.projectResource = project_resource   
885    return ceda_project   
Note: See TracBrowser for help on using the repository browser.