source: cowsclient/branches/qesdi/cowsclient/controllers/wmsviz.py @ 5502

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/cowsclient/branches/qesdi/cowsclient/controllers/wmsviz.py@5502
Revision 5502, 6.2 KB checked in by pnorton, 11 years ago (diff)

Made a first attempt at dynamically populating the rendering options by retrieving JSON from the <MetadataURL> in the capabilities response.

Line 
1# Copyright (C) 2007 STFC & NERC (Science and Technology Facilities Council).
2# This software may be distributed under the terms of the
3# Q Public License, version 1.0 or later.
4# http://ndg.nerc.ac.uk/public_docs/QPublic_license.txt
5#
6"""
7 Controller for the 'View' tab - allowing the display of WMC map layers
8
9 @author C Byrom Feb 08, Modified D Lowe, May 09
10"""
11
12from cowsclient.lib.base import BaseController, g, response, config, request, c, session, render
13
14from paste.request import parse_querystring
15#from ows_server.models import Utilities
16from cowsclient.lib.wmc_util import GetWebMapContext, GetWebMapCapabilities, GetLegend, openURL, GetResponse
17from cowsclient.model import selectedItem
18
19
20
21import copy, logging
22log = logging.getLogger(__name__)
23import urllib, urllib2
24
25class WmsvizController(BaseController):
26   
27    def index(self):
28        """
29        Default controller method to handle the initial requests to the page
30        """
31        log.debug('wmsviz controller')
32       
33       
34        g.helpIcon='layout/icons/help.png'  #needs to go in config
35       
36        self.inputs=dict(parse_querystring(request.environ))
37        log.info(self.inputs)
38        c.wmcURL = ""
39       
40        # check if all we're doing is removing a view item
41        if 'removeItem' in self.inputs:
42            return self.removeViewItem(self.inputs['removeItem'])
43       
44       
45        log.debug("self.inputs = %s" % (self.inputs,))
46        # check if we're doing an AJAX callback to get some WMC data
47        if 'REQUEST' in self.inputs:
48                       
49            if self.inputs['REQUEST'] == 'GetWebMapContext':
50                wmc= GetWebMapContext(self)
51                return wmc
52           
53            if self.inputs['REQUEST'] == 'GetWebMapCapabilities':
54
55                wmcDoc = GetWebMapCapabilities(self.inputs['ENDPOINT'])
56               
57                response.headers['Content-Type'] = 'text/xml'
58                response.write(wmcDoc)
59                return           
60           
61            elif self.inputs['REQUEST'] == 'GetLegend':
62                return GetLegend(self)
63           
64            if self.inputs['REQUEST'] == 'GetDisplayOptions':
65               
66                jsonTxt = GetResponse(self.inputs['URL'])
67               
68                response.headers['Content-Type'] = 'application/json'
69                response.write(jsonTxt)
70                return
71               
72
73       
74        #get server information from config file
75        g.server=config['app_conf']['serverurl']
76   
77   
78       
79        #TODO: WORK OUT HOW TO COUPLE THIS TO BROWSE
80        # otherwise, we can get here by two routes:
81        # i) either by clicking on the WMC icon in the details view - if so, get passed endpoint and add to
82        #    selected items;
83        # ii) or from the selections tab - which will already have set up the correct selected items
84           
85        # if ENDPOINT specified, we've reached the page via the WMC icon
86               
87        if ('ENDPOINT' in self.inputs):
88            #clear out old endpoints NOTE. this means only one endpoint at a time can be viewed. May want to
89        #rethink this to enable 'shopping cart' type selection.
90            self.removeAllViewItems()
91            urlstring=str(self.inputs['ENDPOINT'])
92            req = urllib2.Request(urlstring)
93            req.add_header('Cookie', request.headers.get('Cookie', ''))
94            try:
95                    filehandle = openURL(req)
96            except urllib2.HTTPError, e:
97               
98                log.exception("exception occurred")
99               
100                if e.code == 401:
101                    log.info ('401 unauthorized error in cowsclient')
102                    return abort(401) #triggers ndg security framework
103                elif e.code == 403:  #TODO: 403 response is UNTESTED.
104                    # User is authenticated but doesn't have the required permissions
105                    # or an error occurred in the authorization process
106                    # Read response
107                   
108                    xresponse = e.read()
109                    # Send response to user
110                    self.start_response("%d %s" % (e.code, e.msg), e.headers.dict.items())
111                    return xresponse
112            self.addViewItem(self.inputs['ENDPOINT'])
113       
114        # avoid page crashing if we come here without view items defined
115#        if 'viewItems' not in session:
116#            h.redirect_to(h.url_for(controller='discovery'))
117#                                       
118        session.save() 
119        log.info('SAVED SESSION')
120       
121        # check if page has been visited before; if not display tab
122#        if (Utilities.isTabRequired(c.pageTabs, 'View')):
123#            c.pageTabs.append(('View', h.url_for(controller='viewItems',action='index')))
124
125        return render('wmsviz')
126
127
128    def addViewItem(self,endpoint):
129        """
130        Add a selected item to the session
131         - if this is the first item, then display the selections tab
132         @param endpoint: WMC endpoint
133        """
134       
135        item = selectedItem.SelectedItem(None, None, None, endpoint)
136       
137        selections = [item,]
138        # avoid duplicates
139        if 'viewItems' in session:
140            for selection in session['viewItems']:
141                if selection.wmcURL != endpoint:
142                    selections.append(selection)
143                   
144        session['viewItems'] = selections
145        session.save() 
146       
147   
148    def removeViewItem(self,endpoint):
149        """
150        Remove view item from session data
151        - NB, do this by rebuilding the session data without the input data included
152        @param endpoint: The WMC endpoint of the view item to remove
153        """
154        selections = []
155        for selection in session['viewItems']:
156            if selection.wmcURL != endpoint:
157                selections.append(selection)
158               
159        # if the new list is empty, remove the session variable
160        if len(selections) == 0:
161            del session['viewItems']
162            c.UpdatePageTabs=1
163        else:
164            session['viewItems'] = selections
165        session.save()
166       
167    def removeAllViewItems(self):
168        """
169        Remove all old view items - clears out old endpoints
170        """
171        session['viewItems']=[]
172        session.save()
Note: See TracBrowser for help on using the repository browser.