source: mauRepo/HPFos/trunk/src/HPFos/osImpl/myimpl.py @ 8353

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

Removed the whole migration folder (was from the cedaManager project)

  • Property svn:mime-type set to text/plain
RevLine 
[8346]1'''
2Created on 5 May 2012
3
4@author: kusanagi
5'''
6from xml.etree.ElementTree import tostring, ElementTree
7from xml.dom import minidom
8from markup.atom.atom import Atom
9from markup.opensearch.os_response import OpenSearchResponse
10from markup.opensearch.osParam import OSParam
11from markup.atom.link import Link
12from markup.opensearch.os_engine import get_mimetype
13from markup.atom.info import Title, Info, Content
14from markup.atom.entry import Entry
15from markup.dc.dc import Date
16from markup.gml.gml import PosList, LinearRing, Exterior, Polygon
17from markup.georss.georss import Where
18from markup.template.html import OSHTMLResponse
19from markup.template.atom import OSAtomResponse
20from datetime import datetime
21from markup.opensearch.osquery import OSQuery
22 
23COLLECTION = 'collection'
24OBSERVATION = 'observation'
25RESULT = 'result'
26
[8352]27def calculateStep(**kwargs):
28    step = 20
29    if kwargs['params_values'].has_key('count'):
30        step = int(kwargs['params_values']['count'])
31    return step
32
[8346]33class MyOSAtomResponse(OSAtomResponse):
34    '''
35    classdocs
36    '''
37
38    def __init__(self):
39        #query_params = {"q": "searchTerms", "pw":"startPage"}
40        super(MyOSAtomResponse, self).__init__()
41       
42        '''
43        Constructor
44        '''
45       
46                       
[8352]47    def generateResponse(self, result, queries, ospath, **kwargs):
[8346]48        """
49            @param result: a Result instance
50            @param queries:
51            @param ospath: 
52        """
53        id = ""
54        ospath = self.generateLinkHref(ospath, result.id, self.extension, rel = None)
55       
56        #Generates the ATOM document
57        atomdoc = Atom.createDocument(ospath + "atom", \
58                                      result.title, \
59                                      result.updated)
60       
61        #configuration level
62        #path = "http://mysite.com/"
[8352]63        step = calculateStep(**kwargs)
64        root = ElementTree(atomdoc).getroot()
[8346]65        #extracted from result parameter
[8352]66
[8346]67        #Generate feed's links
[8352]68        self.generateFeedLinks(root, ospath, None, result.totalResult, step)
[8346]69   
70       
71        #Inserts the OpenSearchResponse elements
[8352]72        osdoc = OpenSearchResponse(root)
73        os_totalResults = str(result.totalResult)
[8346]74        os_startIndex = str(0)
75        os_itemsPerPage = str(step)
[8352]76        osdoc.createDocument(totalResults = os_totalResults, startIndex = os_startIndex, itemsPerPage = os_itemsPerPage)
77        for query in queries:                       
78            root.append(query)
[8346]79
[8352]80        self.generateEntries(root, result.subresult, ospath)
[8346]81       
82        reparsed = minidom.parseString(tostring(atomdoc))
83        return reparsed.toprettyxml(indent="  ")
84
85    def generateFeedLinks(self, atomroot, path, linkid = None, total_results = None, step = 0):
86        self.appendAtomLink(atomroot, path, linkid, startIndex = None, rel = Link.REL_SEARCH)
87        self.appendAtomLink(atomroot, path, linkid, 0, Link.REL_SELF)
88        self.appendAtomLink(atomroot, path, linkid, 0, Link.REL_FIRST)
89       
90        if total_results > 2*step:
91            self.appendAtomLink(atomroot, path, linkid, step, Link.REL_NEXT)
92            self.appendAtomLink(atomroot, path, linkid, total_results - (total_results % step), Link.REL_LAST)
93        else:
94            if total_results > step:
95                self.appendAtomLink(atomroot, path, linkid, step, Link.REL_NEXT)                   
96                self.appendAtomLink(atomroot, path, linkid, step, Link.REL_LAST)
97            else:
98                self.appendAtomLink(atomroot, path, linkid, 0, Link.REL_NEXT)                   
99                self.appendAtomLink(atomroot, path, linkid, 0, Link.REL_LAST)                               
100       
101    def generateEntryLinks(self, atomroot, path, linkid = None):
102        self.appendAtomLink(atomroot, path, linkid, startIndex = None, rel = Link.REL_ALTERNATE)
103        self.appendAtomLink(atomroot, path, linkid, startIndex = None, rel = Link.REL_SEARCH)               
104               
105    def appendAtomLink(self, atomroot, path, linkid = None, startIndex = 0, rel = Link.REL_SELF):
106        href = self.generateLinkHref(path, linkid, startIndex, rel)
107        type = get_mimetype(self.extension)
108        if rel == Link.REL_SEARCH:
109            type = get_mimetype('opensearchdescription')           
110        link = Link(href, rel, type)                   
111        atomroot.append(link.buildElement())
112
113    def generateLinkHref(self, path, linkid, startIndex = None, rel = Link.REL_SELF):
114        """
115            @param path: the host URL
116            @param linkid: the search id
117            @param startIndex: the starting index
118            @param rel: a Link type identificator. If None returns a generic ID   
119        """
120        if rel == None:
121            if linkid:
122                return "%s/search/%s/" % (path, linkid)
123            else:
124                return "%s/search/" % (path)
125   
126        if rel == Link.REL_SEARCH:
127            if linkid:
128                return "%s%s/description" % (path, linkid)   
129            else:
130                return "%sdescription" % (path)
131       
132        if rel == Link.REL_ALTERNATE:
133            if linkid:
134                return "%s%s/%s" % (path, linkid, self.extension)
135            else:
136                return "%s%s" % (path, self.extension)
137   
138        if linkid:
139            return "%s%s/%s/?startIndex=%d" % (path, linkid, self.extension, startIndex)
140        else:
141            return "%s%s/?startIndex=%d" % (path, self.extension, startIndex)       
142
143    def generateEntries(self, atomroot, subresults, path):
144        entries = []
145       
146        for subresult in subresults:
147            #Here could loop over results
148            ititle = Title(Info.TEXT_TYPE, subresult.title)
149            icontent = Content(Info.HTML_TYPE, '<b> Search Feed  </b>  \
150                <ul> <li> Title: ASAR Image Mode source packets Level 0 (ASA_IM__0P) </li> \
151             The ASAR Image Mode source packets Level 0 data product offers Level 0 data for possible images processing on an other processing site. It includes some mandatory information for SAR processing. The Image Mode Level 0 product consists of time-ordered Annotated Instrument Source Packets (AISPs) collected while the instrument is in Image Mode. The echo samples contained in the AISPs are compressed to 4 bits/sample using Flexible Block Adaptive Quantisation (FBAQ). This is a high-rate, narrow swath mode so data is only acquired for partial orbit segments and may be from one of seven possible image swaths. The Level 0 product is produced systematically for all data acquired within this mode. This product provides a continuation of the ERS-SAR_RAW product.<li> Abstract: The ASAR Image Mode source packets Level 0 data product offers Level 0 data for possible images processing on an other processing site. It includes some mandatory information for SAR processing. The Image Mode Level 0 product consists of time-ordered Annotated Instrument Source Packets (AISPs) collected while the instrument is in Image Mode. The echo samples contained in the AISPs are compressed to 4 bits/sample using Flexible Block Adaptive Quantisation (FBAQ). This is a high-rate, narrow swath mode so data is only acquired for partial orbit segments and may be from one of seven possible image swaths. The Level 0 product is produced systematically for all data acquired within this mode. This product provides a continuation of the ERS-SAR_RAW product. </li><li> Subject: Radar Imagery, Solid Earth (Tectonics/Seismic Activity), Water (Water Management), Natural Disasters (Oil Slick), Land (Topography/Mapping,Soil,Vegetation) Ocean and Coast (Ocean Currents and Topography,Ocean Waves,Coastal Geomorphology) </li>  \
152               <li> Date: 2002-10-18 to 2012-03-29  \
153                </li> <li> Number of Records: 15945 </ul>')
154            entry = Entry(path + subresult.id + '/' + self.extension, \
155                          ititle.buildElement(), \
156                          subresult.updated, \
157                          published = '2011-01-21T11:05:29.511Z', \
158                           link = [], \
159                           content = icontent.buildElement())
160            xmlentry = entry.buildElement()
161           
162            idate = Date(atomroot, '2002-10-18T08:07:37.387Z/2012-03-29T07:12:20.735Z')       
163            xmlentry.append(idate.buildElement())
164           
165            posList = PosList(atomroot, body = '-90 -180 90 -180 90 180 -90 180 -90 -180', srsDimension = '2')
166            linearRing = LinearRing(atomroot, posList)
167            exterior = Exterior(atomroot, linearRing)
168            polygon = Polygon(atomroot, exterior)
169            where = Where(atomroot, polygon)
170            xmlentry.append(where.buildElement())
171            self.generateEntryLinks(xmlentry, path, subresult.id)
172           
173            entries.append(xmlentry)
174
[8352]175        for entry in entries:
176            atomroot.append(entry)
[8346]177
178class MyOSHTMLResponse(OSHTMLResponse):
179    '''
180    classdocs
181    '''
182
183    def __init__(self):
184        '''
185        Constructor
186        '''
187        super(MyOSHTMLResponse, self).__init__()
188       
[8352]189    def generateResponse(self, result, queries, ospath, **kwargs):
[8346]190        return result + " HTML!"
191       
192class MyOSQuery(OSQuery):
193    '''
194    classdocs
195    '''
196
197    def __init__(self):
198        '''
199            Constructor
200        '''
201        #param_1 = OSParam("q", "searchTerms", namespace = "http://example.com/opensearchextensions/1.0/")       
202        param_1 = OSParam("count", "count")
203        param_2 = OSParam("startPage", "startPage")
204        param_3 = OSParam("startIndex", "startIndex")               
205        param_4 = OSParam("q", "searchTerms")           
206        param_5 = OSParam("uid", "uid", namespace = "http://a9.com/-/opensearch/extensions/geo/1.0/")       
207        param_6 = OSParam("box", "box", namespace = "http://a9.com/-/opensearch/extensions/geo/1.0/")       
208        param_7 = OSParam("start", "start", namespace = "http://a9.com/-/opensearch/extensions/geo/1.0/")       
209        param_8 = OSParam("stop", "stop", namespace = "http://a9.com/-/opensearch/extensions/time/1.0/")       
210        params = [param_1, param_2, param_3, param_4, param_5, param_6, param_7, param_8]
211        super(MyOSQuery, self).__init__(params)
[8352]212
213    def _packResult(self, results, id = None, **kwargs):
214        subresults = []
215
216        step = calculateStep(**kwargs)
217
218        startIndex = self.indexOffset
219        if kwargs['params_values'].has_key('startIndex'):
220            if int(kwargs['params_values']['startIndex']) < len(results):
221                startIndex = int(kwargs['params_values']['startIndex'])
[8346]222       
[8352]223        startPage = self.pageOffset
224        if kwargs['params_values'].has_key('startPage'):
225            if int(kwargs['params_values']['startPage']) * step < len(results):
226                startPage = int(kwargs['params_values']['startPage'])
227               
228        firstResult = startIndex
229        lastResult = firstResult + step
230
[8353]231        if startPage > 1 and (firstResult + (startPage - 1)*step) <= len(results):
232            firstResult = firstResult + (startPage - 1)*step
[8352]233            if firstResult + step <= len(results):           
234                lastResult = firstResult + step
235            else:
236                lastResult = len(results)
237
238        for result in results[firstResult:lastResult]:
239            result_guid = kwargs['moles3EPB'].retrieveGUIDFromInstance(result)
240            item = Subresult(result_guid.id, "title", datetime.now().isoformat())
241            subresults.append(item)
242       
243        return Result(len(results), subresult = subresults)
244       
245       
[8346]246    def doSearch(self, **kwargs):
[8347]247        if kwargs['params_values'] and kwargs['params_values'].has_key(COLLECTION) and kwargs['params_values'].has_key(OBSERVATION):
[8346]248            return self.searchObservation(**kwargs)       
249       
[8347]250        if kwargs['params_values'] and kwargs['params_values'].has_key(COLLECTION):
[8346]251            return self.searchCollection(**kwargs)       
252           
253        results = kwargs['moles3EPB'].getObservationCollections()
[8352]254        return self._packResult(results, **kwargs)
[8346]255
256    def searchCollection(self, **kwargs):       
257        obs_coll = kwargs['moles3EPB'].getInstanceFromGUID(kwargs['params_values'][COLLECTION])
258        if obs_coll:
259            obs_coll = kwargs['moles3EPB'].searchSelectiveLoadByInstance(obs_coll, 'member')
260                       
[8352]261        return self._packResult(obs_coll.member, id = kwargs['params_values'][COLLECTION], **kwargs)
[8346]262
263    def searchObservation(self, **kwargs):       
264        observation = kwargs['moles3EPB'].getInstanceFromGUID(kwargs['params_values'][OBSERVATION])
265        if observation:
266            observation = kwargs['moles3EPB'].searchSelectiveLoadByInstance(observation, 'result')
267           
268        print observation
269        '''                       
270        subresults = []
271        for result in obs_coll.member:
272            result_guid = kwargs['moles3EPB'].retrieveGUIDFromInstance(result)
273            item = Subresult(result_guid.id, "title", datetime.now().isoformat())
274            subresults.append(item)
275           
276        result = Result(id = kwargs['params_values'][COLLECTION], subresult = subresults)
277        return result
278        '''
279        return None
280
281class Result(object):
[8352]282    def __init__(self, totalResults, id = None, title = "Discovery feed for Search Services", updated = datetime.now().isoformat(), subresult = []):
[8346]283        '''
284            Constructor
285            @param id: a unique identifier, eventually an URI
286            @param title: an atom.Entry instance
287            @param updated: the last time the record was updated
288            @param subresult: a Subresults array                       
289        '''
[8352]290        self.totalResult = totalResults
[8346]291        self.id = id
292        self.title = title
293        self.updated = updated
294        self.subresult = subresult       
295       
296
297class Subresult(object):
298    def __init__(self, id, title, updated):
299        '''
300            Constructor
301            @param id: a unique identifier, eventually an URI
302            @param title: an atom.Entry instance
303            @param updated: the last time the record was updated                       
304        '''
305        self.id = id
306        self.title = title
307        self.updated = updated
Note: See TracBrowser for help on using the repository browser.