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

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

MERGING the Qesdi branch back into the trunk. Version 0.2.1

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    filehandle = openURL(req)
109    return filehandle.read()   
110
111
112def GetResponse(url):
113    req = urllib2.Request(url)
114    req.add_header('Cookie', request.headers.get('Cookie', ''))
115    filehandle = openURL(req)
116    return filehandle.read()   
117   
118
119noProxyOpener = urllib2.build_opener(urllib2.HTTPHandler(), urllib2.ProxyHandler({}))
120
121def openURL(req):
122    log.debug("req.get_full_url() = %s" % (req.get_full_url(),))
123   
124    if _shouldUseProxy(req.get_full_url()):
125        log.debug("using proxy")
126        fh = urllib2.urlopen(req)
127    else:
128        log.debug("not using proxy")
129        fh = noProxyOpener.open(req)
130       
131    return fh
132
133def _shouldUseProxy(urlstring) :
134    no_proxy   = os.environ.get('no_proxy', '')
135   
136    urlObj = urlparse.urlparse(urlstring)
137    for np in no_proxy.split(','):
138        if urlObj.hostname == urlparse.urlparse(np).hostname:
139            return False
140   
141    return True
Note: See TracBrowser for help on using the repository browser.