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

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

Correct wsgi.
Add version number on the title

  • 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
53from hpfos import __version__
54
55GUID = 'guid'
56COLLECTION = 'collection'
57OBSERVATION = 'observation'
58RESULT = 'result'
59BBOX = 'bbox'
60DUMMY_GUID = 'dummy_guid'
61
62HPFos_TITLE = 'Discovery feed for Search Services (v. %s)' % (__version__)
63
64
65
66class MyOSAtomResponse(OSAtomResponse):
67    '''
68    classdocs
69    '''
70
71    def __init__(self):
72        #query_params = {"q": "searchTerms", "pw":"startPage"}
73        super(MyOSAtomResponse, self).__init__()
74       
75        '''
76        Constructor
77        '''
78
79    def _get_tot_results(self, results):
80        if results is None:
81            return 0
82       
83        if isinstance(results, list):
84            return len(results)
85       
86        return 1
87
88    def digest_search_results(self, results, context):
89        count, start_index, start_page = self._importCountAndPage(context)
90       
91        filtered = None
92        tot_results = 0
93       
94        if type(results) == CEDA_ObservationCollection:
95            filtered = filter_results(results.member, count, start_index, start_page)
96            tot_results = self._get_tot_results(results.member)
97        elif type(results) == CEDA_Observation:
98            #to be done
99            filtered = filter_results(results.result, count, start_index, start_page)
100            tot_results = self._get_tot_results(results.result)       
101        else:
102            filtered = filter_results(results, count, start_index, start_page)
103            tot_results = self._get_tot_results(results)
104             
105        if filtered is None:
106            return Result(count, start_index, start_page, tot_results, subresult = [])
107             
108        subresults = []
109        for result in filtered:
110            item = None
111            if type(result) != CEDA_Result:           
112                result_guid = context['moles3EPB'].retrieveGUIDFromInstance(result)
113                if result_guid is None:
114                    continue
115                ititle = self._extractTitle(result)
116                item = Subresult(result_guid.id, ititle, datetime.now().isoformat(), description = result.description)
117            else:   
118                item = Subresult(DUMMY_GUID, 'dummy_resultTitle', datetime.now().isoformat(), description = 'dummy_resultDescription')
119            subresults.append(item)
120       
121       
122        return Result(count, start_index, start_page, tot_results, subresult = subresults, title=HPFos_TITLE)
123       
124    def generateEntryLinks(self, entry, atomroot, path, linkid = None):
125        entry.append(create_autodiscovery_link(atomroot, path, self.extension, linkid, None, rel = REL_ALTERNATE))
126        entry.append(create_autodiscovery_link(atomroot, path, self.extension, linkid, None, rel = REL_SEARCH))               
127
128    def generate_entries(self, atomroot, subresults, path):
129        entries = []
130       
131        for subresult in subresults:
132            #Here could loop over results
133            atomID = createID(path + subresult.id + '/' + self.extension, root = atomroot)
134            ititle = createTitle(root = atomroot, body = subresult.title, itype = HTML_TYPE)
135            atomContent = createContent(root = atomroot, body = subresult.description, itype = HTML_TYPE)
136            atomUpdated = createUpdated(subresult.updated, root = atomroot)
137            atomPublished = createPublished('TO_BE_DONE_2011-01-21T11:05:29.511Z', root = atomroot)           
138            entry = createEntry(atomID, ititle, atomUpdated,
139                                published=atomPublished,
140                                content=atomContent, root = atomroot)
141            #xmlentry = entry.buildElement()
142           
143            idate = createDate(root = atomroot,
144                               body = 'TO_BE_DONE_2002-10-18T08:07:37.387Z/2012-03-29T07:12:20.735Z')       
145            entry.append(idate)
146           
147            posList = createPosList(root = atomroot, body = '-90 -180 90 -180 90 180 -90 180 -90 -180', srsDimension = '2')
148            linearRing = createLinearRing(root = atomroot, body = posList)
149            exterior = createExterior(root = atomroot, body = linearRing)
150            polygon = createPolygon(root = atomroot, body = exterior)
151            where = createWhere(root = atomroot, body = polygon)
152            entry.append(where)
153            self.generateEntryLinks(entry, atomroot, path, subresult.id)           
154            entries.append(entry)
155
156        for entry in entries:
157            atomroot.append(entry)
158
159    def _importCountAndPage(self, context):       
160        count = COUNT_DEFAULT
161        start_index = START_INDEX_DEFAULT
162        start_page = START_PAGE_DEFAULT
163       
164        try:
165            count = int(context['count'])
166        except:
167            pass       
168       
169        try:
170            start_index = int(context['startIndex'])
171        except:
172            pass
173       
174        try:
175            start_page = int(context['startPage'])
176        except:
177            pass
178       
179        return count, start_index, start_page
180
181    def _extractTitle(self, cedaObj):
182        if hasattr(cedaObj, 'identifier'):
183            for ident in cedaObj.identifier:
184                if ident.authority.title == HPFos_TITLE:
185                    return ident.code 
186
187class MyOSHTMLResponse(OSHTMLResponse):
188    '''
189    classdocs
190    '''
191
192    def __init__(self):
193        '''
194        Constructor
195        '''
196        super(MyOSHTMLResponse, self).__init__()
197       
198    def generateResponse(self, result, queries, ospath, **kwargs):
199        return result + " HTML!"
200       
201class MyOSQuery(OSQuery):
202    '''
203    classdocs
204    '''
205
206    def __init__(self):
207        '''
208            Constructor
209        '''
210        #param_1 = OSParam("q", "searchTerms", namespace = "http://example.com/opensearchextensions/1.0/")       
211        param_1 = OSParam("count", "count")
212        param_2 = OSParam("startPage", "startPage")
213        param_3 = OSParam("startIndex", "startIndex")               
214        param_4 = OSParam("q", "searchTerms")           
215        param_5 = OSParam("uid", "uid", namespace = "http://a9.com/-/opensearch/extensions/geo/1.0/")       
216        param_6 = OSParam(BBOX, BBOX, namespace = "http://a9.com/-/opensearch/extensions/geo/1.0/")       
217        param_7 = OSParam("start", "start", namespace = "http://a9.com/-/opensearch/extensions/geo/1.0/")       
218        param_8 = OSParam("stop", "stop", namespace = "http://a9.com/-/opensearch/extensions/time/1.0/")       
219        params = [param_1, param_2, param_3, param_4, param_5, param_6, param_7, param_8]
220        super(MyOSQuery, self).__init__(params)
221       
222    def do_search(self, context):
223        ibbox = None
224        if context is not None and context.has_key(BBOX) and context[BBOX] is not None:
225            coords = context[BBOX].split(',')
226            try:
227                if len(coords) == 4:
228                    ibbox = create_st_setSRID(int(coords[0]),int(coords[1]),int(coords[2]),int(coords[3]))
229            except:
230                pass
231       
232        if not context.has_key(GUID) or context[GUID] is None:
233            return context['moles3EPB'].getObservationCollections(bbox = ibbox)       
234             
235        obj = context['moles3EPB'].getInstanceFromGUID(context[GUID])   
236        if obj is None:
237            return None
238        if type(obj) == CEDA_ObservationCollection:
239            return context['moles3EPB'].searchSelectiveLoadByInstance(obj, 'member') #need to add bbox & phenomTime
240        elif type(obj) == CEDA_Observation:
241            return context['moles3EPB'].searchSelectiveLoadByInstance(obj, 'result') #need to add bbox & phenomTime
Note: See TracBrowser for help on using the repository browser.