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

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/mauRepo/HPFos/trunk/src/HPFos/HPFos/osImpl/myimpl.py@8347
Revision 8347, 13.5 KB checked in by mnagni, 7 years ago (diff)
  • Property svn:mime-type set to text/plain
Line 
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
27class MyOSAtomResponse(OSAtomResponse):
28    '''
29    classdocs
30    '''
31
32    def __init__(self):
33        #query_params = {"q": "searchTerms", "pw":"startPage"}
34        super(MyOSAtomResponse, self).__init__()
35       
36        '''
37        Constructor
38        '''
39       
40                       
41    def generateResponse(self, result, queries, ospath):
42        """
43            @param result: a Result instance
44            @param queries:
45            @param ospath: 
46        """
47        id = ""
48        ospath = self.generateLinkHref(ospath, result.id, self.extension, rel = None)
49       
50        #Generates the ATOM document
51        atomdoc = Atom.createDocument(ospath + "atom", \
52                                      result.title, \
53                                      result.updated)
54       
55        #configuration level
56        #path = "http://mysite.com/"
57        step = 20
58       
59        #extracted from result parameter
60        linkid = result.id
61        total_result = len(result.subresult)
62        #Generate feed's links
63        self.generateFeedLinks(ElementTree(atomdoc).getroot(), ospath, None, total_result, step)
64   
65       
66        #Inserts the OpenSearchResponse elements
67        osdoc = OpenSearchResponse(ElementTree(atomdoc).getroot())
68        os_totalResults = str(total_result)
69        os_startIndex = str(0)
70        os_itemsPerPage = str(step)
71        osdoc.createDocument(totalResults = os_totalResults, startIndex = os_startIndex, itemsPerPage = os_itemsPerPage)                     
72        ElementTree(atomdoc).getroot().extend(queries)
73
74        self.generateEntries(ElementTree(atomdoc).getroot(), result.subresult, ospath)
75       
76        reparsed = minidom.parseString(tostring(atomdoc))
77        return reparsed.toprettyxml(indent="  ")
78
79    def generateFeedLinks(self, atomroot, path, linkid = None, total_results = None, step = 0):
80        self.appendAtomLink(atomroot, path, linkid, startIndex = None, rel = Link.REL_SEARCH)
81        self.appendAtomLink(atomroot, path, linkid, 0, Link.REL_SELF)
82        self.appendAtomLink(atomroot, path, linkid, 0, Link.REL_FIRST)
83       
84        if total_results > 2*step:
85            self.appendAtomLink(atomroot, path, linkid, step, Link.REL_NEXT)
86            self.appendAtomLink(atomroot, path, linkid, total_results - (total_results % step), Link.REL_LAST)
87        else:
88            if total_results > step:
89                self.appendAtomLink(atomroot, path, linkid, step, Link.REL_NEXT)                   
90                self.appendAtomLink(atomroot, path, linkid, step, Link.REL_LAST)
91            else:
92                self.appendAtomLink(atomroot, path, linkid, 0, Link.REL_NEXT)                   
93                self.appendAtomLink(atomroot, path, linkid, 0, Link.REL_LAST)                               
94       
95    def generateEntryLinks(self, atomroot, path, linkid = None):
96        self.appendAtomLink(atomroot, path, linkid, startIndex = None, rel = Link.REL_ALTERNATE)
97        self.appendAtomLink(atomroot, path, linkid, startIndex = None, rel = Link.REL_SEARCH)               
98               
99    def appendAtomLink(self, atomroot, path, linkid = None, startIndex = 0, rel = Link.REL_SELF):
100        href = self.generateLinkHref(path, linkid, startIndex, rel)
101        type = get_mimetype(self.extension)
102        if rel == Link.REL_SEARCH:
103            type = get_mimetype('opensearchdescription')           
104        link = Link(href, rel, type)                   
105        atomroot.append(link.buildElement())
106
107    def generateLinkHref(self, path, linkid, startIndex = None, rel = Link.REL_SELF):
108        """
109            @param path: the host URL
110            @param linkid: the search id
111            @param startIndex: the starting index
112            @param rel: a Link type identificator. If None returns a generic ID   
113        """
114        if rel == None:
115            if linkid:
116                return "%s/search/%s/" % (path, linkid)
117            else:
118                return "%s/search/" % (path)
119   
120        if rel == Link.REL_SEARCH:
121            if linkid:
122                return "%s%s/description" % (path, linkid)   
123            else:
124                return "%sdescription" % (path)
125       
126        if rel == Link.REL_ALTERNATE:
127            if linkid:
128                return "%s%s/%s" % (path, linkid, self.extension)
129            else:
130                return "%s%s" % (path, self.extension)
131   
132        if linkid:
133            return "%s%s/%s/?startIndex=%d" % (path, linkid, self.extension, startIndex)
134        else:
135            return "%s%s/?startIndex=%d" % (path, self.extension, startIndex)       
136
137    def generateEntries(self, atomroot, subresults, path):
138        entries = []
139       
140        for subresult in subresults:
141            #Here could loop over results
142            ititle = Title(Info.TEXT_TYPE, subresult.title)
143            icontent = Content(Info.HTML_TYPE, '<b> Search Feed  </b>  \
144                <ul> <li> Title: ASAR Image Mode source packets Level 0 (ASA_IM__0P) </li> \
145             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>  \
146               <li> Date: 2002-10-18 to 2012-03-29  \
147                </li> <li> Number of Records: 15945 </ul>')
148            entry = Entry(path + subresult.id + '/' + self.extension, \
149                          ititle.buildElement(), \
150                          subresult.updated, \
151                          published = '2011-01-21T11:05:29.511Z', \
152                           link = [], \
153                           content = icontent.buildElement())
154            xmlentry = entry.buildElement()
155           
156            idate = Date(atomroot, '2002-10-18T08:07:37.387Z/2012-03-29T07:12:20.735Z')       
157            xmlentry.append(idate.buildElement())
158           
159            posList = PosList(atomroot, body = '-90 -180 90 -180 90 180 -90 180 -90 -180', srsDimension = '2')
160            linearRing = LinearRing(atomroot, posList)
161            exterior = Exterior(atomroot, linearRing)
162            polygon = Polygon(atomroot, exterior)
163            where = Where(atomroot, polygon)
164            xmlentry.append(where.buildElement())
165            self.generateEntryLinks(xmlentry, path, subresult.id)
166           
167            entries.append(xmlentry)
168
169        atomroot.extend(entries)
170
171class MyOSHTMLResponse(OSHTMLResponse):
172    '''
173    classdocs
174    '''
175
176    def __init__(self):
177        '''
178        Constructor
179        '''
180        super(MyOSHTMLResponse, self).__init__()
181       
182    def generateResponse(self, result):
183        return result + " HTML!"
184       
185class MyOSQuery(OSQuery):
186    '''
187    classdocs
188    '''
189
190    def __init__(self):
191        '''
192            Constructor
193        '''
194        #param_1 = OSParam("q", "searchTerms", namespace = "http://example.com/opensearchextensions/1.0/")       
195        param_1 = OSParam("count", "count")
196        param_2 = OSParam("startPage", "startPage")
197        param_3 = OSParam("startIndex", "startIndex")               
198        param_4 = OSParam("q", "searchTerms")           
199        param_5 = OSParam("uid", "uid", namespace = "http://a9.com/-/opensearch/extensions/geo/1.0/")       
200        param_6 = OSParam("box", "box", namespace = "http://a9.com/-/opensearch/extensions/geo/1.0/")       
201        param_7 = OSParam("start", "start", namespace = "http://a9.com/-/opensearch/extensions/geo/1.0/")       
202        param_8 = OSParam("stop", "stop", namespace = "http://a9.com/-/opensearch/extensions/time/1.0/")       
203        params = [param_1, param_2, param_3, param_4, param_5, param_6, param_7, param_8]
204        super(MyOSQuery, self).__init__(params)
205       
206    def doSearch(self, **kwargs):
207        if kwargs['params_values'] and kwargs['params_values'].has_key(COLLECTION) and kwargs['params_values'].has_key(OBSERVATION):
208            return self.searchObservation(**kwargs)       
209       
210        if kwargs['params_values'] and kwargs['params_values'].has_key(COLLECTION):
211            return self.searchCollection(**kwargs)       
212           
213        results = kwargs['moles3EPB'].getObservationCollections()
214        subresults = []
215
216        for result in results:
217            result_guid = kwargs['moles3EPB'].retrieveGUIDFromInstance(result)
218            item = Subresult(result_guid.id, "title", datetime.now().isoformat())
219            subresults.append(item)
220
221        #item = Subresult("ASA_IM__0P", "ASAR Image Mode source packets Level 0 (ASA_IM__0P)", "2012-06-01T00:52:48.213Z")
222        #subresults.append(item)
223        #item = Subresult("ER02_SAR_RAW_0P", "ERS-2 SAR Image SAR Annotated Raw Data Product Level 0 (ER02_SAR_RAW_0P)", "2012-05-09T11:09:49.570Z")
224        #subresults.append(item)
225       
226        result = Result(subresult = subresults)
227        return result
228
229    def searchCollection(self, **kwargs):       
230        obs_coll = kwargs['moles3EPB'].getInstanceFromGUID(kwargs['params_values'][COLLECTION])
231        if obs_coll:
232            obs_coll = kwargs['moles3EPB'].searchSelectiveLoadByInstance(obs_coll, 'member')
233                       
234        subresults = []
235        for result in obs_coll.member:
236            result_guid = kwargs['moles3EPB'].retrieveGUIDFromInstance(result)
237            item = Subresult(result_guid.id, "title", datetime.now().isoformat())
238            subresults.append(item)
239           
240        result = Result(id = kwargs['params_values'][COLLECTION], subresult = subresults)
241        return result
242
243    def searchObservation(self, **kwargs):       
244        observation = kwargs['moles3EPB'].getInstanceFromGUID(kwargs['params_values'][OBSERVATION])
245        if observation:
246            observation = kwargs['moles3EPB'].searchSelectiveLoadByInstance(observation, 'result')
247           
248        print observation
249        '''                       
250        subresults = []
251        for result in obs_coll.member:
252            result_guid = kwargs['moles3EPB'].retrieveGUIDFromInstance(result)
253            item = Subresult(result_guid.id, "title", datetime.now().isoformat())
254            subresults.append(item)
255           
256        result = Result(id = kwargs['params_values'][COLLECTION], subresult = subresults)
257        return result
258        '''
259        return None
260
261class Result(object):
262    def __init__(self, id = None, title = "Discovery feed for Search Services", updated = datetime.now().isoformat(), subresult = []):
263        '''
264            Constructor
265            @param id: a unique identifier, eventually an URI
266            @param title: an atom.Entry instance
267            @param updated: the last time the record was updated
268            @param subresult: a Subresults array                       
269        '''
270        self.id = id
271        self.title = title
272        self.updated = updated
273        self.subresult = subresult       
274       
275
276class Subresult(object):
277    def __init__(self, id, title, updated):
278        '''
279            Constructor
280            @param id: a unique identifier, eventually an URI
281            @param title: an atom.Entry instance
282            @param updated: the last time the record was updated                       
283        '''
284        self.id = id
285        self.title = title
286        self.updated = updated
Note: See TracBrowser for help on using the repository browser.