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

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

Improvements in date and person handling.

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