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

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

Complete - # 22386: CEDA Observation - title
 http://team.ceda.ac.uk/trac/ceda/ticket/22386

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