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

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

Incomplete - # 22399: CEDA Observation - permission
 http://team.ceda.ac.uk/trac/ceda/ticket/22399

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.moles3_4.utilities.mo_organization import MO_Organization
36from ea_model.iso_19115_2006_metadata_corrigendum.citation_and_responsible_party_information.ci_contact import CI_Contact
37from ea_model.iso_19115_2006_metadata_corrigendum.citation_and_responsible_party_information.ci_address import CI_Address
38from ea_model.iso_19115_2006_metadata_corrigendum.citation_and_responsible_party_information.ci_onlineresource import CI_OnlineResource
39from ea_model.iso_19115_2006_metadata_corrigendum.citation_and_responsible_party_information.ci_telephone import CI_Telephone
40from ea_model.iso_19108_2006_temporal_schema.temporal_objects.tm_period import TM_Period
41from ea_model.iso_19115_2006_metadata_corrigendum.constraint_information.md_constraints import MD_Constraints
42from ea_model.iso_19115_2006_metadata_corrigendum.constraint_information.md_legalconstraints import MD_LegalConstraints
43from ea_model.ceda_metadatamodel.ceda_project.ceda_project import CEDA_Project
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 extractMolesTemporalRange(migrationObject):
215    resourceXML = getAtomDocumentByMO(migrationObject)
216    temporal_range = resourceXML.find('%stemporalRange' % (molesNS))
217    return _returnNotNoneText(temporal_range)
218
219def extractMolesCreationDate(migrationObject):
220    resourceXML = getAtomDocumentByMO(migrationObject)
221    return findMolesCreationDate(resourceXML)
222
223def extractQuality(dataEntityMigration):
224    resourceXML = getAtomDocumentByMO(dataEntityMigration)
225    quality = resourceXML.find('%sentity/%smolesISO/%squality' % (molesNS, molesNS, molesNS))
226    return _returnNotNoneText(quality)
227
228def extractContent(dataEntityMigration):
229    """
230        Returns a dictionary containing the div composing the
231        <content> element in a dataentity document.
232    """
233    resourceXML = getAtomDocumentByMO(dataEntityMigration)
234    content = resourceXML.find('%scontent' % (atomNS))
235    text = _returnNotNoneText(content)
236    contentDict = {}
237    if text:
238        doc = htmlParser.parse(unescape(text))
239        for el in doc.findall('body//div'):   
240            prop = el.get('property')
241            if prop:
242                if prop.startswith('cedacat'):
243                    contentDict[prop.split(':')[1]] = escape(tostring(el))
244    return contentDict
245
246def _extractAuthors(authorsCSV):
247    if authorsCSV is None:
248        return []
249    authors = authorsCSV.split(',')
250    for index in range(len(authors)):
251        authors[index] = authors[index].strip()
252        if len(authors[index]) == 0:
253            authors.remove(authors[index])
254    return authors
255
256def findAuthorsInResource(resourceMigration):
257    '''
258        Returns a dictionary with the following keys:
259        'authors': a list of string representing the authors
260        'contributors': a list of string representing the contributors
261    '''
262    ret = {}   
263    resourceXML = getAtomDocumentByMO(resourceMigration)
264    ret['authors'] = findAuthorInResource(resourceXML)
265    ret['contributors'] = findContributorInResource(resourceXML)
266    return ret
267
268def findAuthorInResource(resourceXML): 
269    author = resourceXML.find('%sauthor/%sname' % (atomNS, atomNS))
270    return _returnNotNoneText(author)
271
272def findContributorInResource(resourceXML): 
273    contributors = resourceXML.find('%scontributor/%sname' % (atomNS, atomNS))
274    return _returnNotNoneText(contributors)
275
276def findID(dataEntXML):
277    ent_id = dataEntXML.find('%sid' % (atomNS))
278    return _returnNotNoneText(ent_id)
279
280def _updateLinksDict(linksDict, link, linkMarker):
281    if not linksDict.has_key(linkMarker):
282        linksDict[linkMarker] = []
283    rel = link.get('rel')
284    if rel and rel.endswith('/' + linkMarker):
285        linksDict[linkMarker].append({'href': link.get('href'), 'title': link.get('title')}) 
286
287def _extractLinks(dataEntXML, markers):
288    linksDict = {}
289    links = dataEntXML.findall('%slink' % (atomNS))
290    for link in links:
291        for marker in markers:
292            _updateLinksDict(linksDict, link, marker)       
293    return linksDict
294
295def findLinksInMigrationDocument(dataEntityMigration):
296    dataEntXML = getAtomDocumentByMO(dataEntityMigration)
297    linksDict = _extractLinks(dataEntXML, linkMarkers)
298    return linksDict
299
300def findDownloadLinksInMigrationDocument(migrationObject):
301    """
302        Return a list of dictionaries describing a <link rel="...DOWNLOAD..."> tag type
303        Each dictionary has two keys: 'href' and 'title'
304        @param migrationObject: the migration instance to retrieve and parse
305        @return: a list of dictionaries
306    """
307    linksDict = findLinksInMigrationDocument(migrationObject)
308    return linksDict['DOWNLOAD']
309
310def findAccessLinksInMigrationDocument(migrationObject):
311    """
312        Return a list of dictionaries describing a <link rel="...ACCESS..."> tag type
313        Each dictionary has two keys: 'href' and 'title'
314        @param migrationObject: the migration instance to retrieve and parse
315        @return: a list of dictionaries
316    """
317    linksDict = findLinksInMigrationDocument(migrationObject)
318    return linksDict['ACCESS']
319
320def findDOIInMigrationDocument(migrationObject):
321    """
322        Return a dictionary describing a <link rel="...DOCUMENTATION..."> tag type
323        The dictionary has two keys: 'href' and 'title'
324        @param migrationObject: the migration instance to retrieve and parse
325        @return: a dictionary relative to the DOI, None otherwise
326    """
327    linksDict = findLinksInMigrationDocument(migrationObject)
328    for link in linksDict['DOCUMENTATION']:
329        if link['href'].startswith('doi:'):
330            return link
331    return None
332
333def findDeploymentsInDE(dataEntityMigration):
334    linksDict = findLinksInMigrationDocument(dataEntityMigration)
335    links = _extractLinksByMarker(linksDict, 'Deployment')
336    return [depName + '.atom' for depName in links]
337
338def findSubTypeInDPT(resourceMigration):
339    resourceXML = getAtomDocumentByMO(resourceMigration)
340    categories = resourceXML.findall('%scategory' % (atomNS))
341    for category in categories:
342        if category.get("term") == "ATOM_SUBTYPE":
343            return category.get("label")   
344       
345def extractTitle(deploymentMigration):
346    resourceXML = getAtomDocumentByMO(deploymentMigration)
347    title = resourceXML.find('%stitle' % (atomNS))
348    return _returnNotNoneText(title)
349
350def extractSummary(deploymentMigration, dataEntityMigration):
351    resourceXML = getAtomDocumentByMO(deploymentMigration)
352    summary = resourceXML.find('%ssummary' % (atomNS))
353    ret = _returnNotNoneText(summary)
354    if ret:
355        return ret
356    resourceXML = getAtomDocumentByMO(dataEntityMigration)
357    summary = resourceXML.find('%ssummary' % (atomNS))
358    return _returnNotNoneText(summary)
359
360def extractGeographicExtentInMigrationDocument(migrationObject):
361    """
362        Extracts if existing the georss:where/gel:Enveloper/upper-lowerCorner elements.
363        @param migrationObject: a migration object to retrieve to parse for data
364        @return: None if no data are found, otherwise a dictionary with keys: 'east', 'north', 'west', 'south' where
365        the values are float
366    """
367    resourceXML = getAtomDocumentByMO(migrationObject)
368    upperCorner = resourceXML.find('%swhere/%sEnvelope/%supperCorner' % (georssNS, gmlNS, gmlNS))
369    lowerCorner = resourceXML.find('%swhere/%sEnvelope/%slowerCorner' % (georssNS, gmlNS, gmlNS))
370    ret = None
371    if upperCorner != None and lowerCorner != None:
372        upperCornerData = upperCorner.text.split()
373        lowerCornerData = lowerCorner.text.split()
374        ret = {'east': float(upperCornerData[0]), 'north': float(upperCornerData[1]), 'west': float(lowerCornerData[0]), 'south': float(lowerCornerData[1])}
375    return ret
376
377def findLinksInDeployment(migrationObject):
378    """
379        Returns a dictionary of links owned by the given dataEntity document
380        @param deploymentMigration: a MigrationObject instance
381        @return: a dictionary of links.
382    """
383    links = {}
384    linksDict = findLinksInMigrationDocument(migrationObject)
385    for marker in linkMarkers:   
386        links[marker] = _extractLinksByMarker(linksDict, marker)
387    return links
388
389def _extractLinksByMarker(linksDict, marker):
390    dpt = []
391    if linksDict.has_key(marker):
392        for link in linksDict[marker]:
393            try:
394                linkLongName = link['href'].split('/')[-1]
395                linkName = linkLongName.rsplit('__ATOM__')[1]
396                dpt.append(linkName)
397            except Exception as ex:
398                print ex
399    return dpt
400
401
402def getResourceRefs(deploymentRefs):
403    '''
404        Returns a list of Elements representing the inner resource reference items
405        @param resourceRefs: the name of the eXist collection name below the 'deployments' one
406    ''' 
407    XMLDepl = _getXMLDocument(deploymentRefs)
408    return XMLDepl.findall('%scollection/%sresource' % (existNS, existNS))
409
410def getOwnerRefs(docStatus, docType, docOwner):
411    '''
412        Returns a list of Elements representing the inner resource reference items
413        @param resourceRefs: the name of the eXist collection name below the 'deployments' one
414    '''     
415    XMLDepl = _getXMLDocument(buildExistOwnerPath(docStatus, docType, docOwner))
416    return XMLDepl.findall('%scollection/%sresource' % (existNS, existNS))
417
418def getTypeRefs(docStatus, docType):
419    '''
420        Returns a list of Elements representing the inner resource reference items
421        @param resourceRefs: the name of the eXist collection name below the 'deployments' one
422    '''     
423    XMLDepl = _getXMLDocument(buildExistTypePath(docStatus, docType))
424    return XMLDepl.findall('%scollection/%sresource' % (existNS, existNS))
425
426
427
428def getCollectionRefs(publishedRefs):
429    '''
430        Returns a list of Elements representing the inner deployment reference items
431        @param basePublished: the name of the eXist collection name below the 'published' one
432    ''' 
433    XMLPubl = _getXMLDocument(publishedRefs)
434    return XMLPubl.findall('%scollection/%scollection' % (existNS, existNS))
435
436def getResource(source, resourceName):
437    resourceSource = '%s/%s' % (source, resourceName)
438    resourceDoc = _getDocument(resourceSource)
439    return XML(resourceDoc)
440
441def createDateTime(datetime):
442    '''
443        Creates a new DateTime instance.
444        @param datetime: a datetime.datetime instance       
445    '''
446    dateTime = DateTime()
447    dateTime.century = (datetime.year / 100) + 1
448    dateTime.year = datetime.year
449    dateTime.month = datetime.month       
450    dateTime.day = datetime.day
451    dateTime.hour = datetime.hour
452    dateTime.minute = datetime.minute
453    dateTime.second = datetime.second
454    dateTime.timeZone = datetime.tzinfo       
455    return dateTime       
456       
457def createDate(date):
458    '''
459        Creates a new Date instance.
460        @param date: a datetime.date instance
461    '''
462    idate = Date()
463    idate.century = (date.year / 100) + 1
464    idate.year = date.year
465    idate.month = date.month       
466    idate.day = date.day       
467    return idate       
468       
469def createTM_Position(anyOther = None, date8601 = None, dateTime8601 = None, time8601 = None):
470    '''
471        Creates a new TM_Position instance
472        @param anyOther: a TM_TemporalPosition instance
473        @param date8601: a Date instance
474        @param dateTime8601:a DateTime instance
475        @param time8601: a Time instance   
476    '''
477    tm_position = TM_Position()
478    if anyOther:
479        tm_position.anyOther = anyOther
480    if date8601:
481        tm_position.date8601 = date8601 
482    if dateTime8601:
483        tm_position.dateTime8601 = dateTime8601
484    if time8601:
485        tm_position.time8601 = time8601
486    return tm_position           
487
488def createTM_Instant(position):
489    '''
490        Creates a new TM_Position instance
491        @param position: a TM_Position instance
492    '''
493    tm_instant = TM_Instant()
494    tm_instant.position = position
495    return tm_instant
496
497def createTM_Period(begin, end):
498    '''
499        Creates a new TM_Position instance
500        @param position: a TM_Position instance
501    '''
502    tm_period = TM_Period()
503    tm_period.begin = begin
504    tm_period.end = end   
505    return tm_period
506
507def createCI_Address(deliveryPoint = None, electronicMailAddress = None, city = None, country = None, postalCode = None):
508    '''
509        Creates a new CI_Address instance
510        @param deliveryPoint: an array of Strings
511        @param electronicMailAddress: an array of Strings
512        @param city: a string
513        @param country: a string               
514        @param postalCode: a string       
515    '''
516    ci_address = CI_Address()
517    if electronicMailAddress:
518        ci_address.electronicMailAddress = deliveryPoint
519    if postalCode:
520        ci_address.postalCode = postalCode       
521    if city:
522        ci_address.city = city       
523    if country:
524        ci_address.country = country       
525    if postalCode:
526        ci_address.postalCode = postalCode       
527    return ci_address
528
529def createCI_OnlineResource(linkage, name=None):
530    '''
531        Creates a new CI_OnlineResource instance
532        @param linkage: a string (the URL class is associated with a String)
533        @param name: a String
534    '''
535    ci_online_resource = CI_OnlineResource()
536    ci_online_resource.linkage = linkage
537    if name:
538        ci_online_resource.name = name
539    return ci_online_resource
540
541def createCI_Telephone(voice=None, facsimile=None):
542    '''
543        Creates a new CI_Telephone instance
544        @param voice: an array of strings       
545        @param facsimile: an array of strings
546    '''
547    ci_telephone = CI_Telephone()
548    if voice:
549        ci_telephone.voice = voice
550    if facsimile:
551        ci_telephone.facsimile = voice       
552    return ci_telephone
553
554def createCI_Contact(phone, address = None, onlineResource = None):
555    '''
556        Creates a new CI_Contact instance
557        @param phone: a CI_Telephone instance       
558        @param address: a CI_Address instance
559        @param onlineResource: a CI_OnlineResource instance
560    '''
561    ci_contact = CI_Contact()
562    ci_contact.phone = phone
563    if address:
564        ci_contact.address = address
565    if onlineResource:
566        ci_contact.onlineResource = onlineResource       
567    return ci_contact
568
569def createCI_Individual(name = None, contactInfo = None):
570    '''
571        Creates a new CI_Individual instance
572        @param name: a String
573        @param contactInfo: an array of CI_Contact       
574    '''   
575    ci_party = CI_Individual()
576    if name:
577        ci_party.name = name
578    if contactInfo:
579        ci_party.contactInfo = contactInfo       
580    return ci_party
581
582def createMO_Organization(name = None, contactInfo = None):
583    '''
584        Creates a new MO_Organization instance
585        @param name: a String
586        @param contactInfo: an array of CI_Contact       
587    '''       
588    ci_party = MO_Organization()
589    if name:
590        ci_party.name = name
591    if contactInfo:
592        ci_party.contactInfo = contactInfo         
593    return ci_party
594
595def createMO_ResponsiblePartyInfo_(role, i_party):
596    """
597        @param role: a CI_RoleCode/MO_RoleValue assigned to this ResponsibleParty
598        @param party: a list of MO_Organization/CI_Individual instances
599    """
600    mo_responsableInfo = MO_ResponsiblePartyInfo()
601    mo_responsableInfo.role = role
602    mo_responsableInfo.party = i_party
603    return mo_responsableInfo
604
605def createMO_ResponsiblePartyInfoAsCI_Organization(role, names):
606    '''
607        @param role: a CI_RoleCode/MO_RoleValue assigned to this ResponsibleParty
608        @param names: the name assigned to each CI_Party
609    '''
610    return createMO_ResponsiblePartyInfo(role, names, CI_Organisation)
611
612def createMO_ResponsiblePartyInfoAsCI_Individual(role, names):
613    '''
614        @param role: a CI_RoleCode/MO_RoleValue assigned to this ResponsibleParty
615        @param names: the name assigned to each CI_Party
616    '''
617    return createMO_ResponsiblePartyInfo(role, names, CI_Individual)
618
619def createMO_ResponsiblePartyInfo(role, names, partyType = CI_Party):
620    """
621        @param role: a CI_RoleCode/MO_RoleValue assigned to this ResponsibleParty
622        @param names: the name assigned to each CI_Party
623        @param partyType: the CI_Party implementation to use
624    """
625    mo_responsableInfo = MO_ResponsiblePartyInfo()
626    mo_responsableInfo.role = role
627    parties = []
628    for name in names:
629        ci_org = partyType()
630        ci_org.name = name
631        parties.append(ci_org)
632    mo_responsableInfo.party = parties
633    return mo_responsableInfo
634
635
636
637def createCI_Date(dateType, date = None):
638    """
639        Creates a new CI_Date
640        @param dateType: a CI_DateTypeCode value
641        @param date: a timestamp
642    """
643    ci_date = CI_Date()
644    ci_date.dateType = dateType
645    if date:
646        ci_date.date = date
647    return ci_date
648
649def createCI_Citation(title, date = None):
650    """
651        Creates a new CI_Citation
652        @param titile: the CI_Citation title
653        @param date: a CI_Date instance
654    """   
655    ci_citation = CI_Citation()
656    ci_citation.title = title
657    if date:
658        ci_citation.date = date
659    return ci_citation
660
661def createMD_Constraints(useLimitation = None):
662    """
663        Creates a new MD_Constrains
664        @param useLimitation: a string array
665    """ 
666    md_constraints = MD_Constraints()
667    if useLimitation and type(useLimitation) == list:
668        md_constraints.useLimitation = useLimitation
669    return md_constraints
670
671def createMD_LegalConstraints(useLimitation = None, accessConstrains = None):
672    """
673        Creates a new MD_LegalConstrains
674        @param useLimitation: a string array
675        @param accessConstrains: an MD_RestrictionCode array
676    """ 
677    md_legalconstraints = MD_LegalConstraints()
678    if useLimitation and type(useLimitation) == list:
679        md_legalconstraints.useLimitation = useLimitation
680    if accessConstrains and type(accessConstrains) == list:
681        md_legalconstraints.accessConstrains = accessConstrains       
682    return md_legalconstraints
683
684def createMD_Identifier(code, authority = None):
685    """
686        Creates a new MD_Identifier
687        @param title: the MD_Identifier.authority.title field
688        @param code: the MD_Identifier.code field
689        @param date: the MD_Identifier.authority.date field
690    """
691    md_identifier = MD_Identifier()
692    md_identifier.code = code
693    if authority:
694        md_identifier.authority = authority
695    return md_identifier
696
697def createMO_OnlineResource(linkage, name = None, function = None, description = None, applicationProfile = None):
698    """
699        Creates a new CEDA_Result
700        @param linkage: the MO_OnlineResource.linkage.url.??? field
701        @param name: the MO_OnlineResource.linkage.name field
702        @param function: the MO_OnlineResource.function field
703        @param description: the MO_OnlineResource.description field
704        @param applicationProfile: the MO_OnlineResource.applicationProfile field
705    """
706    on_line_resource = MO_OnlineResource()
707    url = URL()
708    #url.???? = linkage   
709    on_line_resource.linkage = url
710    if name: 
711        on_line_resource.name = name
712    if function:
713        on_line_resource.function = function
714    if description:
715        on_line_resource.description = description
716    if applicationProfile:
717        on_line_resource.applicationProfile = applicationProfile
718    return on_line_resource       
719
720def createCEDA_Result(linkage, name = None, function = None, description = None, applicationProfile = None):
721    """
722        Creates a new CEDA_Result
723        @param linkage: the CEDA_Result.source.linkage.url.??? field
724        @param name: the CEDA_Result.source.linkage.name field
725        @param function: the CEDA_Result.source.function field
726    """
727    ceda_result = CEDA_Result()
728    on_line_resource = createMO_OnlineResource(linkage, name, function, description, applicationProfile)       
729    ceda_result.source.append(on_line_resource)
730    return ceda_result
731
732
733
734def createDQ_ConformanceResult(explaination = ""):
735    dq_conformanceResult = DQ_ConformanceResult()
736    dq_conformanceResult.explanation = explaination
737    return dq_conformanceResult
738
739def createDQ_Element(explaination = ""):
740    dq_element = DQ_Element()
741    dq_element.result = []
742    dq_result = createDQ_ConformanceResult(explaination)
743    dq_element.result.append(dq_result)
744    return dq_element
745
746def createEX_GeographicBoundingBox(east, north, west, south):
747    """
748        Creates an EX_GeographicBoundingBox instance
749        @param east: the eastBoundLongitude attribute as float
750        @param north: the northBoundLongitude attribute as float
751        @param west: the westBoundLongitude attribute as float
752        @param south: the southBoundLongitude attribute as float               
753    """
754    ex_geographic_bb = EX_GeographicBoundingBox()
755    ex_geographic_bb.eastBoundLongitude = east
756    ex_geographic_bb.northBoundLatitude = north
757    ex_geographic_bb.westBoundLongitude = west
758    ex_geographic_bb.southBoundLatitude = south
759    return ex_geographic_bb
760   
761def createCEDA_Processing():
762    ceda_processing = CEDA_Processing()
763    return ceda_processing
764
765
766def createCEDA_Instrument():
767    ceda_instrument = CEDA_Instrument()
768    return ceda_instrument
769
770def createCEDA_CompositeProcess():
771    ceda_cp = CEDA_CompositeProcess()
772    return ceda_cp
773
774def createCEDA_Acquisition():
775    ceda_acquisition = CEDA_Acquisition()
776    return ceda_acquisition
777
778def createCEDA_Project():
779    ceda_project = CEDA_Project()
780    return ceda_project   
Note: See TracBrowser for help on using the repository browser.