source: TI07-MOLES/trunk/PythonCode/wsgi/renderDiscoverySet.py @ 2487

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

Modifications to support cut-down stub-b xquery.
Slight rearrangement of page positioning in discovery. (Needs CSS
support)

Line 
1from DiscoveryState import DiscoveryState
2from ndgSearch import ndgSearch
3from DIF import DIF
4from htmlUtilities import *
5from renderService import *
6debug=1
7
8def CalculateStride(start,stride,total):
9    ''' Work out the previous and next chunks, returns a list of lists, the first of which
10    is the start and offset of the next chunk, the second of which is the staft and offset
11    of the previous chunk '''
12    result=[]
13    defStride=10
14    if start+stride<total:
15        #there are more to look at
16        r=[start+stride,stride]
17        if r[0]+r[1]-1>total: r[1]=total+1-r[0]
18        result.append(r)
19    else:result.append([])
20    if start>1:
21        #there are previous records
22        b=max(stride,defStride)
23        r=[start-b,b]
24        if r[0]<1: r[0]=1
25        if r[1]>total: r[1]=total
26        result.append(r)
27    else: result.append([])
28    return result
29   
30def htmlStride(state):
31    ''' Given the previous and next list from CalculateStride, and the
32    current state class (which provides a method for the fundamental URL,
33    return a previous next piece of html '''
34    html='Results %s to %s of %s'%(state.offset,state.offset+state.stride-1,state.hits)
35    r=CalculateStride(state.offset,state.stride,state.hits)
36    if r[0]<>[]:
37        s1='Next %s'%r[0][1]
38        nexturl=state.geturl(offset=r[0][0],stride=r[0][1])
39        html+=', %s'%hyperlink(s1,nexturl)
40    if r[1]<>[]:
41        l1='Previous %s'%r[1][1]
42        lasturl=state.geturl(offset=r[1][0],stride=r[1][1])
43        html+=', %s'%hyperlink(l1,lasturl)
44    html+='.'
45    stml='Search for <span class="searchString">%s</span>.'%state.searchString
46    html='''<div class="stridePosition"><table width="100%%"><tbody>
47            <tr><td align="left">%s</td><td align="right">%s</td></tr></tbody></table></div>'''%(stml,html)
48    return html
49   
50       
51def renderDiscoverySet(difSet,state,config,summary=0,services=0,spatial=0,temporal=0,
52    linkto='NDG_B_SERVICE',selector=None):
53    '''Takes a set of xml DIFS from a discovery search (difSet) and renders a
54    list of responses as a table, with layout depending on a set of keywords:
55            summary (boolean) - show the abstract,
56            services (boolean) - show the service list,
57            spatial (boolean) - show the bounding box,
58            temporal (boolean) - show the date range,
59            linkto (string) - clicking on the select widget should add the url for
60                              this service to the selected list
61     Note that state is a DiscoveryState instance containing the sessionID from the search,
62     and the offset, stride, and total number of results ...selector is a class for adding
63     particular datasets to a selection dataset (and cookie).
64     '''
65           
66    #
67    # List of methods which deal with the actual row content ...
68    #   
69   
70    def row(rowList,bgcolor='rbgWhite'):
71        h='<tr class="%s">'%bgcolor
72        for item in rowList:
73            if type(item)==type((1,2)):
74                h+='<td colspan="%s">%s</td>'%(item[1],item[0])
75            else:h+='<td>%s</td>'%item
76        h+='</tr>'
77        return h#span(h,bgcolor)
78
79    def spatialBox(elem):
80        return elem.bbox.toHTMLbox()
81     
82    def temporalRange(elem):
83        return ''
84   
85    def serviceList(d):
86        ll=span(' Links: ','ndgem')
87        ndg=0
88        serviceRenderer=renderService(config)
89        if d.binding is not None: ll+=serviceRenderer.get(d.binding)[0]
90        for i in d.services: print i.url
91        for item in d.services:
92            ll+=', '
93            #s=0
94            if item.contentType == 'NDG_A_SERVICE': 
95                ndg+=1
96            elif item.contentType == 'NDG_B_SERVICE':
97                ndg+=1
98            print 'starting services',item.url
99            ll+=serviceRenderer.get(item)[0]
100            print 'finishing services',item.url
101        if ndg<2: ndg=0
102        return ndg,ll
103
104   
105    # ##################################
106    # Actual html production follows
107    # ##################################
108   
109    # depending on keyword options, provide column headings
110    #
111   
112    columns=['Dataset',]   
113    if spatial: columns.append('Location')
114    if temporal: 
115        #two columns for temporal but put a column header across both columns
116        header='''<table><tbody><tr><td colspan="2" align="center">Time&nbsp;Coverage</td></tr><tr>
117        <td align="center">Start</td><td align="center"> End</td></tr></tbody></table>'''
118        columns.append((header,2))
119    html='<table><tbody>'+row(columns,bgcolor="rbgBeige")
120   
121    # ok, now let's cycle through the hits
122    i=1
123    for item in difSet:
124        #print item.entryID
125        d=item # we used to do the diffing here ... but we don't anymore
126        bgc={1:'rbgWhite',-1:'rbgGrey'}[i]
127        i=-1*i
128        if debug: print 'Rendering ',d.entryID
129        if d.tree is None:
130            html+='<tr class="%s"><td colspan="%s"> Unparseable record </td></tr>'%(bgc,len(columns))
131        else:
132            ndg,slist=serviceList(d)
133            rlist=['',]
134            if summary:
135                if d.briefCitation <>'':
136                    rlist[0]='%s: %s'%(span('Citation','ndgem'),d.briefCitation)
137                else:
138                    rlist[0]='%s: %s'%(span('Title','ndgem'),abbreviate(d.name,60))
139                rlist[0]+='<br/>%s: %s'%(span('Summary','ndgem'),abbreviate(d.abstract,200))
140                if d.binding is not None: rlist[0]+=' '+hyperlink('(more)',d.binding.url)
141            rlist[0]+='<br/>%s: %s.'%(span('Repository','ndgem'),d.centre.url())
142            if not summary and d.binding is not None:
143                rlist[0]+=' '+hyperlink('(more)',d.binding.url)
144            if services:rlist[0]+=slist
145            if ndg and selector !=None: 
146                rlist[0]+=',&nbsp;'+selector.target(d.entryID,name=d.abbreviation)
147            if spatial: rlist.append(spatialBox(d))
148            if temporal: 
149                rlist.append(htmlTime(d.timeCoverage[0]))
150                rlist.append(htmlTime(d.timeCoverage[1]))
151            html+=row(rlist,bgcolor=bgc)
152        print 'Completed rendering ',d.entryID
153
154    html+='</tbody></table>'
155    html='<div class="ListOfResults">%s\n%s</div>'%(htmlStride(state),html)
156    return html
157
158import unittest
159
160class TestCase(unittest.TestCase):
161
162    def testStrideself(self):
163        ''' Test striding through a dataset '''
164        res=CalculateStride(1,10,15)
165        self.assertEqual([[11,5],[]],res)
166        res=CalculateStride(11,5,15)
167        self.assertEqual([[],[1,10]],res)
168        res=CalculateStride(11,10,50)
169        self.assertEqual([[21,10],[1,10]],res)
170 
171    def testHtmlStride(self):
172        ''' Test the html striding part '''
173        DummyEnviron={'QUERY_STRING':'start=10&howmany=10','HTTP_HOST':'example.ndg',
174                      'PATH_INFO':'/discovery','wsgi.url_scheme':'http','SERVER_PORT':'80'}
175        d=DiscoveryState('123','blah',DummyEnviron,12)
176        html=htmlStride(d)
177        print html
178       
179if __name__=="__main__":
180    unittest.main()
181             
Note: See TracBrowser for help on using the repository browser.