source: TI07-MOLES/trunk/PythonCode/wsgi/stubB.py @ 2379

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI07-MOLES/trunk/PythonCode/wsgi/stubB.py@2379
Revision 2379, 8.9 KB checked in by lawrence, 12 years ago (diff)

Improved handling of deployments in browse.

Line 
1#!/usr/bin/env python
2#
3# This python code (will) handle all forms of stub-B and provide HTML
4# methods to the extent required by the NDG browse functionality
5# BNL April 2006
6#
7from renderEntity import renderEntity
8from Utilities import *
9from AccessControl import AccessControl
10from geoUtilities import Bounding
11from People import *
12from ndgObject import ndgObject
13from xmlHandler import xmlHandler
14try: #python 2.5
15    from xml.etree import ElementTree as ET
16except ImportError:
17    try:
18        # if you've installed it yourself it comes this way
19        import ElementTree as ET
20    except ImportError:
21        # if you've egged it this is the way it comes
22        from elementtree import ElementTree as ET
23
24def idconvert(helper,elem,config=None):
25    ''' Given an elementTree element for a dgMetadataID, create
26    a standard ndg URI, and produce an ndgObject '''
27    id=helper.find(elem,'dgMetadataID')
28    entryID='%s__%s__%s'%(helper.getText(id,'repositoryIdentifier'),
29                            helper.getText(id,'schemeIdentifier'),
30                            helper.getText(id,'localIdentifier'))
31    uri=ndgObject(entryID,config)
32    return uri
33
34class ndgLink:
35    ''' This is a holder for an ndgObject which has a name (and possibly abbreviation) '''
36    def __init__(self,name,abbrev,ndgO):
37        self.ndgObject=ndgO
38        self.name=name
39        self.abbrev=abbrev
40        self.image=None
41        self.URL=ndgO.URL
42    def toHTML(self):
43        ### needs to be finished
44        return self.ndgObject.URL
45
46class dataGranule:
47        ''' Provides support for data granule structures '''
48        def __init__(self,helper,elem,config,name=''):
49            self.elem=elem
50            self.constraints=AccessControl(helper.find(elem,'accessControlPolicy'))
51            self.name=name
52            self.uri=idconvert(helper,elem,config)
53            self.entryID=self.uri.uri
54
55class ObservationStation:
56    def __init__(self,e):
57        self.e=e
58        if e is None: return
59class DataProductionTool:
60    def __init__(self,e):
61        self.e=e
62        if e is None: return
63class Activity:
64    def __init__(self,e):
65        self.e=e
66        if e is None: return
67       
68class Deployment:
69    def __init__(self,helper,elem,others,config):
70        # not passing the config file, a deployment shouldn't be linkable in it's own right
71        n=idconvert(helper,elem) 
72        self.uri=n.uri
73        self.dateRange=(helper.getText(elem,'DateStart'),helper.getText(elem,'DateEnd'))
74        self.links={}
75        for o in others:
76            ids=helper.findall(elem,o)
77            if o not in self.links: self.links[o]=[]
78            for i in ids:
79                link=ndgLink(
80                     helper.getText(i,'name'),helper.getText(i,'abbreviation'),idconvert(helper,i,config))
81                self.links[o].append(link)
82       
83class DataEntity:
84    def __init__(self,helper,element):
85        ''' Attempt to instantiate this stubB as a data entity'''
86        self.elem=element
87        self.helper=helper
88        #just one curator
89        self.curator=dgContact(self.elem.find('dgDataRoles/dgDataCurator'),ctype='organisation')
90        #possibly multiple creators
91        self.creators=[dgContact(i) for i in self.elem.findall('dgDataRoles/dgDataCreator')]
92        host,service = '','' # dummy for now
93        #possibly multiple granules
94        self.getGranules()
95        #bounding box, handled as a class because this is going to be difficult ...
96        self.bbox=Bounding(self.elem,entity='stubB')
97        self.temporal()
98        #parameters
99        self.parameters=wrapGetText(self.elem,'dgDataSummary/dgParameterSummary/ParameterName',multiple=1)
100       
101    def getGranules(self):
102        ''' Load up the granule content within the entity '''
103        granList=self.elem.findall('dgDataGranule')
104        self.granules=[]
105        i=0
106        for item in granList:
107            i+=1
108            #following needs to be refactored when granule definition includes a proper name ...
109            name=wrapGetText(item,'name')
110            if name=='': name='Granule %s'%i
111            self.granules.append(dataGranule(self.helper,item,self.config,name=name))
112               
113    def temporal(self):
114        '''Instantiate the timeCoverage attribute by parsing for temporal coverage '''
115        t=self.elem.find('dgDataSummary/dgDataCoverage/dgTemporalCoverage/DateRange')
116        if t is not None:
117           try:
118                self.timeCoverage=(float(i.text) for i in t)
119           except:
120                self.timeCoverage=('',)
121                               
122        else:
123           t=self.elem.find('dgDataSummary/dgDataCoverage/dgTemporalCoverage/DateSingle')
124           try:
125                self.timeCoverage=(t.text,)
126           except:
127                self.timeCoverage=('',)
128
129class dgMetadataDescription:
130   
131    def __init__(self,helper,elem):
132        ''' Initialise a Metadata Description '''
133        n=idconvert(helper,elem)
134        self.uri=n.uri
135        self.abstract=helper.getText(elem,'abstract/abstractText')
136        self.description=helper.getText(elem,'descriptionSection/dgDescriptionText')
137        self.descriptionType=helper.getText(elem,'descriptionSection/contentType')
138        online=helper.findall(elem,'descriptionSection/descriptionOnlineReference/dgSimpleLink')
139        self.onlineRefs=[]
140        for o in online:
141            self.onlineRefs.append((helper.getText(o,'name'),helper.getText(o,'URI')))
142
143
144class stubB(DataEntity,Deployment,ObservationStation,DataProductionTool,Activity):
145       
146        ''' Holds the stub-b document and provides methods which get and manipulate it '''
147       
148        def __init__(self,xml,config):
149               
150                '''Instantiate by parsing an xml document passed in as a string '''
151               
152                self.metadataType='stubB'
153                self.services=[]
154                self.config=config
155               
156                self.labels={'activity':'Activity ','observationstation':'Observation Station ',
157                                        'dataproductiontool':'Data Production Tool ','dataEntity':'Data Entity ','dataentity':'Data Entity'}
158                try:
159                        self.xml=xml
160                        self.xh=xmlHandler(xml,string=1)
161                        self.tree=self.xh.tree
162                        helper=nsdumb(self.tree)
163                        self.name=helper.getText(self.tree,'name')
164                except Exception,e:
165                        raise ValueError('Error instantiating stubB [%s]'%e)
166               
167
168                self.ndgObject=idconvert(helper,self.tree,self.config)
169                self.entryID=self.ndgObject.uri
170               
171                #Note that the root of the ElementTree instance is dgMetadataRecord
172                #so we don't need (or want) that in our xpath expressions.
173               
174                self.constraints=AccessControl(helper.find(self.tree,'dgMetadataSecurity'))
175                self.abbreviation=helper.getText(self.tree,'abbreviation')
176                if self.abbreviation=='': self.abbreviation=self.name[0:min(15,len(self.name))]
177               
178                for i in ('dgDataEntity','dgActivity','dgDataProductionTool','dgObservationStation'):
179                    elem=helper.find(self.tree,i)
180                    if elem is not None: break
181                   
182                if elem is None:
183                    raise ValueError('StubB record does not contain an Activity, DE, DPT, ObsStn')
184                elif elem.tag=='dgDataEntity':
185                        DataEntity.__init__(self,helper,elem)
186                        self.type='dgDataEntity'
187                        self.others=('activity','observationstation','dataproductiontool')
188                        related='RelatedDeployment'
189                elif elem.tag=='dgActivity':
190                        self.type='dgActivity'
191                        #nb activity stub-b seems to have dataentity instead of dataEntity
192                        self.others=('dataentity','dataEntity','observationstation','dataproductiontool')
193                        related='ActivityDeployment'
194                elif elem.tag=='dgDataProductionTool':
195                        self.type='dgDataProductionTool'
196                        self.others=('dataEntity','observationstation','activity')
197                        related='DPTDeployment'
198                elif elem.tag=='dgObservationStation':
199                        related='ObsStnDeployment'
200                        self.type='dgObservationStation'
201                        self.others=('dataEntity','dataproductiontool','activity')
202
203                self.description=dgMetadataDescription(helper,helper.find(self.tree,'dgMetadataDescription'))
204                self.abstract=self.description.abstract
205             
206                # now go get all the related links
207                self.related=[]
208                for d in helper.findall(elem,related):
209                    self.related.append(Deployment(helper,d,self.others,self.config))
210
211        def toHTML(self,config):
212            if self.tree is not None:
213                renderer=renderEntity(config)
214                return renderer.render(self)
215            else:
216                return '<p>No Valid Stub-B</p>'
217           
218       
219if __name__=="__main__":
220       
221        #xml=open("../../exampleB/methyl.example.xml",'r').read()
222        xml=open('examples/badc.nerc.ac.uk__NDG-B1__dataent_chablis.xml','r').read()
223        config=myConfig('ndgDiscovery.config')
224        x=stubB(xml,config)
225        y='''<?xml version="1.0" encoding="UTF-8"?>
226                <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
227                <html xmlsns="http://www.w3.org/1999/xhtml" xml:lang="en">
228                        <head>
229                                <META http-equiv="Content-Type" content="text/xhtml; charset=iso-8859-1"/>
230                                <title>stubB</title>
231                                <LINK media="all, screen" href="../layout/style.css" type="text/css" rel="stylesheet"/>
232                        </head> '''+x.toHTML(config)
233        f=file('output.html','w')
234        f.write(y)
Note: See TracBrowser for help on using the repository browser.