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

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

Incomplete - # 22412: CEDA Observation - publisher, curator
 http://team.ceda.ac.uk/trac/ceda/ticket/22412

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    return linksDict['DOWNLOAD']
336
337def findAccessLinksInMigrationDocument(migrationObject):
338    """
339        Return a list of dictionaries describing a <link rel="...ACCESS..."> tag type
340        Each dictionary has two keys: 'href' and 'title'
341        @param migrationObject: the migration instance to retrieve and parse
342        @return: a list of dictionaries
343    """
344    linksDict = findLinksInMigrationDocument(migrationObject)
345    return linksDict['ACCESS']
346
347def findDocumentationInMigrationDocument(migrationObject):
348    """
349        Return a list of dictionaries describing a <link rel="...DOCUMENT..."> tag type
350        Each dictionary has two keys: 'href' and 'title'
351        @param migrationObject: the migration instance to retrieve and parse
352        @return: a list of dictionaries
353    """
354    linksDict = findLinksInMigrationDocument(migrationObject)
355    return linksDict['DOCUMENT']
356
357def findDOIInMigrationDocument(migrationObject):
358    """
359        Return a dictionary describing a <link rel="...DOCUMENTATION..."> tag type
360        The dictionary has two keys: 'href' and 'title'
361        @param migrationObject: the migration instance to retrieve and parse
362        @return: a dictionary relative to the DOI, None otherwise
363    """
364    for link in findDocumentationInMigrationDocument(migrationObject):
365        if link['href'].startswith('doi:'):
366            return link
367    return None
368
369def findDeploymentsInDE(dataEntityMigration):
370    linksDict = findLinksInMigrationDocument(dataEntityMigration)
371    links = _extractLinksByMarker(linksDict, 'Deployment')
372    return [depName + '.atom' for depName in links]
373
374def findSubTypeInDPT(resourceMigration):
375    resourceXML = getAtomDocumentByMO(resourceMigration)
376    categories = resourceXML.findall('%scategory' % (atomNS))
377    for category in categories:
378        if category.get("term") == "ATOM_SUBTYPE":
379            return category.get("label")   
380       
381def extractTitle(deploymentMigration):
382    resourceXML = getAtomDocumentByMO(deploymentMigration)
383    title = resourceXML.find('%stitle' % (atomNS))
384    return _returnNotNoneText(title)
385
386def extractSummary(deploymentMigration, dataEntityMigration):
387    resourceXML = getAtomDocumentByMO(deploymentMigration)
388    summary = resourceXML.find('%ssummary' % (atomNS))
389    ret = _returnNotNoneText(summary)
390    if ret:
391        return ret
392    resourceXML = getAtomDocumentByMO(dataEntityMigration)
393    summary = resourceXML.find('%ssummary' % (atomNS))
394    return _returnNotNoneText(summary)
395
396def extractGeographicExtentInMigrationDocument(migrationObject):
397    """
398        Extracts if existing the georss:where/gel:Enveloper/upper-lowerCorner elements.
399        @param migrationObject: a migration object to retrieve to parse for data
400        @return: None if no data are found, otherwise a dictionary with keys: 'east', 'north', 'west', 'south' where
401        the values are float
402    """
403    resourceXML = getAtomDocumentByMO(migrationObject)
404    upperCorner = resourceXML.find('%swhere/%sEnvelope/%supperCorner' % (georssNS, gmlNS, gmlNS))
405    lowerCorner = resourceXML.find('%swhere/%sEnvelope/%slowerCorner' % (georssNS, gmlNS, gmlNS))
406    ret = None
407    if upperCorner != None and lowerCorner != None:
408        upperCornerData = upperCorner.text.split()
409        lowerCornerData = lowerCorner.text.split()
410        ret = {'east': float(upperCornerData[0]), 'north': float(upperCornerData[1]), 'west': float(lowerCornerData[0]), 'south': float(lowerCornerData[1])}
411    return ret
412
413def findLinksInDeployment(migrationObject):
414    """
415        Returns a dictionary of links owned by the given dataEntity document
416        @param deploymentMigration: a MigrationObject instance
417        @return: a dictionary of links.
418    """
419    links = {}
420    linksDict = findLinksInMigrationDocument(migrationObject)
421    for marker in linkMarkers:   
422        links[marker] = _extractLinksByMarker(linksDict, marker)
423    return links
424
425def _extractLinksByMarker(linksDict, marker):
426    dpt = []
427    if linksDict.has_key(marker):
428        for link in linksDict[marker]:
429            try:
430                linkLongName = link['href'].split('/')[-1]
431                linkName = linkLongName.rsplit('__ATOM__')[1]
432                dpt.append(linkName)
433            except Exception as ex:
434                print ex
435    return dpt
436
437
438def getResourceRefs(deploymentRefs):
439    '''
440        Returns a list of Elements representing the inner resource reference items
441        @param resourceRefs: the name of the eXist collection name below the 'deployments' one
442    ''' 
443    XMLDepl = _getXMLDocument(deploymentRefs)
444    return XMLDepl.findall('%scollection/%sresource' % (existNS, existNS))
445
446def getOwnerRefs(docStatus, docType, docOwner):
447    '''
448        Returns a list of Elements representing the inner resource reference items
449        @param resourceRefs: the name of the eXist collection name below the 'deployments' one
450    '''     
451    XMLDepl = _getXMLDocument(buildExistOwnerPath(docStatus, docType, docOwner))
452    return XMLDepl.findall('%scollection/%sresource' % (existNS, existNS))
453
454def getTypeRefs(docStatus, docType):
455    '''
456        Returns a list of Elements representing the inner resource reference items
457        @param resourceRefs: the name of the eXist collection name below the 'deployments' one
458    '''     
459    XMLDepl = _getXMLDocument(buildExistTypePath(docStatus, docType))
460    return XMLDepl.findall('%scollection/%sresource' % (existNS, existNS))
461
462
463
464def getCollectionRefs(publishedRefs):
465    '''
466        Returns a list of Elements representing the inner deployment reference items
467        @param basePublished: the name of the eXist collection name below the 'published' one
468    ''' 
469    XMLPubl = _getXMLDocument(publishedRefs)
470    return XMLPubl.findall('%scollection/%scollection' % (existNS, existNS))
471
472def getResource(source, resourceName):
473    resourceSource = '%s/%s' % (source, resourceName)
474    resourceDoc = _getDocument(resourceSource)
475    return XML(resourceDoc)
476
477def createDateTime(datetime):
478    '''
479        Creates a new DateTime instance.
480        @param datetime: a datetime.datetime instance       
481    '''
482    dateTime = DateTime()
483    dateTime.century = (datetime.year / 100) + 1
484    dateTime.year = datetime.year
485    dateTime.month = datetime.month       
486    dateTime.day = datetime.day
487    dateTime.hour = datetime.hour
488    dateTime.minute = datetime.minute
489    dateTime.second = datetime.second
490    dateTime.timeZone = datetime.tzinfo       
491    return dateTime       
492       
493def createDate(date):
494    '''
495        Creates a new Date instance.
496        @param date: a datetime.datetime instance
497    '''
498    idate = Date()
499    idate.century = (date.year / 100) + 1
500    idate.year = date.year
501    idate.month = date.month       
502    idate.day = date.day       
503    return idate       
504       
505def createTM_Position(anyOther = None, date8601 = None, dateTime8601 = None, time8601 = None):
506    '''
507        Creates a new TM_Position instance
508        @param anyOther: a TM_TemporalPosition instance
509        @param date8601: a Date instance
510        @param dateTime8601:a DateTime instance
511        @param time8601: a Time instance   
512    '''
513    tm_position = TM_Position()
514    if anyOther:
515        tm_position.anyOther = anyOther
516    if date8601:
517        tm_position.date8601 = date8601 
518    if dateTime8601:
519        tm_position.dateTime8601 = dateTime8601
520    if time8601:
521        tm_position.time8601 = time8601
522    return tm_position           
523
524def createTM_Instant(position):
525    '''
526        Creates a new TM_Position instance
527        @param position: a TM_Position instance
528    '''
529    tm_instant = TM_Instant()
530    tm_instant.position = position
531    return tm_instant
532
533def createTM_Period(begin, end):
534    '''
535        Creates a new TM_Position instance
536        @param position: a TM_Position instance
537    '''
538    tm_period = TM_Period()
539    tm_period.begin = begin
540    tm_period.end = end   
541    return tm_period
542
543def createCI_Address(deliveryPoint = None, electronicMailAddress = None, city = None, country = None, postalCode = None):
544    '''
545        Creates a new CI_Address instance
546        @param deliveryPoint: an array of Strings
547        @param electronicMailAddress: an array of Strings
548        @param city: a string
549        @param country: a string               
550        @param postalCode: a string       
551    '''
552    ci_address = CI_Address()
553    if deliveryPoint:
554        ci_address.deliveryPoint = deliveryPoint
555    if electronicMailAddress:
556        ci_address.electronicMailAddress = electronicMailAddress       
557    if postalCode:
558        ci_address.postalCode = postalCode       
559    if city:
560        ci_address.city = city       
561    if country:
562        ci_address.country = country       
563    if postalCode:
564        ci_address.postalCode = postalCode       
565    return ci_address
566
567def createCI_OnlineResource(linkage, name=None):
568    '''
569        Creates a new CI_OnlineResource instance
570        @param linkage: a string (the URL class is associated with a String)
571        @param name: a String
572    '''
573    ci_online_resource = CI_OnlineResource()
574    ci_online_resource.linkage = linkage
575    if name:
576        ci_online_resource.name = name
577    return ci_online_resource
578
579def createCI_Telephone(voice=None, facsimile=None):
580    '''
581        Creates a new CI_Telephone instance
582        @param voice: an array of strings       
583        @param facsimile: an array of strings
584    '''
585    ci_telephone = CI_Telephone()
586    if voice:
587        ci_telephone.voice = voice
588    if facsimile:
589        ci_telephone.facsimile = voice       
590    return ci_telephone
591
592def createCI_Contact(phone, address = None, onlineResource = None):
593    '''
594        Creates a new CI_Contact instance
595        @param phone: a CI_Telephone instance       
596        @param address: a CI_Address instance
597        @param onlineResource: a CI_OnlineResource instance
598    '''
599    ci_contact = CI_Contact()
600    ci_contact.phone = phone
601    if address:
602        ci_contact.address = address
603    if onlineResource:
604        ci_contact.onlineResource = onlineResource       
605    return ci_contact
606
607def createCI_Individual(name = None, contactInfo = None):
608    '''
609        Creates a new CI_Individual instance
610        @param name: a String
611        @param contactInfo: an array of CI_Contact       
612    '''   
613    ci_party = CI_Individual()
614    if name:
615        ci_party.name = name
616    if contactInfo:
617        ci_party.contactInfo = contactInfo       
618    return ci_party
619
620def createCI_Organization(name = None, contactInfo = None):
621    '''
622        Creates a new CI_Individual instance
623        @param name: a String
624        @param contactInfo: an array of CI_Contact       
625    '''   
626    ci_party = CI_Organisation()
627    if name:
628        ci_party.name = name
629    if contactInfo:
630        ci_party.contactInfo = contactInfo       
631    return ci_party
632
633def createMO_Organization(name = None, contactInfo = None):
634    '''
635        Creates a new MO_Organization instance.
636        TEMPORARILY RETURNS A CI_ORGANIZATION BECAUSE A DB SCHEMA PROBLEM!!!!
637        @param name: a String
638        @param contactInfo: an array of CI_Contact       
639    '''       
640    ci_party = CI_Organisation()
641    if name:
642        ci_party.name = name
643    if contactInfo:
644        ci_party.contactInfo = contactInfo         
645    return ci_party
646
647def createMO_ResponsiblePartyInfo_(role, i_party):
648    """
649        @param role: a CI_RoleCode/MO_RoleValue assigned to this ResponsibleParty
650        @param party: a list of MO_Organization/CI_Individual instances
651    """
652    mo_responsableInfo = MO_ResponsiblePartyInfo()
653    mo_responsableInfo.role = role
654    mo_responsableInfo.party = i_party
655    return mo_responsableInfo
656
657def createMO_ResponsiblePartyInfoAsCI_Organization(role, names):
658    '''
659        @param role: a CI_RoleCode/MO_RoleValue assigned to this ResponsibleParty
660        @param names: the name assigned to each CI_Party
661    '''
662    return createMO_ResponsiblePartyInfo(role, names, CI_Organisation)
663
664def createMO_ResponsiblePartyInfoAsCI_Individual(role, names):
665    '''
666        @param role: a CI_RoleCode/MO_RoleValue assigned to this ResponsibleParty
667        @param names: the name assigned to each CI_Party
668    '''
669    return createMO_ResponsiblePartyInfo(role, names, CI_Individual)
670
671def createMO_ResponsiblePartyInfo(role, names, partyType = CI_Party):
672    """
673        @param role: a CI_RoleCode/MO_RoleValue assigned to this ResponsibleParty
674        @param names: the name assigned to each CI_Party
675        @param partyType: the CI_Party implementation to use
676    """
677    mo_responsableInfo = MO_ResponsiblePartyInfo()
678    mo_responsableInfo.role = role
679    parties = []
680    for name in names:
681        ci_org = partyType()
682        ci_org.name = name
683        parties.append(ci_org)
684    mo_responsableInfo.party = parties
685    return mo_responsableInfo
686
687
688
689def createCI_Date(dateType, date = None):
690    """
691        Creates a new CI_Date
692        @param dateType: a CI_DateTypeCode value
693        @param date: a DateTime instance
694    """
695    ci_date = CI_Date()
696    ci_date.dateType = dateType
697    if date:
698        ci_date.date = date
699    return ci_date
700
701def createCI_Citation(title, date = None):
702    """
703        Creates a new CI_Citation
704        @param titile: the CI_Citation title
705        @param date: an array of CI_Date instances
706    """   
707    ci_citation = CI_Citation()
708    ci_citation.title = title
709    if date and type(date) == list:
710        ci_citation.date = date
711    return ci_citation
712
713def createMD_Constraints(useLimitation = None):
714    """
715        Creates a new MD_Constrains
716        @param useLimitation: a string array
717    """ 
718    md_constraints = MD_Constraints()
719    if useLimitation and type(useLimitation) == list:
720        md_constraints.useLimitation = useLimitation
721    return md_constraints
722
723def createMD_LegalConstraints(useLimitation = None, accessConstrains = None):
724    """
725        Creates a new MD_LegalConstrains
726        @param useLimitation: a string array
727        @param accessConstrains: an MD_RestrictionCode array
728    """ 
729    md_legalconstraints = MD_LegalConstraints()
730    if useLimitation and type(useLimitation) == list:
731        md_legalconstraints.useLimitation = useLimitation
732    if accessConstrains and type(accessConstrains) == list:
733        md_legalconstraints.accessConstrains = accessConstrains       
734    return md_legalconstraints
735
736def createMD_Identifier(code, authority = None):
737    """
738        Creates a new MD_Identifier
739        @param title: the MD_Identifier.authority.title field
740        @param code: the MD_Identifier.code field
741        @param date: the MD_Identifier.authority.date field
742    """
743    md_identifier = MD_Identifier()
744    md_identifier.code = code
745    if authority:
746        md_identifier.authority = authority
747    return md_identifier
748
749def createMD_Metadata(date_stamp, contact, language = None):
750    """
751        Creates a new MD_Metadata
752        @param date_stamp: a Date instance
753        @param contact: a CI_Citation instance
754        @param language: a string
755    """   
756    md_metadata = MD_Metadata()
757    md_metadata.dateStamp = date_stamp
758    md_metadata.contact = contact
759    if language:
760        md_metadata.language = language   
761    return md_metadata
762
763def createMO_OnlineResource(linkage, name = None, function = None, description = None, applicationProfile = None):
764    """
765        Creates a new CEDA_Result
766        @param linkage: the MO_OnlineResource.linkage.url.??? field
767        @param name: the MO_OnlineResource.linkage.name field
768        @param function: the MO_OnlineResource.function field
769        @param description: the MO_OnlineResource.description field
770        @param applicationProfile: the MO_OnlineResource.applicationProfile field
771    """
772    on_line_resource = MO_OnlineResource()
773    url = URL()
774    #url.???? = linkage   
775    on_line_resource.linkage = url
776    if name: 
777        on_line_resource.name = name
778    if function:
779        on_line_resource.function = function
780    if description:
781        on_line_resource.description = description
782    if applicationProfile:
783        on_line_resource.applicationProfile = applicationProfile
784    return on_line_resource       
785
786def createCEDA_Result(linkage, name = None, function = None, description = None, applicationProfile = None):
787    """
788        Creates a new CEDA_Result
789        @param linkage: the CEDA_Result.source.linkage.url.??? field
790        @param name: the CEDA_Result.source.linkage.name field
791        @param function: the CEDA_Result.source.function field
792    """
793    ceda_result = CEDA_Result()
794    on_line_resource = createMO_OnlineResource(linkage, name, function, description, applicationProfile)       
795    ceda_result.source.append(on_line_resource)
796    return ceda_result
797
798
799
800def createDQ_ConformanceResult(explanation, pass_, specification):
801    """
802        Creates a DQ_ConformanceResult instance
803        @param explanation: a String
804        @param pass_: a boolean value
805        @param specification: a CI_Citation instance 
806    """
807    dq_conformanceResult = DQ_ConformanceResult()
808    dq_conformanceResult.explanation = explanation
809    dq_conformanceResult.pass_ = pass_
810    dq_conformanceResult.specification = specification
811    return dq_conformanceResult
812
813def createDQ_Element(result):
814    """
815        Creates a DQ_Element instance
816        @param result: a DQ_Result array (mix 1, max 2 items)
817    """
818    dq_element = DQ_Element()
819    if result and (type(result) == list) and (len(result) >= 1 and len(result) <= 2):
820        dq_element.result = result
821    return dq_element
822
823def createEX_GeographicBoundingBox(east, north, west, south):
824    """
825        Creates an EX_GeographicBoundingBox instance
826        @param east: the eastBoundLongitude attribute as float
827        @param north: the northBoundLongitude attribute as float
828        @param west: the westBoundLongitude attribute as float
829        @param south: the southBoundLongitude attribute as float               
830    """
831    ex_geographic_bb = EX_GeographicBoundingBox()
832    ex_geographic_bb.eastBoundLongitude = east
833    ex_geographic_bb.northBoundLatitude = north
834    ex_geographic_bb.westBoundLongitude = west
835    ex_geographic_bb.southBoundLatitude = south
836    return ex_geographic_bb
837   
838def createCEDA_Processing():
839    ceda_processing = CEDA_Processing()
840    return ceda_processing
841
842
843def createCEDA_Instrument():
844    ceda_instrument = CEDA_Instrument()
845    return ceda_instrument
846
847def createCEDA_CompositeProcess():
848    ceda_cp = CEDA_CompositeProcess()
849    return ceda_cp
850
851def createCEDA_Acquisition():
852    ceda_acquisition = CEDA_Acquisition()
853    return ceda_acquisition
854
855def createCEDA_Project(abstract = None, publication_state = None, documentation = None, project_resource=None):
856    ceda_project = CEDA_Project()
857    if abstract:
858        ceda_project.abstract = abstract
859    if publication_state:
860        ceda_project.publicationState = publication_state       
861    if documentation and type(documentation) == list:
862        ceda_project.documentation = documentation
863    if project_resource and type(project_resource) == list:
864        ceda_project.projectResource = project_resource   
865    return ceda_project   
Note: See TracBrowser for help on using the repository browser.