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

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

Incomplete - # 22534: Add versiojn number to the gui page
 http://team.ceda.ac.uk/trac/ceda/ticket/22534
Corrects import mistakes

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