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

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

Modified the behaviour of the layerList so that new items added are automatically selected and added to the start of the list.

Also implemented an attempt at setting up the initial selection via the URL arguments.

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
19import simplejson as json
20import urlparse
21
22import copy, logging
23log = logging.getLogger(__name__)
24import urllib, urllib2
25
26class WmsvizController(BaseController):
27   
28    def index(self):
29        """
30        Default controller method to handle the initial requests to the page
31        """
32        log.debug('wmsviz controller')
33       
34       
35        g.helpIcon='layout/icons/help.png'  #needs to go in config
36       
37        self.inputs=dict(parse_querystring(request.environ))
38        log.info(self.inputs)
39        c.wmcURL = ""
40       
41        # check if all we're doing is removing a view item
42        if 'removeItem' in self.inputs:
43            return self.removeViewItem(self.inputs['removeItem'])
44       
45       
46        log.debug("self.inputs = %s" % (self.inputs,))
47        # check if we're doing an AJAX callback to get some WMC data
48        if 'REQUEST' in self.inputs:
49                       
50            if self.inputs['REQUEST'] == 'GetWebMapContext':
51                wmc= GetWebMapContext(self)
52                return wmc
53           
54            if self.inputs['REQUEST'] == 'GetWebMapCapabilities':
55
56                wmcDoc = GetWebMapCapabilities(self.inputs['ENDPOINT'])
57               
58                response.headers['Content-Type'] = 'text/xml'
59                response.write(wmcDoc)
60                return           
61           
62            elif self.inputs['REQUEST'] == 'GetLegend':
63                return GetLegend(self)
64           
65            if self.inputs['REQUEST'] == 'GetDisplayOptions':
66               
67                jsonTxt = GetResponse(self.inputs['URL'])
68               
69                response.headers['Content-Type'] = 'application/json'
70                response.write(jsonTxt)
71                return
72               
73
74       
75        #get server information from config file
76        g.server=config['app_conf']['serverurl']
77   
78   
79       
80        #TODO: WORK OUT HOW TO COUPLE THIS TO BROWSE
81        # otherwise, we can get here by two routes:
82        # i) either by clicking on the WMC icon in the details view - if so, get passed endpoint and add to
83        #    selected items;
84        # ii) or from the selections tab - which will already have set up the correct selected items
85           
86        # if ENDPOINT specified, we've reached the page via the WMC icon
87               
88        if ('ENDPOINT' in self.inputs):
89            #clear out old endpoints NOTE. this means only one endpoint at a time can be viewed. May want to
90        #rethink this to enable 'shopping cart' type selection.
91            self.removeAllViewItems()
92            urlstring=str(self.inputs['ENDPOINT'])
93            req = urllib2.Request(urlstring)
94            req.add_header('Cookie', request.headers.get('Cookie', ''))
95            try:
96                    filehandle = openURL(req)
97            except urllib2.HTTPError, e:
98               
99                log.exception("exception occurred")
100               
101                if e.code == 401:
102                    log.info ('401 unauthorized error in cowsclient')
103                    return abort(401) #triggers ndg security framework
104                elif e.code == 403:  #TODO: 403 response is UNTESTED.
105                    # User is authenticated but doesn't have the required permissions
106                    # or an error occurred in the authorization process
107                    # Read response
108                   
109                    xresponse = e.read()
110                    # Send response to user
111                    self.start_response("%d %s" % (e.code, e.msg), e.headers.dict.items())
112                    return xresponse
113            self.addViewItem(self.inputs['ENDPOINT'])
114       
115        # avoid page crashing if we come here without view items defined
116#        if 'viewItems' not in session:
117#            h.redirect_to(h.url_for(controller='discovery'))
118#                                       
119        session.save() 
120        log.info('SAVED SESSION')
121       
122        # check if page has been visited before; if not display tab
123#        if (Utilities.isTabRequired(c.pageTabs, 'View')):
124#            c.pageTabs.append(('View', h.url_for(controller='viewItems',action='index')))
125
126        initialSetup = []
127        if 'ENDPOINT' in self.inputs:
128            for ep in self.inputs['ENDPOINT'].split(','):
129                endpoint = {}
130                o = urlparse.urlparse(ep)
131               
132                if o.path.find(':') > 0:
133                    path = o.path[:o.path.find(':')]
134
135                    url = "%(scheme)s://%(hostname)s%(port)s%(path)s" % {
136                        'scheme' : o.scheme if o.scheme != None else '',
137                        'hostname' : o.hostname if o.hostname != None else '',
138                        'port' : ':' + str(o.port) if o.port != None else '',
139                        'path': path,
140                    }
141                    layers = o.path[o.path.find(':')+1:].split('|')
142                   
143                else:
144                    url = ep
145                    layers = ""
146               
147                endpoint['url'] = url
148                endpoint['layers'] = layers
149
150                initialSetup.append(endpoint)
151           
152        c.initialSetupJSON = json.dumps(initialSetup).replace('"', '\\"') 
153
154        return render('wmsviz')
155
156
157    def addViewItem(self,endpoint):
158        """
159        Add a selected item to the session
160         - if this is the first item, then display the selections tab
161         @param endpoint: WMC endpoint
162        """
163       
164        item = selectedItem.SelectedItem(None, None, None, endpoint)
165       
166        selections = [item,]
167        # avoid duplicates
168        if 'viewItems' in session:
169            for selection in session['viewItems']:
170                if selection.wmcURL != endpoint:
171                    selections.append(selection)
172                   
173        session['viewItems'] = selections
174        session.save() 
175       
176   
177    def removeViewItem(self,endpoint):
178        """
179        Remove view item from session data
180        - NB, do this by rebuilding the session data without the input data included
181        @param endpoint: The WMC endpoint of the view item to remove
182        """
183        selections = []
184        for selection in session['viewItems']:
185            if selection.wmcURL != endpoint:
186                selections.append(selection)
187               
188        # if the new list is empty, remove the session variable
189        if len(selections) == 0:
190            del session['viewItems']
191            c.UpdatePageTabs=1
192        else:
193            session['viewItems'] = selections
194        session.save()
195       
196    def removeAllViewItems(self):
197        """
198        Remove all old view items - clears out old endpoints
199        """
200        session['viewItems']=[]
201        session.save()
Note: See TracBrowser for help on using the repository browser.