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

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

Complete - # 22423: CEDA Project - publicationState
 http://team.ceda.ac.uk/trac/ceda/ticket/22423

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