source: cowsclient/trunk/cowsclient/lib/wmc_util.py @ 5659

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/cowsclient/trunk/cowsclient/lib/wmc_util.py@5659
Revision 5659, 4.8 KB checked in by domlowe, 11 years ago (diff)

adding securityredirect controller to enable ajax handling of new secure endpoints

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"""
6Utils to aid use of wmc docs - including interfacing these with the con terra client
7and getting associated legend data
8
9@author: Calum Byrom, modified for NDG Security by Dominic Lowe
10"""
11from cowsclient.lib.base import *
12from cowsclient.model.WMC import WMC
13from cowsclient.lib import exceptions
14import urllib2, urllib
15import os
16import logging
17import urlparse
18log = logging.getLogger(__name__)
19
20
21def getConTerraDoc(wmcURLs):
22    """
23    Construct an aggregated XML file and display this as a temporary webpage; this will automatically be
24    POSTED so that the data is sent via POST to the Con Terra mapClient to visualise (as required by this client)
25    @param wmcURLS: An array of URLs pointing to WMC docs to visualise
26    """
27    # firstly, retrieve each WMC doc
28    wmcDocs = []
29    for wmcURL in wmcURLs:
30        wmcDocs.append(WMC(wmcURL))
31
32    # now create a dictionary of WMS/layer from these docs - to avoid duplicate layers
33    c.wms = {}
34    for wmcDoc in wmcDocs:
35        for layer in wmcDoc.layers:
36            if layer.wmsURL not in c.wms:
37                c.wms[layer.wmsURL] = [layer.name]
38            else:
39                if layer.name not in c.wms[layer.wmsURL]:
40                    c.wms[layer.wmsURL].append(layer.name)
41
42    # now create the form to post this data
43    c.redirectToConterra = True; #TODO, remove?
44    response.write(render('selectedItems'))
45
46
47
48def GetWebMapContext(self):
49    """
50    Lookup a WMC doc and return it in the response
51    """
52    # retrieve context data from the specifiled url
53    wmcDoc = RetrieveWebMapContext(self, self.inputs['ENDPOINT'])
54    log.info('WMC RESPONSE %s'%response)
55    response.headers['Content-Type'] = 'text/xml'
56    response.write(wmcDoc)
57
58def GetLegend(self):
59    """
60    Lookup a legend for a WMS map
61    NB, all required parameters are already included in the endpoint by this stage
62    """
63    endpoint = self.inputs['ENDPOINT']
64
65    if not endpoint:
66        raise exceptions.MissingParameterValue, "ENDPOINT parameter required"
67    try:
68        #req = urllib2.Request(endpoint,urllib.urlencode(request.params),{'Cookie': request.headers.get('Cookie', '')})
69        log.debug("endpoint = %s" % (endpoint,))
70        req = urllib2.Request(endpoint, None, {'Cookie': request.headers.get('Cookie', '')})
71        url = req.get_full_url()
72
73        filehandle = openURL(req)
74    except IOError:
75        raise exceptions.URLUnavailable, "Could not access WMC endpoint: %s" % endpoint
76   
77    return "<img src=\"%s\" />" % (url,)
78#    response.headers['Content-Type'] = 'image/gif'
79#    response.write(filehandle.read())
80
81def RetrieveWebMapContext(self, endpoint):
82    """
83    Get a WMC doc from a specified endpoint
84    @param endpoint: endpoint to retrieve WMC doc from
85    """
86    if not endpoint:
87        raise exceptions.MissingParameterValue, "ENDPOINT parameter required"
88    log.info('Getting WebMapContext from endpoint: ' + endpoint)
89    #urlstring=('%s&request=GetContext'%(str(endpoint)))
90    urlstring=('%s?request=GetContext&service=WMS'%(str(endpoint)))
91#    urlstring = str(endpoint)
92    log.info("urlstring=%s" % (urlstring,))
93    #cookies are passed to enable authorisation mechanisms e.g. ndg security
94    #try:
95
96    req = urllib2.Request(urlstring)
97    req.add_header('Cookie', request.headers.get('Cookie', ''))
98    filehandle = openURL(req)
99    return filehandle.read()
100
101def GetWebMapCapabilities(endpoint):
102
103   
104    urlstring=('%s?request=GetCapabilities&service=WMS'%(str(endpoint)))
105    log.debug("GetWebMapCapabilities endpoint = %s" % (endpoint,))
106    req = urllib2.Request(urlstring)
107    req.add_header('Cookie', request.headers.get('Cookie', ''))
108   
109    try:   
110        filehandle = openURL(req)
111        return filehandle.read()
112    except urllib2.HTTPError:
113        #TODO: manage 403 errors too.
114        return abort(401)
115
116
117def GetResponse(url):
118    req = urllib2.Request(url)
119    req.add_header('Cookie', request.headers.get('Cookie', ''))
120    filehandle = openURL(req)
121    return filehandle.read()   
122   
123
124noProxyOpener = urllib2.build_opener(urllib2.HTTPHandler(), urllib2.ProxyHandler({}))
125
126def openURL(req):
127    log.debug("req.get_full_url() = %s" % (req.get_full_url(),))
128   
129    if _shouldUseProxy(req.get_full_url()):
130        log.debug("using proxy")
131        fh = urllib2.urlopen(req)
132    else:
133        log.debug("not using proxy")
134        fh = noProxyOpener.open(req)
135       
136    return fh
137
138def _shouldUseProxy(urlstring) :
139    no_proxy   = os.environ.get('no_proxy', '')
140   
141    urlObj = urlparse.urlparse(urlstring)
142    for np in no_proxy.split(','):
143        if urlObj.hostname == urlparse.urlparse(np).hostname:
144            return False
145   
146    return True
Note: See TracBrowser for help on using the repository browser.