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

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

Complete - # 22434: CEDA Observation - keywords (following Gemini method)
 http://team.ceda.ac.uk/trac/ceda/ticket/22434
Removed the SA session from all but the EPBxx instances

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