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

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

Complete - # 22434: CEDA Observation - keywords (following Gemini method)
 http://team.ceda.ac.uk/trac/ceda/ticket/22434

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('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                linkName = linkLongName.rsplit('__ATOM__')[1]
455                dpt.append(linkName)
456            except Exception as ex:
457                print "WARN - Cannot extractLinksByMarker %s" % (link)
458    return dpt
459
460
461def getResourceRefs(deploymentRefs):
462    '''
463        Returns a list of Elements representing the inner resource reference items
464        @param resourceRefs: the name of the eXist collection name below the 'deployments' one
465    ''' 
466    XMLDepl = _getXMLDocument(deploymentRefs)
467    return XMLDepl.findall('%scollection/%sresource' % (existNS, existNS))
468
469def getOwnerRefs(docStatus, docType, docOwner):
470    '''
471        Returns a list of Elements representing the inner resource reference items
472        @param resourceRefs: the name of the eXist collection name below the 'deployments' one
473    '''     
474    XMLDepl = _getXMLDocument(buildExistOwnerPath(docStatus, docType, docOwner))
475    return XMLDepl.findall('%scollection/%sresource' % (existNS, existNS))
476
477def getTypeRefs(docStatus, docType):
478    '''
479        Returns a list of Elements representing the inner resource reference items
480        @param resourceRefs: the name of the eXist collection name below the 'deployments' one
481    '''     
482    XMLDepl = _getXMLDocument(buildExistTypePath(docStatus, docType))
483    return XMLDepl.findall('%scollection/%sresource' % (existNS, existNS))
484
485
486
487def getCollectionRefs(publishedRefs):
488    '''
489        Returns a list of Elements representing the inner deployment reference items
490        @param basePublished: the name of the eXist collection name below the 'published' one
491    ''' 
492    XMLPubl = _getXMLDocument(publishedRefs)
493    return XMLPubl.findall('%scollection/%scollection' % (existNS, existNS))
494
495def getResource(source, resourceName):
496    resourceSource = '%s/%s' % (source, resourceName)
497    resourceDoc = _getDocument(resourceSource)
498    return XML(resourceDoc)
499
500def createMD_Keywords(keywords, k_type=None, thesaurusName=None):
501    '''
502        Creates a new MD_Keywords instance.
503        @param keywords: a String array       
504    '''   
505    md_keywords = MD_Keywords()
506    md_keywords.keyword.extend(keywords)
507    if k_type:
508        md_keywords.type = k_type
509    if thesaurusName:
510        md_keywords.thesaurusName = thesaurusName       
511    return md_keywords
512   
513
514def createDateTime(datetime):
515    '''
516        Creates a new DateTime instance.
517        @param datetime: a datetime.datetime instance       
518    '''
519    dateTime = DateTime()
520    dateTime.century = (datetime.year / 100) + 1
521    dateTime.year = datetime.year
522    dateTime.month = datetime.month       
523    dateTime.day = datetime.day
524    dateTime.hour = datetime.hour
525    dateTime.minute = datetime.minute
526    dateTime.second = datetime.second
527    dateTime.timeZone = datetime.tzinfo       
528    return dateTime       
529       
530def createDate(date):
531    '''
532        Creates a new Date instance.
533        @param date: a datetime.datetime instance
534    '''
535    idate = Date()
536    idate.century = (date.year / 100) + 1
537    idate.year = date.year
538    idate.month = date.month       
539    idate.day = date.day       
540    return idate       
541       
542def createTM_Position(anyOther = None, date8601 = None, dateTime8601 = None, time8601 = None):
543    '''
544        Creates a new TM_Position instance
545        @param anyOther: a TM_TemporalPosition instance
546        @param date8601: a Date instance
547        @param dateTime8601:a DateTime instance
548        @param time8601: a Time instance   
549    '''
550    tm_position = TM_Position()
551    if anyOther:
552        tm_position.anyOther = anyOther
553    if date8601:
554        tm_position.date8601 = date8601 
555    if dateTime8601:
556        tm_position.dateTime8601 = dateTime8601
557    if time8601:
558        tm_position.time8601 = time8601
559    return tm_position           
560
561def createTM_Instant(position):
562    '''
563        Creates a new TM_Position instance
564        @param position: a TM_Position instance
565    '''
566    tm_instant = TM_Instant()
567    tm_instant.position = position
568    return tm_instant
569
570def createTM_Period(begin, end):
571    '''
572        Creates a new TM_Position instance
573        @param position: a TM_Position instance
574    '''
575    tm_period = TM_Period()
576    tm_period.begin = begin
577    tm_period.end = end   
578    return tm_period
579
580def createCI_Address(deliveryPoint = None, electronicMailAddress = None, city = None, country = None, postalCode = None):
581    '''
582        Creates a new CI_Address instance
583        @param deliveryPoint: an array of Strings
584        @param electronicMailAddress: an array of Strings
585        @param city: a string
586        @param country: a string               
587        @param postalCode: a string       
588    '''
589    ci_address = CI_Address()
590    if deliveryPoint:
591        ci_address.deliveryPoint = deliveryPoint
592    if electronicMailAddress:
593        ci_address.electronicMailAddress = electronicMailAddress       
594    if postalCode:
595        ci_address.postalCode = postalCode       
596    if city:
597        ci_address.city = city       
598    if country:
599        ci_address.country = country       
600    if postalCode:
601        ci_address.postalCode = postalCode       
602    return ci_address
603
604def createCI_OnlineResource(linkage, name=None):
605    '''
606        Creates a new CI_OnlineResource instance
607        @param linkage: a string (the URL class is associated with a String)
608        @param name: a String
609    '''
610    ci_online_resource = CI_OnlineResource()
611    ci_online_resource.linkage = linkage
612    if name:
613        ci_online_resource.name = name
614    return ci_online_resource
615
616def createCI_Telephone(voice=None, facsimile=None):
617    '''
618        Creates a new CI_Telephone instance
619        @param voice: an array of strings       
620        @param facsimile: an array of strings
621    '''
622    ci_telephone = CI_Telephone()
623    if voice:
624        ci_telephone.voice = voice
625    if facsimile:
626        ci_telephone.facsimile = voice       
627    return ci_telephone
628
629def createCI_Contact(phone, address = None, onlineResource = None):
630    '''
631        Creates a new CI_Contact instance
632        @param phone: a CI_Telephone instance       
633        @param address: a CI_Address instance
634        @param onlineResource: a CI_OnlineResource instance
635    '''
636    ci_contact = CI_Contact()
637    ci_contact.phone = phone
638    if address:
639        ci_contact.address = address
640    if onlineResource:
641        ci_contact.onlineResource = onlineResource       
642    return ci_contact
643
644def createCI_Individual(name = None, contactInfo = None):
645    '''
646        Creates a new CI_Individual instance
647        @param name: a String
648        @param contactInfo: an array of CI_Contact       
649    '''   
650    ci_party = CI_Individual()
651    if name:
652        ci_party.name = name
653    if contactInfo:
654        ci_party.contactInfo = contactInfo       
655    return ci_party
656
657def createCI_Organization(name = None, contactInfo = None):
658    '''
659        Creates a new CI_Individual instance
660        @param name: a String
661        @param contactInfo: an array of CI_Contact       
662    '''   
663    ci_party = CI_Organisation()
664    if name:
665        ci_party.name = name
666    if contactInfo:
667        ci_party.contactInfo = contactInfo       
668    return ci_party
669
670def createMO_Organization(name = None, contactInfo = None):
671    '''
672        Creates a new MO_Organization instance.
673        TEMPORARILY RETURNS A CI_ORGANIZATION BECAUSE A DB SCHEMA PROBLEM!!!!
674        @param name: a String
675        @param contactInfo: an array of CI_Contact       
676    '''       
677    ci_party = CI_Organisation()
678    if name:
679        ci_party.name = name
680    if contactInfo:
681        ci_party.contactInfo = contactInfo         
682    return ci_party
683
684def createMO_ResponsiblePartyInfo(role, i_party):
685    """
686        @param role: a CI_RoleCode/MO_RoleValue assigned to this ResponsibleParty
687        @param party: a list of MO_Organization/CI_Individual instances
688    """
689    mo_responsableInfo = MO_ResponsiblePartyInfo()
690    mo_responsableInfo.role = role
691    mo_responsableInfo.party.extend(i_party)
692    return mo_responsableInfo
693
694
695def createCI_Date(dateType, date = None):
696    """
697        Creates a new CI_Date
698        @param dateType: a CI_DateTypeCode value
699        @param date: a DateTime instance
700    """
701    ci_date = CI_Date()
702    ci_date.dateType = dateType
703    if date:
704        ci_date.date = date
705    return ci_date
706
707def createCI_Citation(title, date = None, citedResponsibleParty = None):
708    """
709        Creates a new CI_Citation
710        @param title: the CI_Citation title
711        @param date: an array of CI_Date instances
712        @param citedResponsibleParty: a list of CI_ResponsibleParty instances
713    """   
714    ci_citation = CI_Citation()
715    ci_citation.title = title
716    if date and type(date) == list:
717        ci_citation.date = date
718    if citedResponsibleParty:
719        ci_citation.extend(citedResponsibleParty)
720    return ci_citation
721
722def createMD_Constraints(useLimitation = None):
723    """
724        Creates a new MD_Constrains
725        @param useLimitation: a string array
726    """ 
727    md_constraints = MD_Constraints()
728    if useLimitation and type(useLimitation) == list:
729        md_constraints.useLimitation = useLimitation
730    return md_constraints
731
732def createMD_LegalConstraints(useLimitation = None, accessConstrains = None):
733    """
734        Creates a new MD_LegalConstrains
735        @param useLimitation: a string array
736        @param accessConstrains: an MD_RestrictionCode array
737    """ 
738    md_legalconstraints = MD_LegalConstraints()
739    if useLimitation and type(useLimitation) == list:
740        md_legalconstraints.useLimitation = useLimitation
741    if accessConstrains and type(accessConstrains) == list:
742        md_legalconstraints.accessConstrains = accessConstrains       
743    return md_legalconstraints
744
745def createMD_Identifier(code, authority = None):
746    """
747        Creates a new MD_Identifier
748        @param code: a String
749        @param authority: a CI_Citation instance
750    """
751    md_identifier = MD_Identifier()
752    md_identifier.code = code
753    if authority:
754        md_identifier.authority = authority
755    return md_identifier
756
757def createCI_ResponsibleParty(role, organizationName = None, individualName = None):
758    """
759        Creates a new CI_ResponsibeParty
760        @param role: a CI_RoleCode
761    """
762    ci_responsible_party = CI_ResponsibleParty()
763    ci_responsible_party.role = role
764    if organizationName:
765        ci_responsible_party.organisationName = organizationName
766    if individualName:
767        ci_responsible_party.individualName = individualName   
768    return ci_responsible_party
769
770def createMD_Metadata(date_stamp, contact, language = None):
771    """
772        Creates a new MD_Metadata
773        @param date_stamp: a Date instance
774        @param contacts: a CI_ResponsibleParty array instances
775        @param language: a string
776    """   
777    md_metadata = MD_Metadata()
778    md_metadata.dateStamp = date_stamp
779    for item in contact:
780        md_metadata.contact.append(item)
781    if language:
782        md_metadata.language = language   
783    return md_metadata
784
785def createMO_OnlineResource(linkage, name = None, function = None, description = None, applicationProfile = None):
786    """
787        Creates a new CEDA_Result
788        @param linkage: the MO_OnlineResource.linkage.url.??? field
789        @param name: the MO_OnlineResource.linkage.name field
790        @param function: the MO_OnlineResource.function field
791        @param description: the MO_OnlineResource.description field
792        @param applicationProfile: the MO_OnlineResource.applicationProfile field
793    """
794    on_line_resource = MO_OnlineResource()   
795    on_line_resource.linkage = linkage
796    if name: 
797        on_line_resource.name = name
798    if function:
799        on_line_resource.function = function
800    if description:
801        on_line_resource.description = description
802    if applicationProfile:
803        on_line_resource.applicationProfile = applicationProfile
804    return on_line_resource       
805
806def createCEDA_Result(curation_category, internal_path, source = None):
807    """
808        Creates a new CEDA_Result
809        @param curation_category: a CEDA_CurationValue instance
810        @param internal_path: a String
811        @param source: an array of MO_OnlineResource instances
812    """
813    ceda_result = CEDA_Result()
814    ceda_result.curationCategory = curation_category
815    ceda_result.internalPath = internal_path           
816    if source: 
817        ceda_result.source = source
818    return ceda_result
819
820
821
822def createDQ_ConformanceResult(explanation, pass_, specification):
823    """
824        Creates a DQ_ConformanceResult instance
825        @param explanation: a String
826        @param pass_: a boolean value
827        @param specification: a CI_Citation instance 
828    """
829    dq_conformanceResult = DQ_ConformanceResult()
830    dq_conformanceResult.explanation = explanation
831    dq_conformanceResult.pass_ = pass_
832    dq_conformanceResult.specification = specification
833    return dq_conformanceResult
834
835def createDQ_Element(result):
836    """
837        Creates a DQ_Element instance
838        @param result: a DQ_Result array (mix 1, max 2 items)
839    """
840    dq_element = DQ_Element()
841    if result and (type(result) == list) and (len(result) >= 1 and len(result) <= 2):
842        dq_element.result = result
843    return dq_element
844
845def createEX_GeographicBoundingBox(east, north, west, south):
846    """
847        Creates an EX_GeographicBoundingBox instance
848        @param east: the eastBoundLongitude attribute as float
849        @param north: the northBoundLongitude attribute as float
850        @param west: the westBoundLongitude attribute as float
851        @param south: the southBoundLongitude attribute as float               
852    """
853    ex_geographic_bb = EX_GeographicBoundingBox()
854    ex_geographic_bb.eastBoundLongitude = east
855    ex_geographic_bb.northBoundLatitude = north
856    ex_geographic_bb.westBoundLongitude = west
857    ex_geographic_bb.southBoundLatitude = south
858    return ex_geographic_bb
859   
860def createCEDA_Processing():
861    ceda_processing = CEDA_Processing()
862    return ceda_processing
863
864
865def createCEDA_Instrument():
866    ceda_instrument = CEDA_Instrument()
867    return ceda_instrument
868
869def createCEDA_CompositeProcess():
870    ceda_cp = CEDA_CompositeProcess()
871    return ceda_cp
872
873def createCEDA_Acquisition():
874    ceda_acquisition = CEDA_Acquisition()
875    return ceda_acquisition
876
877def createCEDA_Review(reviewer, reviewFrequency, reviewStatus):
878    """
879        Returns a new CEDA_Review
880        @param reviewer: an MO_ResponsibilityPartyInfo
881        @param reviewFrequency: a CEDA_ReviewFrequencyValue
882        @param reviewStatus: a CEDA_ReviewStatusValue
883    """
884    ceda_review = CEDA_Review()
885    ceda_review.reviewer = reviewer
886    ceda_review.reviewFrequency = reviewFrequency
887    ceda_review.reviewStatus = reviewStatus           
888    return ceda_review
889
890def createCEDA_Project(abstract = None, publication_state = None, documentation = None, project_resource=None):
891    ceda_project = CEDA_Project()
892    if abstract:
893        ceda_project.abstract = abstract
894    if publication_state:
895        ceda_project.publicationState = publication_state       
896    if documentation and type(documentation) == list:
897        ceda_project.documentation = documentation
898    if project_resource and type(project_resource) == list:
899        ceda_project.projectResource = project_resource   
900    return ceda_project   
Note: See TracBrowser for help on using the repository browser.