source: mauRepo/HPFos/trunk/hpfos/HPFos/osImpl/myimpl.py @ 8505

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/mauRepo/HPFos/trunk/hpfos/HPFos/osImpl/myimpl.py@8505
Revision 8505, 10.1 KB checked in by mnagni, 8 years ago (diff)

Incomplete - # 22540: The pagination links provided in the feed do not appear to be working correctly
 http://team.ceda.ac.uk/trac/ceda/ticket/22540

  • Property svn:mime-type set to text/plain
Line 
1'''
2BSD Licence
3Copyright (c) 2012, Science & Technology Facilities Council (STFC)
4All rights reserved.
5
6Redistribution and use in source and binary forms, with or without modification,
7are permitted provided that the following conditions are met:
8
9    * Redistributions of source code must retain the above copyright notice,
10        this list of conditions and the following disclaimer.
11    * Redistributions in binary form must reproduce the above copyright notice,
12        this list of conditions and the following disclaimer in the documentation
13        and/or other materials provided with the distribution.
14    * Neither the name of the Science & Technology Facilities Council (STFC)
15        nor the names of its contributors may be used to endorse or promote
16        products derived from this software without specific prior written permission.
17
18THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
20THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
22BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
23OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29Created on 5 May 2012
30
31@author: Maurizio Nagni
32'''
33from datetime import datetime
34from hpfos.libs.postgisutil import create_st_setSRID
35from ceda_markup.opensearch.osquery import OSQuery
36from ceda_markup.atom.atom import createID, createUpdated,\
37    createPublished, createEntry
38from ceda_markup.atom.info import createTitle, HTML_TYPE, createContent
39from ceda_markup.dc.dc import createDate
40from ceda_markup.gml.gml import createPosList, createLinearRing, createExterior,\
41    createPolygon
42from ceda_markup.georss.georss import createWhere
43from ceda_markup.atom.link import REL_SEARCH, REL_ALTERNATE
44from ceda_markup.opensearch import filter_results, COUNT_DEFAULT,\
45    START_INDEX_DEFAULT, START_PAGE_DEFAULT, create_autodiscovery_link
46from ceda_markup.opensearch.template.osresponse import Result, Subresult
47from ceda_markup.opensearch.template.atom import OSAtomResponse
48from ceda_markup.opensearch.template.html import OSHTMLResponse
49from ea_model.ceda_metadatamodel.ceda_observationcollection.ceda_observationcollection import CEDA_ObservationCollection
50from ea_model.ceda_metadatamodel.ceda_observation.ceda_observation import CEDA_Observation
51from ea_model.ceda_metadatamodel.ceda_result.ceda_result import CEDA_Result
52from ceda_markup.opensearch.os_param import OSParam
53
54GUID = 'guid'
55COLLECTION = 'collection'
56OBSERVATION = 'observation'
57RESULT = 'result'
58BBOX = 'bbox'
59DUMMY_GUID = 'dummy_guid'
60
61CEDA_TITLE = 'ceda_title'
62
63
64
65class MyOSAtomResponse(OSAtomResponse):
66    '''
67    classdocs
68    '''
69
70    def __init__(self):
71        #query_params = {"q": "searchTerms", "pw":"startPage"}
72        super(MyOSAtomResponse, self).__init__()
73       
74        '''
75        Constructor
76        '''
77
78    def _get_tot_results(self, results):
79        if results is None:
80            return 0
81       
82        if isinstance(results, list):
83            return len(results)
84       
85        return 1
86
87    def digest_search_results(self, results, context):
88        count, start_index, start_page = self._importCountAndPage(context)
89       
90        filtered = None
91        tot_results = 0
92       
93        if type(results) == CEDA_ObservationCollection:
94            filtered = filter_results(results.member, count, start_index, start_page)
95            tot_results = self._get_tot_results(results.member)
96        elif type(results) == CEDA_Observation:
97            #to be done
98            filtered = filter_results(results.result, count, start_index, start_page)
99            tot_results = self._get_tot_results(results.result)       
100        else:
101            filtered = filter_results(results, count, start_index, start_page)
102            tot_results = self._get_tot_results(results)
103             
104        if filtered is None:
105            return Result(count, start_index, start_page, tot_results, subresult = [])
106             
107        subresults = []
108        for result in filtered:
109            item = None
110            if type(result) != CEDA_Result:           
111                result_guid = context['moles3EPB'].retrieveGUIDFromInstance(result)
112                if result_guid is None:
113                    continue
114                ititle = self._extractTitle(result)
115                item = Subresult(result_guid.id, ititle, datetime.now().isoformat(), description = result.description)
116            else:   
117                item = Subresult(DUMMY_GUID, 'dummy_resultTitle', datetime.now().isoformat(), description = 'dummy_resultDescription')
118            subresults.append(item)
119       
120        return Result(count, start_index, start_page, tot_results, subresult = subresults)
121       
122    def generateEntryLinks(self, entry, atomroot, path, linkid = None):
123        entry.append(create_autodiscovery_link(atomroot, path, self.extension, linkid, None, rel = REL_ALTERNATE))
124        entry.append(create_autodiscovery_link(atomroot, path, self.extension, linkid, None, rel = REL_SEARCH))               
125
126    def generate_entries(self, atomroot, subresults, path):
127        entries = []
128       
129        for subresult in subresults:
130            #Here could loop over results
131            atomID = createID(path + subresult.id + '/' + self.extension, root = atomroot)
132            ititle = createTitle(root = atomroot, body = subresult.title, itype = HTML_TYPE)
133            atomContent = createContent(root = atomroot, body = subresult.description, itype = HTML_TYPE)
134            atomUpdated = createUpdated(subresult.updated, root = atomroot)
135            atomPublished = createPublished('TO_BE_DONE_2011-01-21T11:05:29.511Z', root = atomroot)           
136            entry = createEntry(atomID, ititle, atomUpdated,
137                                published=atomPublished,
138                                content=atomContent, root = atomroot)
139            #xmlentry = entry.buildElement()
140           
141            idate = createDate(root = atomroot,
142                               body = 'TO_BE_DONE_2002-10-18T08:07:37.387Z/2012-03-29T07:12:20.735Z')       
143            entry.append(idate)
144           
145            posList = createPosList(root = atomroot, body = '-90 -180 90 -180 90 180 -90 180 -90 -180', srsDimension = '2')
146            linearRing = createLinearRing(root = atomroot, body = posList)
147            exterior = createExterior(root = atomroot, body = linearRing)
148            polygon = createPolygon(root = atomroot, body = exterior)
149            where = createWhere(root = atomroot, body = polygon)
150            entry.append(where)
151            self.generateEntryLinks(entry, atomroot, path, subresult.id)           
152            entries.append(entry)
153
154        for entry in entries:
155            atomroot.append(entry)
156
157    def _importCountAndPage(self, context):       
158        count = COUNT_DEFAULT
159        start_index = START_INDEX_DEFAULT
160        start_page = START_PAGE_DEFAULT
161       
162        try:
163            count = int(context['count'])
164        except:
165            pass       
166       
167        try:
168            start_index = int(context['startIndex'])
169        except:
170            pass
171       
172        try:
173            start_page = int(context['startPage'])
174        except:
175            pass
176       
177        return count, start_index, start_page
178
179    def _extractTitle(self, cedaObj):
180        if hasattr(cedaObj, 'identifier'):
181            for ident in cedaObj.identifier:
182                if ident.authority.title == CEDA_TITLE:
183                    return ident.code 
184
185class MyOSHTMLResponse(OSHTMLResponse):
186    '''
187    classdocs
188    '''
189
190    def __init__(self):
191        '''
192        Constructor
193        '''
194        super(MyOSHTMLResponse, self).__init__()
195       
196    def generateResponse(self, result, queries, ospath, **kwargs):
197        return result + " HTML!"
198       
199class MyOSQuery(OSQuery):
200    '''
201    classdocs
202    '''
203
204    def __init__(self):
205        '''
206            Constructor
207        '''
208        #param_1 = OSParam("q", "searchTerms", namespace = "http://example.com/opensearchextensions/1.0/")       
209        param_1 = OSParam("count", "count")
210        param_2 = OSParam("startPage", "startPage")
211        param_3 = OSParam("startIndex", "startIndex")               
212        param_4 = OSParam("q", "searchTerms")           
213        param_5 = OSParam("uid", "uid", namespace = "http://a9.com/-/opensearch/extensions/geo/1.0/")       
214        param_6 = OSParam(BBOX, BBOX, namespace = "http://a9.com/-/opensearch/extensions/geo/1.0/")       
215        param_7 = OSParam("start", "start", namespace = "http://a9.com/-/opensearch/extensions/geo/1.0/")       
216        param_8 = OSParam("stop", "stop", namespace = "http://a9.com/-/opensearch/extensions/time/1.0/")       
217        params = [param_1, param_2, param_3, param_4, param_5, param_6, param_7, param_8]
218        super(MyOSQuery, self).__init__(params)
219       
220    def do_search(self, context):
221        ibbox = None
222        if context is not None and context.has_key(BBOX) and context[BBOX] is not None:
223            coords = context[BBOX].split(',')
224            try:
225                if len(coords) == 4:
226                    ibbox = create_st_setSRID(int(coords[0]),int(coords[1]),int(coords[2]),int(coords[3]))
227            except:
228                pass
229       
230        if not context.has_key(GUID) or context[GUID] is None:
231            return context['moles3EPB'].getObservationCollections(bbox = ibbox)       
232             
233        obj = context['moles3EPB'].getInstanceFromGUID(context[GUID])   
234        if obj is None:
235            return None
236        if type(obj) == CEDA_ObservationCollection:
237            return context['moles3EPB'].searchSelectiveLoadByInstance(obj, 'member') #need to add bbox & phenomTime
238        elif type(obj) == CEDA_Observation:
239            return context['moles3EPB'].searchSelectiveLoadByInstance(obj, 'result') #need to add bbox & phenomTime
Note: See TracBrowser for help on using the repository browser.