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

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

Incomplete - # 22385: CEDA Observation - result
 http://team.ceda.ac.uk/trac/ceda/ticket/22385

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