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

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

Some more browse improvements. Handling dgMetadataDescription.
Better Linking.

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