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

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

Improvements associated with ticket:733

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