source: mauRepo/MolesManager/trunk/src/libs/migration/processor/deployment.py @ 8263

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/mauRepo/MolesManager/trunk/src/libs/migration/processor/deployment.py@8263
Revision 8263, 30.3 KB checked in by mnagni, 8 years ago (diff)
Line 
1'''
2Created on 15 Nov 2011
3
4@author: mnagni
5'''
6from libs.migration.processor.commons import findMolesLineage,\
7    createMO_ResponsiblePartyInfo,\
8    DO_BADC, DO_NEODC, findAuthorsInResource, CEDA,\
9    createMD_Identifier, extractSummary, extractQuality, \
10    hasAtomDocumentSameHash, getAtomDocumentHashByMO, extractTitle,\
11        createCEDA_Result,\
12    createEX_GeographicBoundingBox, extractGeographicExtentInMigrationDocument, findDownloadLinksInMigrationDocument,\
13    findDOIInMigrationDocument, extractContent, createCI_Citation, createCI_Date, createDate,\
14    createTM_Position, createTM_Instant, extractMolesCreationDate,\
15    createDateTime, isoDateTimeStringToTimeDate, extractMolesProviderID,\
16    DO_UKSSDC, createMO_Organization,\
17    createCI_Contact, createCI_Address, createCI_OnlineResource,\
18    createCI_Telephone, extractMolesTemporalRange, isoDateStringToTimeDate,\
19    createTM_Period, createCI_Individual, findAccessLinksInMigrationDocument,\
20    findLinksInDeployment, createMD_LegalConstraints,\
21    createDQ_Element, createDQ_ConformanceResult, findUpdatedDate,\
22    createMD_Metadata, createMO_OnlineResource, createCEDA_Review, calculateHash,\
23    createCI_ResponsibleParty, extractUpdateFrequency,\
24    findLinksInMigrationDocument, findSubTypeInDPT
25from ea_model.moles3_4.utilities.mo_rolevalue import MO_RoleValue
26from ea_model.ceda_metadatamodel.ceda_observation.ceda_observation import CEDA_Observation
27from libs.migration.MigrationEPB import MigrationEPB
28from libs.epb import EPB
29from libs.migration.processor.deployment_data import DeploymentDataProcessor
30from ea_model.moles3_4.utilities.mo_publicationstatevalue import MO_PublicationStateValue
31from libs.migration.exception.exceptions import NoDataLineage,\
32    NoAssociatedAuthor
33from MolesManager.moles3epb import Moles3EPB
34from libs.migration.authors import authors
35from logging import StreamHandler
36import logging
37from datetime import date
38from ea_model.iso_19115_2006_metadata_corrigendum.citation_and_responsible_party_information.ci_onlinefunctioncode import CI_OnLineFunctionCode
39from ea_model.iso_19115_2006_metadata_corrigendum.citation_and_responsible_party_information.ci_datetypecode import CI_DateTypeCode
40from ea_model.iso_19115_2006_metadata_corrigendum.constraint_information.md_restrictioncode import MD_RestrictionCode
41from copy import deepcopy
42import datetime
43from libs.migration.InfodbEPB import InfodbEPB
44from ea_model.ceda_metadatamodel.ceda_result import ceda_curationvalue
45from ea_model.ceda_metadatamodel.ceda_utilities.ceda_reviewfrequencyvalue import CEDA_ReviewFrequencyValue
46from ea_model.ceda_metadatamodel.ceda_utilities.ceda_reviewstatusvalue import CEDA_ReviewStatusValue
47from MolesManager.ceda_guid import CedaGUID
48from ea_model.iso_19115_2006_metadata_corrigendum.citation_and_responsible_party_information.ci_rolecode import CI_RoleCode
49from ea_model.iso_19115_2006_metadata_corrigendum.maintenance_information.md_maintenancefrequencycode import MD_MaintenanceFrequencyCode
50from ea_model.ceda_metadatamodel.ceda_result.ceda_curationvalue import CEDA_CurationValue
51
52class DeploymentProcessor(object):
53    '''
54        Migrates a deployment element in a CEDA_Observation entity
55    '''
56    publisherName = 'CEDA'
57   
58    log = logging.getLogger('DeploymentProcessor')
59    log.addHandler(StreamHandler())
60    log.setLevel(logging.DEBUG)   
61    def __init__(self, dataEntityMigration, deploymentMigration, migrationSessions):
62        '''
63            Initializes the class
64            @param dataEntityMigration: a DataEntityMigration instance
65            @param deploymentMigration: the DeploymentMigration instance
66            @param migrationSessions: a MigrationSessions instance   
67        '''             
68        self._dataEntityMigration = dataEntityMigration
69        self._deploymentMigration = deploymentMigration
70        self._dataEntityHasSameHash = hasAtomDocumentSameHash(self._dataEntityMigration) and self._dataEntityMigration.doc_hash is not None
71        self._deploymentHasSameHash = hasAtomDocumentSameHash(self._deploymentMigration) and self._deploymentMigration.doc_hash is not None
72       
73        self._migrationSessions = migrationSessions
74
75    def _existsCEDAasPublisher(self):
76        for rp in self._ceda_observation.relatedParty:
77            if rp.role == MO_RoleValue.cl_publisher:
78                for party in rp.parties:
79                    if party.name == DeploymentProcessor.publisherName:
80                        return True
81        return False
82
83    """                   
84    def _extractResponsiblePartyInfo(self, authors = None, parsedParties = []):
85        '''
86            @param authors: the deployment's authors
87            @param parsedParties: a list to fill with the created MO_ResponsiblePartyInfos
88        '''
89        #First is assumend to be the author
90        i_party = createMO_Organization(name = authors[:1])
91        parsedParties.append(createMO_ResponsiblePartyInfo(MO_RoleValue.cl_author, [i_party]))
92        i_party = []
93        if len(authors) < 2:
94            return
95       
96        for i_name in authors[:1]:
97            i_party.append(createMO_Organization(name = i_name))           
98        parsedParties.append(createMO_ResponsiblePartyInfo(MO_RoleValue.cl_coinvestigator, i_party))           
99    """
100
101    def _addResponsiblePartyInfo(self, oldResponsiblePartyInfos, newResponsiblePartyInfo):
102        opi = None
103        for oldPartyInfo in oldResponsiblePartyInfos:
104            if oldPartyInfo.role == newResponsiblePartyInfo.role:
105                opi = oldPartyInfo
106                break
107           
108        if len(oldResponsiblePartyInfos) == 0 or opi is None:
109            oldResponsiblePartyInfos.append(newResponsiblePartyInfo)
110       
111        if opi is not None: 
112            for np in newResponsiblePartyInfo.party:
113                opi.party.append(np)
114
115    def _appendResponsibleParty(self, observation, names, creation_function, role):
116        for nm in names:
117            i_party = creation_function(name = nm)
118            observation.relatedParty.append(createMO_ResponsiblePartyInfo(role, [i_party]))       
119
120    def _assignName(self, observation):       
121        '''
122            @param relatedPartyInfos: a MO_ResponsiblePartyInfo list
123            @return True if the documents changed, False otherwise
124        '''
125        whereAreAuthors = self._deploymentMigration       
126        doc_authors = findAuthorsInResource(self._deploymentMigration)       
127        if doc_authors['authors'] in [DO_BADC, DO_NEODC]:
128            doc_authors = findAuthorsInResource(self._dataEntityMigration)
129            whereAreAuthors = self._dataEntityMigration
130
131        i_party = createMO_Organization(name = CEDA)
132        observation.relatedParty.append(createMO_ResponsiblePartyInfo(MO_RoleValue.cl_curator, [i_party]))                               
133       
134        if authors.has_key(doc_authors['authors']):
135            tmp_auth = authors[doc_authors['authors']]
136            ret = self._extractIndividualsAndOrganizations(tmp_auth, whereAreAuthors)
137            if len(ret['ind']) > 0:
138                self._appendResponsibleParty(observation, ret['ind'], createCI_Individual, MO_RoleValue.cl_author)               
139            if len(ret['org']) > 0:
140                self._appendResponsibleParty(observation, ret['org'], createMO_Organization, MO_RoleValue.cl_author)                               
141            if len(ret['co_ind']) > 0:
142                self._appendResponsibleParty(observation, ret['co_ind'], createCI_Individual, MO_RoleValue.cl_coinvestigator)               
143            if len(ret['co_org']) > 0:
144                self._appendResponsibleParty(observation, ret['co_org'], createMO_Organization, MO_RoleValue.cl_coinvestigator)                                                                                         
145        else:
146            raise NoAssociatedAuthor(doc_authors['authors'], migrationObject = whereAreAuthors)
147       
148        if doc_authors['contributors'] is None:
149            return
150       
151        if authors.has_key(doc_authors['contributors']):
152            tmp_auth = authors[doc_authors['contributors']]           
153            ret = self._extractIndividualsAndOrganizations(tmp_auth, whereAreAuthors)
154            if len(ret['ind']) > 0:
155                self._appendResponsibleParty(observation, ret['ind'], createCI_Individual, MO_RoleValue.cl_coinvestigator)
156            if len(ret['org']) > 0:
157                self._appendResponsibleParty(observation, ret['org'], createMO_Organization, MO_RoleValue.cl_coinvestigator)               
158            if len(ret['co_ind']) > 0:
159                self._appendResponsibleParty(observation, ret['co_ind'], createCI_Individual, MO_RoleValue.cl_coinvestigator)               
160            if len(ret['co_org']) > 0:
161                self._appendResponsibleParty(observation, ret['co_org'], createMO_Organization, MO_RoleValue.cl_coinvestigator)                                                       
162        else:
163            raise NoAssociatedAuthor(doc_authors['contributors'], migrationObject = whereAreAuthors)
164
165
166    def _extractIndividualsAndOrganizations(self, tmp_auth, whereAreAuthors):
167        if whereAreAuthors is None:
168            raise Exception("migrationObject is None")
169        try:
170            ret = {'ind': [], 'org': [], 'co_ind': [], 'co_org': []}
171            if tmp_auth['type'] == 'ind':
172                ret['ind'].append(tmp_auth['author'])
173            elif tmp_auth['type'] == 'org':
174                ret['org'].append(tmp_auth['author'])
175           
176            if tmp_auth['author'] == 'unknown':
177                DeploymentProcessor.log.info("%s %s %s has unknown author" \
178                                             % (whereAreAuthors.doc_status, whereAreAuthors.doc_owner, whereAreAuthors.doc_name))       
179                 
180            for item in tmp_auth['co_author_type']:
181                if item == 'ind':
182                    ret['ind'].append(tmp_auth['co_author'][tmp_auth['co_author_type'].index(item)])
183                elif item == 'org':
184                    ret['org'].append(tmp_auth['co_author'][tmp_auth['co_author_type'].index(item)])
185           
186                if (tmp_auth['co_author'][tmp_auth['co_author_type'].index(item)] == 'unknown'):
187                    DeploymentProcessor.log.info("%s %s %s has unknown author" \
188                                                 % (whereAreAuthors.doc_status, whereAreAuthors.doc_owner, whereAreAuthors.doc_name))
189        except Exception as e:
190            print e
191        return ret
192
193    def _assignLineage(self, observation):
194        data_lineage = findMolesLineage(self._dataEntityMigration)
195        if data_lineage is None:
196            raise NoDataLineage(self._dataEntityMigration)
197        Moles3EPB.addDataLineageToObservation(data_lineage, observation, self._migrationSessions.molesSession)       
198       
199    def _assignTitle(self, observation):       
200        doc_title = extractTitle(self._deploymentMigration)
201        if doc_title is None:
202            doc_title = extractTitle(self._dataEntityMigration)
203       
204        if doc_title.startswith('deployment_') or doc_title.startswith('Deployment_'):
205            links = findLinksInMigrationDocument(self._deploymentMigration)
206            dptList = links['DPT']
207            if links.has_key('DPT'):
208                doc_title = 'Data from ' + dptList[0]['title']
209                if len(dptList) > 2:
210                    for dpt in dptList[1:-2]:
211                        doc_title += ', ' + dpt['title']
212                    if len(dptList) > 1:
213                        doc_title += ' and ' + dptList[-1]
214                                                       
215            links = findLinksInDeployment(self._deploymentMigration)
216            if links.has_key('OBS'):
217                obsList = []
218                for obs in links['OBS']:
219                    observationStation = MigrationEPB.getDeploymentDataMigrationByName(self._deploymentMigration, obs + \
220                                                                                   '.atom', self._migrationSessions.migrationSession)
221                    obsList.append((extractTitle(observationStation), findSubTypeInDPT(observationStation)))
222               
223                if obsList[0][1] in ['stationary platform' ,'moving platform', 'ship','aircraft','satellite','computer']:
224                    doc_title += ' on '
225                else : 
226                    doc_title += ' at '
227                    doc_title += obsList[0][0]
228                if len(obsList) > 2:
229                    for obs in obsList[1:-2]:
230                        doc_title += ', ' + obs[0]
231                    if len(obsList) > 1:
232                        doc_title += ' and ' + obsList[-1][0]
233           
234            if links.has_key('ACTIVITY'):             
235                for link in links['ACTIVITY']:
236                    activity = MigrationEPB.getDeploymentDataMigrationByName(self._deploymentMigration, link + '.atom', \
237                                                                             self._migrationSessions.migrationSession)                   
238     
239                    projSubType = findSubTypeInDPT(activity)
240                    doc_title += ' for the ' + extractTitle(activity)
241                    if projSubType[0:14] == 'dgActivityData':
242                        doc_title += ' ' + projSubType[14:]
243                    else :
244                        doc_title += ' ' + projSubType
245                                                       
246        else:             
247            if doc_title[0:10] != 'Data from' :
248                doc_title = "Data from " + doc_title           
249        auth = createCI_Citation(title = 'ceda_title')                 
250        identifier = createMD_Identifier(code = doc_title, authority = auth)
251        observation.identifier.append(identifier)
252
253    def _assignDescription(self, observation):
254        summary = extractSummary(self._deploymentMigration, self._dataEntityMigration)
255        Moles3EPB.addDescriptionToObservation(summary, observation, self._migrationSessions.molesSession)
256       
257    def _assignQuality(self, observation):
258        doc_quality = extractQuality(self._dataEntityMigration)
259        doc_date = findUpdatedDate(self._dataEntityMigration)
260        ci_dates = []           
261        if doc_date:
262            i_date = createDate(isoDateTimeStringToTimeDate(doc_date))               
263            ci_dates.append(createCI_Date(CI_DateTypeCode.cl_revision, date = i_date))           
264        else:
265            i_date = createDate(isoDateTimeStringToTimeDate(datetime.datetime.now()))
266            ci_dates.append(createCI_Date(CI_DateTypeCode.cl_creation, date = i_date))
267
268        i_specification = createCI_Citation(title = "CEDA Data Quality Statement", date=ci_dates)
269        i_dq_result = createDQ_ConformanceResult(doc_quality, True, i_specification)
270        i_quality_element = createDQ_Element(i_dq_result)       
271        observation.resultQuality.append(i_quality_element)
272       
273    def updateObservation(self):
274        ceda_observation = EPB.searchOrCreate(CEDA_Observation, self._migrationSessions.molesSession, \
275                                              self._deploymentMigration.ceda_observation_id)
276        return ceda_observation
277       
278
279    def _assignResult(self, observation):
280        # TDB - Check that if is an update or not!       
281        download = findDownloadLinksInMigrationDocument(self._deploymentMigration)
282        content = None
283        if len(download) == 0:
284            download = findDownloadLinksInMigrationDocument(self._dataEntityMigration)
285            content = extractContent(self._dataEntityMigration)
286        else:
287            content = extractContent(self._deploymentMigration) 
288        for dwn in download:
289            int_description = None
290            int_applicationProfile = None
291            if content.has_key('formats'):
292                #int_applicationProfile = content['formats']
293                pass
294            if dwn['href'].startswith('http://badc.nerc.ac.uk/browse') or dwn['href'].startswith('http://neodc.nerc.ac.uk/browse'):
295                int_description = "download directly from archive"   
296            i_source = createMO_OnlineResource(linkage = dwn['href'], name = dwn['title'], \
297                                                   function = CI_OnLineFunctionCode.cl_download, \
298                                                   description = int_description, applicationProfile = int_applicationProfile)
299           
300        dataentity_id = '%s__ATOM__%s' % (self._dataEntityMigration.doc_owner, self._dataEntityMigration.doc_name)
301        dataentity_id = dataentity_id.replace('.atom', '')           
302        infodb_de = InfodbEPB.getCedaInfoApp_dataentityByDE_ID(dataentity_id)
303        i_logical_path = '/dummy'
304        if infodb_de is None:
305            i_logical_path = dwn['href'][dwn['href'].index('/browse/') + 7:]
306       
307        if infodb_de and infodb_de.has_key('logical_path'):
308            i_logical_path = infodb_de['logical_path']
309       
310        i_category = ceda_curationvalue.CEDA_CurationValue.cl_a                           
311        if infodb_de and infodb_de.has_key('category'):
312            i_category = CEDA_CurationValue.from_string(infodb_de['category'].lower()) #self._getcurationcategory(infodb_de['category'])               
313        observation.result = createCEDA_Result(i_category, i_logical_path, source = [i_source])                               
314
315
316    def _assignGeographicExtent(self, observation):
317        # TDB - Check that if is an update or not!
318        ge = extractGeographicExtentInMigrationDocument(self._deploymentMigration)
319        if not ge:
320            ge = extractGeographicExtentInMigrationDocument(self._dataEntityMigration)
321        if ge:
322            observation.geographicExtent.append(createEX_GeographicBoundingBox(ge['east'], ge['north'], ge['west'], ge['south']))
323
324    def _assignCreationDate(self, observation):
325        # TDB - Check that if is an update or not!
326        creation_date = extractMolesCreationDate(self._deploymentMigration)
327        py_datetime = isoDateTimeStringToTimeDate(creation_date)
328        date_time = createDateTime(py_datetime)   
329        tm_position = createTM_Position(dateTime8601 = date_time)
330        observation.resultTime = createTM_Instant(tm_position)
331
332    def assignDOI(self, observation, doi):
333        if doi and doi.has_key('href'):
334            doi = doi['href'][4:]           
335            py_date = None
336            cited_responsible = createCI_ResponsibleParty(role=CI_RoleCode.cl_publisher, \
337                                                              organizationName='NERC - British Atmospheric Data Centre')
338            if doi == '10.5285/E8F43A51-0198-4323-A926-FE69225D57DD':
339                py_date = date(2011, 4, 1)
340            elif doi == '10.5285/78114093-E2BD-4601-8AE5-3551E62AEF2B':
341                py_date = date(2011, 11, 29)               
342            elif doi == '10.5285/DB8D8981-1A51-4D6E-81C0-CCED9B921390':
343                py_date = date(2012, 4, 16)
344            elif doi == '10.5285/639A3714-BC74-46A6-9026-64931F355E07':
345                py_date = date(2012, 4, 16)               
346               
347            if py_date:   
348                dt = createDate(py_date)
349                ci_date = createCI_Date(CI_DateTypeCode.cl_publication, date = dt)
350                i_authority = createCI_Citation("DOI", date = ci_date)
351                identifier = createMD_Identifier(code = doi, authority=i_authority)             
352                observation.identifier.append(identifier)                                     
353
354    def _assignPublisherCurator(self, observation):       
355        provider_id = extractMolesProviderID(self._deploymentMigration)
356        party = None
357        if provider_id == DO_BADC:
358            i_linkage = 'http://badc.rl.ac.uk'
359            i_onlineResources = createCI_OnlineResource(linkage = i_linkage, name = 'British Atmospheric Data Centre Website')
360            i_address = createCI_Address(deliveryPoint = ['British Atmospheric Data Centre, STFC Rutherford Appleton Laboratory'], \
361                                         electronicMailAddress=['badc@rl.ac.uk'], postalCode='OX11 0QX', country='UK', city='Harwell Oxford')                                   
362            i_phone = createCI_Telephone(voice=['+44(0)1235 446432'])                                   
363            contact = createCI_Contact(phone=i_phone, address=i_address, onlineResource=i_onlineResources)                       
364            party = createMO_Organization(name = "NERC - British Atmospheric Data Centre", contactInfo = [contact])
365        elif provider_id == DO_NEODC:
366            i_linkage = 'http://www.neodc.rl.ac.uk'
367            i_onlineResources = createCI_OnlineResource(linkage = i_linkage, name = 'NERC Earth Observation Data Centre website')
368            i_address = createCI_Address(deliveryPoint = ['NERC - Earth Observation Data Centre, STFC Rutherford Appleton Laboratory'], \
369                                         electronicMailAddress=['neodc@rl.ac.uk'], postalCode='OX11 0QX', country='UK', city='Harwell Oxford')                                   
370            i_phone = createCI_Telephone(voice=['+44(0)1235 446432'])                                 
371            contact = createCI_Contact(phone=i_phone, address=i_address, onlineResource=i_onlineResources)                       
372            party = createMO_Organization(name = 'NERC - British Atmospheric Data Centre', contactInfo = [contact])
373        elif provider_id == DO_UKSSDC:
374            i_linkage = 'http://www.ukssdc.rl.ac.uk'
375            i_onlineResources = createCI_OnlineResource(linkage = i_linkage, name = 'UK Solar System Data Centre website')
376            i_address = createCI_Address(deliveryPoint = ['UK Solar System Data Centre, STFC Rutherford Appleton Laboratory'], \
377                                         electronicMailAddress=['support@rl.ac.uk'], postalCode='OX11 0QX', country='UK', city='Harwell Oxford')                                   
378            i_phone = createCI_Telephone(voice=['+44(0)1235 445173'])                                 
379            contact = createCI_Contact(phone=i_phone, address=i_address, onlineResource=i_onlineResources)                       
380            party = createMO_Organization(name = 'NERC - UK Solar System Data Centre', contactInfo = [contact])
381       
382        if party:
383            observation.relatedParty.append(createMO_ResponsiblePartyInfo(MO_RoleValue.cl_publisher, [party]))
384            observation.relatedParty.append(createMO_ResponsiblePartyInfo(MO_RoleValue.cl_custodian, deepcopy([party])))
385            observation.relatedParty.append(createMO_ResponsiblePartyInfo(MO_RoleValue.cl_distributor, deepcopy([party])))
386            observation.relatedParty.append(createMO_ResponsiblePartyInfo(MO_RoleValue.cl_pointofcontact, deepcopy([party])))
387            observation.relatedParty.append(createMO_ResponsiblePartyInfo(MO_RoleValue.cl_metadataowner, deepcopy([party])))
388            observation.relatedParty.append(createMO_ResponsiblePartyInfo(MO_RoleValue.cl_curator, deepcopy([party])))                                                           
389
390    def _assignPhenomenonTime(self, observation):       
391        doc_phenomenon_time = extractMolesTemporalRange(self._deploymentMigration)
392       
393        if doc_phenomenon_time:
394            if '/' in doc_phenomenon_time:
395                period = doc_phenomenon_time.split('/')
396                begin_date = createDate(isoDateStringToTimeDate(period[0]))
397                begin_position = createTM_Position(date8601 = begin_date)
398                begin_tm_instant = createTM_Instant(begin_position)
399               
400                end_date = createDate(isoDateStringToTimeDate(period[1]))
401                end_position = createTM_Position(date8601 = end_date)
402                end_tm_instant = createTM_Instant(end_position)
403               
404                observation.phenomenonTime = createTM_Period(begin_tm_instant, end_tm_instant)
405            else:
406                observation.phenomenonTime = createTM_Position(date8601 = createDate(isoDateStringToTimeDate(doc_phenomenon_time)))         
407
408    def _assignPermission(self, observation):
409        access_link = findAccessLinksInMigrationDocument(self._deploymentMigration)
410        dwn_link = findDownloadLinksInMigrationDocument(self._deploymentMigration)
411        if len(access_link) == 0:
412            access_link = findAccessLinksInMigrationDocument(self._dataEntityMigration) 
413
414        i_accessConstraints = []
415        i_use_limitation = []
416       
417        if len(access_link) == 0:
418            if len(dwn_link) == 0:
419                dwn_link = findDownloadLinksInMigrationDocument(self._dataEntityMigration)
420                if dwn_link and len(dwn_link) == 1:               
421                    i_use_limitation.append("These data are open access and available through %s." % (dwn_link[0]['href']) )
422                    #i_accessConstraints.append(MD_RestrictionCode.cl_)
423                    observation.permission = createMD_LegalConstraints(useLimitation = i_use_limitation, accessConstrains = i_accessConstraints)
424        else:
425            if access_link and len(access_link) == 1:
426                i_use_limitation.append("Access to these data is restricted. To obtain access please apply for access at: %s" % (access_link[0]['href']))
427                i_accessConstraints.append(MD_RestrictionCode.cl_restricted)
428                observation.permission = createMD_LegalConstraints(useLimitation = i_use_limitation, accessConstrains = i_accessConstraints)               
429                                   
430        '''                               
431        contentDict = extractContent(self._deploymentMigration)
432        if not contentDict.has_key('access-restricted'):
433            contentDict = extractContent(self._dataEntityMigration)
434        '''
435           
436    def _assignMoles2Link(self, ceda_observation):
437        i_code = 'http://badc.nerc.ac.uk/view/%s__ATOM__%s' % (self._deploymentMigration.doc_owner, self._deploymentMigration.doc_name)
438        i_code = i_code.replace('.atom', '')
439        #i_code = buildExistDocPath(self._deploymentMigration.doc_status, DT_DEPLOYMENTS, self._deploymentMigration.doc_owner, self._deploymentMigration.doc_name)
440        i_authority = createCI_Citation('moles2url')
441        identifier = createMD_Identifier(code = i_code, authority = i_authority)
442        ceda_observation.identifier.append(identifier)
443   
444    def _assignLanguage(self, ceda_observation):
445        i_date_stamp = createDate(datetime.datetime.now())
446        #i_contact = createCI_Citation("", date = i_date_stamp)
447        i_contact = createCI_ResponsibleParty(CI_RoleCode.cl_user)
448        ceda_observation.metadata = createMD_Metadata(date_stamp=i_date_stamp, contact = [i_contact], language = "English")
449   
450    def _assignInternalReview(self, ceda_observation):
451        i_party = createCI_Individual(name = 'Graham Parton')
452        i_reviewer = createMO_ResponsiblePartyInfo(MO_RoleValue.cl_processor, [i_party])
453        ceda_observation.internalReview.append( \
454            createCEDA_Review(reviewer=i_reviewer, reviewFrequency=CEDA_ReviewFrequencyValue.cl_yearly, \
455                              reviewStatus=CEDA_ReviewStatusValue.cl_required))   
456   
457    def _assignUpdateFrequency(self, ceda_observation):
458        updateFrequency = extractUpdateFrequency(self._deploymentMigration)
459        if updateFrequency:
460            ceda_observation.resultAccumulation = MD_MaintenanceFrequencyCode.from_string(updateFrequency)
461   
462    def _create(self):
463        ceda_observation = CEDA_Observation()
464        ceda_observation.publicationState = MO_PublicationStateValue.cl_working
465        self._assignQuality(ceda_observation)
466        self._assignLineage(ceda_observation)
467        self._assignDescription(ceda_observation)
468        self._assignTitle(ceda_observation)
469        self._assignResult(ceda_observation)   
470        self._assignGeographicExtent(ceda_observation)   
471        #self._assignDOI(ceda_observation)       
472        self._assignCreationDate(ceda_observation)
473        self._assignPublisherCurator(ceda_observation)       
474        self._assignPhenomenonTime(ceda_observation)       
475        self._assignPermission(ceda_observation)       
476        self._assignMoles2Link(ceda_observation)
477        self._assignQuality(ceda_observation)               
478        self._assignInternalReview(ceda_observation)       
479        self._assignLanguage(ceda_observation)
480        self._assignUpdateFrequency(ceda_observation)   
481        self._assignName(ceda_observation)                           
482        Moles3EPB.addCedaObject(ceda_observation, self._migrationSessions.molesSession, True)
483       
484        MigrationEPB.associateObservationToDeployment(self._deploymentMigration, ceda_observation.id, self._migrationSessions.migrationSession, True)
485       
486        #Adds the CedaGUID       
487        ceda_guid = CedaGUID()
488        ceda_guid.id = calculateHash(self._deploymentMigration.depl_id)
489        ceda_guid.ceda_observation = ceda_observation.id
490        Moles3EPB.addCedaObject(ceda_guid, self._migrationSessions.molesSession, True)
491       
492        return ceda_observation
493
494    def _getObservation(self):
495        return EPB.search(CEDA_Observation, self._deploymentMigration.ceda_observation_id, self._migrationSessions.molesSession)
496           
497    def _update(self):
498        if hasAtomDocumentSameHash(self._deploymentMigration):
499            return self._getObservation()
500        else:
501            return self.updateObservation()
502       
503    def process(self):
504        ceda_observation = None
505        #Moles3 object exists...
506        if self._deploymentMigration.ceda_observation_id:
507            ceda_observation = self._update()
508        else:
509            #... does not exist so create it
510            ceda_observation = self._create()
511       
512        #process the CEDA_Observation.procedure
513        deploymentDataProcessor = DeploymentDataProcessor(self._deploymentMigration, self._migrationSessions)
514        links = findLinksInDeployment(self._deploymentMigration)
515        procedure = deploymentDataProcessor.createProcess(links)
516       
517        #Temporary commented because CEDA_Project.subProject is not correctly mapped to the DB
518        project = deploymentDataProcessor.createProject(links)       
519        if procedure:
520            ceda_observation.procedure = procedure
521           
522        if project:
523            ceda_observation.inSupportOf = project                 
524                   
525        if procedure or project:                       
526            self._migrationSessions.molesSession.commit()
527           
528        if not self._deploymentHasSameHash:
529            self._deploymentMigration.doc_hash = getAtomDocumentHashByMO(self._deploymentMigration)
530            self._commitMigration()
531             
532       
533        return ceda_observation
Note: See TracBrowser for help on using the repository browser.