def test_ncwms2():
    """Test with an ncWMS2 server.
    """
    # Note that this does not exercise the bug in https://github.com/geopython/OWSLib/issues/556
    wms = WebMapService(NCWMS2_URL, version='1.3.0')
    rsp = wms.getmap(
        layers=['f33_thredds/min_temp'],
        styles=['default'],
        srs='CRS:84',
        bbox=(-124.17, 46.02, -123.29, 46.38),
        size=(256, 256),
        format='image/png',
        transparent=True,
        mode='32bit',

    )
    assert type(rsp) is ResponseWrapper
    assert "service=WMS" in wms.request
    assert "version=1.3.0" in wms.request
    assert "request=GetMap" in wms.request
    assert "layers=f33_thredds/min_temp" in wms.request
    assert "styles=default" in wms.request
    assert "crs=CRS%3A84" in wms.request
    assert "width=256" in wms.request
    assert "height=256" in wms.request
    assert "format=image%2Fpng" in wms.request
    assert "transparent=TRUE" in wms.request
    def get_wms_image_size(self, layer_name, srs, min_x, min_y, max_x, max_y):
        """
        Get the size of the png image returned for the current service url
        | set service url | ${WMS_URL} |
        | ${image_size_in_kb} | get wms image size | bathymetry | EPSG:4326 | -112 | 55 | -106 | 71 |
        | ${greater_than_5kb} | ${image_size_in_kb} > 5 |
        | Should Be True | ${greater_than_5kb} |
        returns an integer which is the size of the image in kB

        """
        wms = WebMapService(self._url, version=self._ogc_version)

        img = wms.getmap(layers=[layer_name], srs=srs,
                         bbox=(float(min_x),
                               float(min_y),
                               float(max_x),
                               float(max_y)),
                         size=(300, 300), format='image/png')

        out = open('test.png', 'wb')
        out.write(img.read())
        out.close()

        f = open('test.png', 'rb')
        size = os.path.getsize('test.png') / 1024
        f.close()

        os.remove('test.png')

        return int(math.ceil(size))
def test_ows_interfaces_wms():
    wmsxml = open(resource_file('wms_JPLCapabilities.xml'), 'rb').read()
    service = WebMapService('url', version='1.1.1', xml=wmsxml)
    # Check each service instance conforms to OWSLib interface
    service.alias = 'WMS'
    isinstance(service, owslib.map.wms111.WebMapService_1_1_1)
    # URL attribute
    assert service.url == 'url'
    # version attribute
    assert service.version == '1.1.1'
    # Identification object
    assert hasattr(service, 'identification')
    # Check all ServiceIdentification attributes
    assert service.identification.type == 'OGC:WMS'
    for attribute in ['type', 'version', 'title', 'abstract', 'keywords', 'accessconstraints', 'fees']:
        assert hasattr(service.identification, attribute)
    # Check all ServiceProvider attributes
    for attribute in ['name', 'url', 'contact']:
        assert hasattr(service.provider, attribute)
    # Check all operations implement IOperationMetadata
    for op in service.operations:
        for attribute in ['name', 'formatOptions', 'methods']:
            assert hasattr(op, attribute)
    # Check all contents implement IContentMetadata as a dictionary
    isinstance(service.contents, OrderedDict)
    # Check any item (WCS coverage, WMS layer etc) from the contents of each service
    # Check it conforms to IContentMetadata interface
    # get random item from contents dictionary -has to be a nicer way to do this!
    content = service.contents[list(service.contents.keys())[0]]
    for attribute in ['id', 'title', 'boundingBox', 'boundingBoxWGS84', 'crsOptions', 'styles', 'timepositions']:
        assert hasattr(content, attribute)
def test_getmap_130_national_map():
    """National Map"""
    # TODO: use flaky tests or fix it: https://pypi.python.org/pypi/pytest-ignore-flaky
    url = SERVICE_URL_NATIONAL_MAP
    wms = WebMapService(url, version='1.3.0')
    rsp = wms.getmap(
        layers=['3'],
        styles=['default'],
        srs='CRS:84',
        bbox=(-176.646, 17.7016, -64.8017, 71.2854),
        size=(500, 300),
        format='image/png',
        transparent=True)
    assert type(rsp) is ResponseWrapper
    assert "service=WMS" in wms.request
    assert "version=1.3.0" in wms.request
    assert "request=GetMap" in wms.request
    assert "layers=3" in wms.request
    assert "styles=default" in wms.request
    assert "crs=CRS%3A84" in wms.request
    assert "box=-176.646%2C17.7016%2C-64.8017%2C71.2854" in wms.request
    assert "width=500" in wms.request
    assert "height=300" in wms.request
    assert "format=image%2Fpng" in wms.request
    assert "transparent=TRUE" in wms.request
Exemple #5
0
class HandleWMS():

    def __init__(self, url, version="1.1.1"):
        self.wms = WebMapService(url, version=version)
        self.type = self.wms.identification.type
        self.version = self.wms.identification.version
        self.title = self.wms.identification.title
        self.abstract = self.wms.identification.abstract
        self.size = (256, 256)

    def get_service_url(self, method='Get'):
        return self.wms.getOperationByName('GetMap').methods[method]['url']

    def get_format_options(self, format='image/png'):
        formats = self.wms.getOperationByName('GetMap').formatOptions
        if format in formats:
            return format
        else:
            return formats

    def get_srs(self, layer, srs='EPSG:4326'):
        this_layer = self.wms[layer]
        srs_list = this_layer.crsOptions
        if srs in srs_list:
            return srs
        else:
            return "SRS Not Found"

    def get_bbox(self, layer):
        this_layer = self.wms[layer]
        return this_layer.boundingBoxWGS84

    def do_layer_check(self, resource):
        layer_list = list(self.wms.contents)
        this_layer = resource.get("layer")
        try:
            first_layer = layer_list[0]
            if this_layer in layer_list:
                return this_layer
            elif this_layer.lower() in layer_list:
                return this_layer.lower()
            else:
                return first_layer
        except Exception:
            pass

    def get_layer_info(self, data_dict):
        layer = self.do_layer_check(data_dict)
        bbox = self.get_bbox(layer)
        srs = self.get_srs(layer)
        format = self.get_format_options()
        service_url = self.get_service_url()
        return {
            'layer': layer,
            'bbox': bbox,
            'srs': srs,
            'format': format,
            'service_url': service_url
        }
Exemple #6
0
 def addLayersFromWms(self):
         """Add new LayerDownloaders from the result of a WMS GetCapabilities
         """
         wmsUrl = self.forgeOwsUrl('wms')
         wms = WebMapService(wmsUrl, version='1.1.1')
         layers = wms.items()
         for l in layers:
                 self.addLayerDownloader(l[1])
         return self.layerDownloaders
Exemple #7
0
 def gui_addgeos(self,website='http://wms.gsfc.nasa.gov/cgi-bin/wms.cgi?project=GEOS.fp.fcst.inst1_2d_hwl_Nx'):
     'GUI handler for adding the figures from WMS support of GEOS'
     from gui import Popup_list
     try:
         from owslib.wms import WebMapService
         from owslib.util import openURL
         from StringIO import StringIO
         from PIL import Image
         self.line.tb.set_message('Loading WMS from :'+website.split('/')[2])
         wms = WebMapService(website)
         cont = list(wms.contents)
     except Exception as ie:
         print ie
         import tkMessageBox
         tkMessageBox.showwarning('Sorry','Loading WMS map file from '+website.split('/')[2]+' servers not working...')
         return
     titles = [wms[c].title for c in cont]
     arr = [x.split('-')[-1]+':  '+y for x,y in zip(cont,titles)]
     i = Popup_list(arr)
     self.line.tb.set_message('Selected WMS map: '+titles[i].split(',')[-1])
     if wms[cont[i]].timepositions:
         times = wms[cont[i]].timepositions
         j = Popup_list(times)
         time_sel = times[j]
     else:
         time_sel = None
     try:
         if not time_sel:
             time_sel = self.line.ex.datestr+'T12:00'
         ylim = self.line.line.axes.get_ylim()
         xlim = self.line.line.axes.get_xlim()
         #img = wms.getdata(layers=[cont[i]],
         #                  bbox=(ylim[0],xlim[0],ylim[1],xlim[1]),
         #                  size=(480,240),
         #                  transparent=True,
         #                  time=time_sel,
         #                  srs='EPSG:4326',
         #                  format='image/png')
         #leg_call = openURL(img.geturl().replace('GetMap','GetLegend'))
         img = wms.getdata(layers=[cont[i],'countries'],
                           bbox=(ylim[0],xlim[0],ylim[1],xlim[1]),
                           size=(480,240),
                           transparent=True,
                           time=time_sel,
                           srs='EPSG:4326',
                           format='image/png')
         geos = Image.open(StringIO(img.read()))
         self.line.addfigure_under(geos,xlim[0],ylim[0],xlim[1],ylim[1])
         #self.line.line.figure.add
         #leg = Image.open(StringIO(leg_call.read()))
         #self.line.addfigure_under(leg,xlim[0],ylim[0],xlim[1],ylim[1],outside=True)
     except:
         import tkMessageBox
         tkMessageBox.showwarning('Sorry','Problem getting the image to load')
         return
	def generate_preview_image(self, styles=None):
		wms = WebMapService(self.wms.online_resource)
		img = wms.getmap(layers=[self.name],
			srs='EPSG:4326',
			bbox=self.latlon_bbox,
			size=(300,250), # TODO: Calculate optimum size for preview image at this approx size
			format='image/jpeg',
			transparent=True)
		out = open(('%s.jpg' % (self.name)), 'wb')
		out.write(img.read())
		out.close()
Exemple #9
0
def build_wms_image(bbox):
    url = "%s/wms" % settings.GEOSERVER_BASE_URL
    wms = WebMapService(url, version='1.1.1')
    img = wms.getmap(layers=['haiti'],
                     srs='EPSG:4326',
                     bbox=bbox,
                     size=(1400, 700),
                     bgcolor="#b5d0d0",
                     format='image/jpeg',
                     transparent=True)
    return img
def test_wms_getmap_130():
    """GetMap 1.3.0"""
    wms = WebMapService(SERVICE_URL, version='1.3.0')
    rsp = wms.getmap(
        layers=['nexrad_base_reflect'],
        styles=['default'],
        srs='EPSG:4326',
        bbox=(-126, 24, -66, 50),
        size=(250, 250),
        format='image/jpeg',
        transparent=True)
    assert type(rsp) is ResponseWrapper
def test_wms_getmap_111():
    """MESONET GetMap 1.1.1"""
    wms = WebMapService(SERVICE_URL, version='1.1.1')
    assert wms.request == '{}?service=WMS&request=GetCapabilities&version=1.1.1'.format(SERVICE_URL)
    rsp = wms.getmap(
        layers=['nexrad_base_reflect'],
        styles=['default'],
        srs='EPSG:4326',
        bbox=(-126, 24, -66, 50),
        size=(250, 250),
        format='image/jpeg',
        transparent=True)
    import owslib.util
    assert type(rsp) is ResponseWrapper
 def check_advertised_wms_layers(self):
     """
     Makes a GetMap request for each layer advertised by WMS service.
     An exception is raised on failure.
     | Check advertised wms layers |
     """
     wms = WebMapService(self._url, version=self._ogc_version)
     for layer in wms.contents.values():
         wms.getmap(
             layers=[layer.name],
             srs=layer.crsOptions[0],
             bbox=layer.boundingBox[0:-1],
             size=(300, 300),
             format=wms.getOperationByName('GetMap').formatOptions[0])
def get_layer(layer_name):

    wms = WebMapService('http://geoserver.gis.irisnetlab.be/geoserver/wfs', version="1.3")

    kml = wms.getmap(
        layers=[layer_name],
        srs="epsg:4326",
        bbox=wms[layer_name].boundingBox[:-1],
        size=(3000, 3000),
        format='kml', 
        transparent=True
    ).read()

    return kml
Exemple #14
0
 def __init__(self, url, version="1.1.1"):
     self.wms = WebMapService(url, version=version)
     self.type = self.wms.identification.type
     self.version = self.wms.identification.version
     self.title = self.wms.identification.title
     self.abstract = self.wms.identification.abstract
     self.size = (256, 256)
def test_wms_getmap_130_service_exception():
    """GetMap 1.3.0 ServiceException for an invalid CRS"""
    wms = WebMapService(SERVICE_URL, version='1.3.0')
    try:
        wms.getmap(
            layers=['nexrad_base_reflect'],
            styles=['default'],
            srs='EPSG:4328',
            bbox=(-126, 24, -66, 50),
            size=(250, 250),
            format='image/jpeg',
            transparent=True)
    except ServiceException as e:
        assert "msWMSLoadGetMapParams(): WMS server error. Invalid CRS given : CRS must be valid for all requested layers." in str(e)  # noqa
    else:
        assert False
def main():
	wms = WebMapService('http://maps.nzoss.org.nz/mapserv?template=openlayers&service=wms&request=getCapabilities', version='1.1.0')

	layer_name = 'default'
	layer = wms[layer_name]
	
	img = wms.getmap(
		layers=[layer_name],
		srs=layer.crsOptions[0],
		bbox=(layer.boundingBox[0], layer.boundingBox[1], layer.boundingBox[2], layer.boundingBox[3]),
		size=(500,400),
		format='image/png',
		transparent=False
		)

	with open('nz_oss_wms.png', 'wb') as out:
		out.write(img.read())
Exemple #17
0
def _process_wms_service(url, name, type, username, password, wms=None, owner=None, parent=None):
    """
    Create a new WMS/OWS service, cascade it if necessary (i.e. if Web Mercator not available)
    """
    if wms is None:
        wms = WebMapService(url)
    try:
        base_url = _clean_url(
            wms.getOperationByName('GetMap').methods['Get']['url'])

        if base_url and base_url != url:
            url = base_url
            wms = WebMapService(base_url)
    except:
        logger.info(
            "Could not retrieve GetMap url, using originally supplied URL %s" % url)
        pass

    try:
        service = Service.objects.get(base_url=url)
        return_dict = [{'status': 'ok',
                        'msg': _("This is an existing service"),
                        'service_id': service.pk,
                        'service_name': service.name,
                        'service_title': service.title
                        }]
        return HttpResponse(json.dumps(return_dict),
                            mimetype='application/json',
                            status=200)
    except:
        pass

    title = wms.identification.title
    if not name:
        if title:
            name = _get_valid_name(title)
        else:
            name = _get_valid_name(urlsplit(url).netloc)
    try:
        supported_crs = ','.join(wms.contents.itervalues().next().crsOptions)
    except:
        supported_crs = None
    if supported_crs and re.search('EPSG:900913|EPSG:3857|EPSG:102100', supported_crs):
        return _register_indexed_service(type, url, name, username, password, wms=wms, owner=owner, parent=parent)
    else:
        return _register_cascaded_service(url, type, name, username, password, wms=wms, owner=owner, parent=parent)
def run_test_resource(resource_type, url):
    """tests a CSW service and provides run metrics"""

    if resource_type not in RESOURCE_TYPES.keys():
        msg = gettext('Invalid resource type')
        msg2 = '%s: %s' % (msg, resource_type)
        LOGGER.error(msg2)
        raise RuntimeError(msg2)

    title = None
    start_time = datetime.datetime.utcnow()
    message = None

    try:
        if resource_type == 'OGC:WMS':
            ows = WebMapService(url)
        elif resource_type == 'OGC:WFS':
            ows = WebFeatureService(url)
        elif resource_type == 'OGC:WCS':
            ows = WebCoverageService(url)
        elif resource_type == 'OGC:WPS':
            ows = WebProcessingService(url)
        elif resource_type == 'OGC:CSW':
            ows = CatalogueServiceWeb(url)
        elif resource_type == 'OGC:SOS':
            ows = SensorObservationService(url)
        elif resource_type in ['WWW:LINK', 'urn:geoss:waf']:
            ows = urlopen(url)
            if resource_type == 'WWW:LINK':
                import re
                try:
                    title_re = re.compile("<title>(.+?)</title>")
                    title = title_re.search(ows.read()).group(1)
                except:
                    title = url
            elif resource_type == 'urn:geoss:waf':
                title = 'WAF %s %s' % (gettext('for'), urlparse(url).hostname)
        elif resource_type == 'FTP':
            ows = urlopen(url)
            title = urlparse(url).hostname
        success = True
        if resource_type.startswith('OGC:'):
            title = ows.identification.title
        if title is None:
            title = '%s %s %s' % (resource_type, gettext('for'), url)
    except Exception as err:
        msg = str(err)
        LOGGER.exception(msg)
        message = msg
        success = False

    end_time = datetime.datetime.utcnow()

    delta = end_time - start_time
    response_time = '%s.%s' % (delta.seconds, delta.microseconds)

    return [title, success, response_time, message, start_time]
Exemple #19
0
def get_full_map(uri, base_name=None, layers=None, size=(300,300)):
    print 'Get map for %s' % uri

    # Get the wms object
    wms = WebMapService(uri)

    # Get random layer if not specified
    if not layers:
        layers = list(wms.contents)
    # Set to maximum 5 layers
    if len(layers) > 5:
        layers = random.sample(layers, 5)

    print 'layers', layers
    
    # Set crs
    srs='EPSG:4326'
    
    # Get bounding box of the layers
    bbox = wms.contents[layers[0]].boundingBoxWGS84
    print 'bbox', bbox
    
    # Get image formats
    image_formats = wms.getOperationByName('GetMap').formatOptions
    
    if 'image/png' in image_formats:
        image_format = 'image/png'
    elif 'image/jpeg' in image_formats:
        image_format = 'image/jpeg'
    else:
        image_format = image_formats[0]
    print 'image_format', image_format

    styles = []

    image = None

    try:
        image = retrieve_map_owslib(uri, bbox, srs, size, image_format, styles, layers, wms)
    except Exception, e:
        print 'Can not use retrieve_map_owslib because %s' % e
    def __init__(self, zoom_level=19):
        self.logger = logging.getLogger(__name__)
        self.current_directory = os.path.dirname(os.path.realpath(__file__))
        self.env = self._read_env()
        self.auth = self.set_auth()
        self.zoom_level = zoom_level

        self._auth_monkey_patch(self.auth)

        from owslib.wms import WebMapService

        self.wms = WebMapService(url=self.env("URL"), version=self.env("VERSION"))
Exemple #21
0
def retrieve_map_owslib(uri, bbox, srs, size, image_format, styles, layers, wms=None):
    """Retrieve image of a map from wms server using owslib."""
    
    print 'Use owslib method'
    if not wms:
        # Get the wms object
        wms = WebMapService(uri)

    # This is important to make sure they have the same length
    if len(styles) != len(layers):
        styles = [''] * len(layers)

    image = wms.getmap(
        layers=layers,
        styles=styles,
        srs=srs,
        bbox=bbox,
        size=size,
        format=image_format,
        transparent=True
    )

    return image
Exemple #22
0
def get_dop(bbox, size):
    from owslib.wms import WebMapService
    wms = WebMapService('http://geodaten.bayern.de/ogc/ogc_dop200_oa.cgi?', version='1.1.1')
    
    img = wms.getmap(
        layers=['adv_dop200c'],
        srs='EPSG:4326', # WGS84
        #srs='EPSG:31468', # GK4
        bbox=bbox,
        size=size,
        format='image/png'
    )
    
    # TODO 
    import cStringIO
    imgIO = cStringIO.StringIO(img.read())
    try:
        img = Image.open(imgIO)
        #img.show()
    except:
        print imgIO.read();   
        raise
    
    return img
def run_test_resource(resource_type, url):
    """tests a CSW service and provides run metrics"""

    if resource_type not in RESOURCE_TYPES.keys():
        msg = 'Invalid resource type: %s' % resource_type
        LOGGER.error(msg)
        raise RuntimeError(msg)

    title = None
    start_time = datetime.datetime.utcnow()
    message = None

    try:
        if resource_type == 'OGC:WMS':
            ows = WebMapService(url)
        elif resource_type == 'OGC:WFS':
            ows = WebFeatureService(url)
        elif resource_type == 'OGC:WCS':
            ows = WebCoverageService(url)
        elif resource_type == 'OGC:WPS':
            ows = WebProcessingService(url)
        elif resource_type == 'OGC:CSW':
            ows = CatalogueServiceWeb(url)
        elif resource_type == 'OGC:SOS':
            ows = SensorObservationService(url)
        elif resource_type in ['WWW:LINK', 'urn:geoss:waf']:
            ows = urlopen(url)
            if resource_type == 'WWW:LINK':
                import re
                try:
                    title_re = re.compile("<title>(.+?)</title>")
                    title = title_re.search(ows.read()).group(1)
                except:
                    title = url
            elif resource_type == 'urn:geoss:waf':
                title = 'WAF for %s' % urlparse(url).hostname
        elif resource_type == 'FTP':
            ows = urlopen(url)
            title = urlparse(url).hostname
        success = True
        if resource_type.startswith('OGC:'):
            title = ows.identification.title
        if title is None:
            title = '%s for %s' % (resource_type, url)
    except Exception, err:
        msg = str(err)
        LOGGER.exception(msg)
        message = msg
        success = False
class HandleWMS():
    """
    Processor for WMS resources.  Requires a getCapabilities URL for the WMS and a WMS version passed in as a string.
    For now, only WMS v1.1.1 is supported by OWSLib.
    """

    def __init__(self, url, version="1.1.1"):
        self.wms = WebMapService(url, version=version)
        self.type = self.wms.identification.type
        self.version = self.wms.identification.version
        self.title = self.wms.identification.title
        self.abstract = self.wms.identification.abstract
        self.size = (256, 256)

    # Return a specific service URL, getMap is default
    def get_service_url(self, method='Get'):
        return self.wms.getOperationByName('GetMap').methods[method]['url']

    # Return an image format, *.png is default
    def get_format_options(self, format='image/png'):
        formats = self.wms.getOperationByName('GetMap').formatOptions
        if format in formats:
            return format
        else:
            return formats

    # Return a spatial reference system, default is WGS84
    def get_srs(self, layer, srs='EPSG:4326'):
        this_layer = self.wms[layer]
        srs_list = this_layer.crsOptions
        if srs in srs_list:
            return srs
        else:
            return "SRS Not Found"

    # Return bounding box of the service
    def get_bbox(self, layer):
        this_layer = self.wms[layer]
        return this_layer.boundingBoxWGS84

    # Pass in a dictionary with the layer name bound to 'layer'.  If the 'layer' is not found, then just return the
    # first layer in the list of available layers
    def do_layer_check(self, data_dict):
        layer_list = list(self.wms.contents)
        resource = data_dict.get("resource", {})
        this_layer = resource.get("layer")
        try:
            first_layer = layer_list[0]
            if this_layer in layer_list:
                return this_layer
            elif this_layer.lower() in layer_list:
                return this_layer.lower()
            else:
                return first_layer
        except Exception:
            pass

    # Return all of the information we need to access features in a WMS as one dictionary
    def get_layer_info(self, data_dict):
        layer = self.do_layer_check(data_dict)
        bbox = self.get_bbox(layer)
        srs = self.get_srs(layer)
        format = self.get_format_options()
        service_url = self.get_service_url()
        return {
            'layer': layer,
            'bbox': bbox,
            'srs': srs,
            'format': format,
            'service_url': service_url
            }
class WmsApi:
    def __init__(self, zoom_level=19):
        self.logger = logging.getLogger(__name__)
        self.current_directory = os.path.dirname(os.path.realpath(__file__))
        self.env = self._read_env()
        self.auth = self.set_auth()
        self.zoom_level = zoom_level

        self._auth_monkey_patch(self.auth)

        from owslib.wms import WebMapService

        self.wms = WebMapService(url=self.env("URL"), version=self.env("VERSION"))

    def set_auth(self):
        user = self.env("NTLM_USER")
        password = self.env("NTLM_PASSWORD")
        return HttpNtlmAuth(user, password) if user is not None and password is not None else None

    def _read_env(self):
        env = environ.Env(
            NTLM_USER=(str, None),
            NTLM_PASSWORD=(str, None),
            URL=(str, None),
            SRS=(str, None),
            VERSION=(str, None),
            LAYER=(str, None),
        )
        current = environ.Path(self.current_directory)
        environ.Env.read_env(current(".env"))
        self._settings_check(env)
        return env

    def _settings_check(self, env):
        if env("URL") is None or env("SRS") is None or env("VERSION") is None or env("LAYER") is None:
            error_message = "You have to set all URL, SRS, LAYER and VERSION in your .env config file."
            self.logger.error(error_message)
            raise Exception(error_message)

    @staticmethod
    def _auth_monkey_patch(auth):
        AuthMonkeyPatch(auth)

    def get_image(self, bbox):
        size = self._calculate_image_size(bbox, self.zoom_level)
        image = self._get(
            layers=[self.env("LAYER")], srs=self.env("SRS"), bbox=self._box(bbox), size=size, format="image/jpeg"
        )
        return image

    @staticmethod
    def _calculate_image_size(bbox, zoom_level):
        meters_per_pixel = geo_helper.meters_per_pixel(zoom_level, bbox.bottom)
        width_meter = bbox.node_left_down().get_distance_in_meter(bbox.node_right_down())
        height_meter = bbox.node_left_down().get_distance_in_meter(bbox.node_left_up())
        height = int(height_meter / meters_per_pixel)
        width = int(width_meter / meters_per_pixel)
        return width, height

    def _get(self, **kwargs):
        img = self.wms.getmap(**kwargs)
        return Image.open(BytesIO(img.read()))

    @staticmethod
    def _box(bbox):
        node_left_down = bbox.node_left_down()
        node_right_up = bbox.node_right_up()
        return node_left_down.longitude, node_left_down.latitude, node_right_up.longitude, node_right_up.latitude
Exemple #26
0
def _parse_wms(context, repos, record, identifier):

    from owslib.wms import WebMapService

    recobjs = []
    serviceobj = repos.dataset()

    md = WebMapService(record)

    # generate record of service instance
    _set(context, serviceobj, 'pycsw:Identifier', identifier)
    _set(context, serviceobj, 'pycsw:Typename', 'csw:Record')
    _set(context, serviceobj, 'pycsw:Schema', 'http://www.opengis.net/wms')
    _set(context, serviceobj, 'pycsw:MdSource', record)
    _set(context, serviceobj, 'pycsw:InsertDate', util.get_today_and_now())
    _set(context, serviceobj, 'pycsw:XML', md.getServiceXML())
    _set(context, serviceobj, 'pycsw:AnyText', util.get_anytext(md.getServiceXML()))
    _set(context, serviceobj, 'pycsw:Type', 'service')
    _set(context, serviceobj, 'pycsw:Title', md.identification.title)
    _set(context, serviceobj, 'pycsw:Abstract', md.identification.abstract)
    _set(context, serviceobj, 'pycsw:Keywords', ','.join(md.identification.keywords))
    _set(context, serviceobj, 'pycsw:Creator', md.provider.contact.name)
    _set(context, serviceobj, 'pycsw:Publisher', md.provider.contact.name)
    _set(context, serviceobj, 'pycsw:Contributor', md.provider.contact.name)
    _set(context, serviceobj, 'pycsw:OrganizationName', md.provider.contact.name)
    _set(context, serviceobj, 'pycsw:AccessConstraints', md.identification.accessconstraints)
    _set(context, serviceobj, 'pycsw:OtherConstraints', md.identification.fees)
    _set(context, serviceobj, 'pycsw:Source', record)
    _set(context, serviceobj, 'pycsw:Format', md.identification.type)
    for c in md.contents:
        if md.contents[c].parent is None:
            bbox = md.contents[c].boundingBoxWGS84
            tmp = '%s,%s,%s,%s' % (bbox[0], bbox[1], bbox[2], bbox[3])
            _set(context, serviceobj, 'pycsw:BoundingBox', util.bbox2wktpolygon(tmp))
            break
    _set(context, serviceobj, 'pycsw:CRS', 'urn:ogc:def:crs:EPSG:6.11:4326')
    _set(context, serviceobj, 'pycsw:DistanceUOM', 'degrees')
    _set(context, serviceobj, 'pycsw:ServiceType', md.identification.type)
    _set(context, serviceobj, 'pycsw:ServiceTypeVersion', md.identification.version)
    _set(context, serviceobj, 'pycsw:Operation', ','.join([d.name for d in md.operations]))
    _set(context, serviceobj, 'pycsw:OperatesOn', ','.join(list(md.contents)))
    _set(context, serviceobj, 'pycsw:CouplingType', 'tight')

    recobjs.append(serviceobj) 
         
    # generate record foreach layer

    LOGGER.debug('Harvesting %d WMS layers' % len(md.contents))

    for layer in md.contents:
        recobj = repos.dataset()
        identifier2 = '%s-%s' % (identifier, md.contents[layer].name)
        _set(context, recobj, 'pycsw:Identifier', identifier2)
        _set(context, recobj, 'pycsw:Typename', 'csw:Record')
        _set(context, recobj, 'pycsw:Schema', 'http://www.opengis.net/wms')
        _set(context, recobj, 'pycsw:MdSource', record)
        _set(context, recobj, 'pycsw:InsertDate', util.get_today_and_now())
        _set(context, recobj, 'pycsw:XML', md.getServiceXML())
        _set(context, recobj, 'pycsw:AnyText', util.get_anytext(md._capabilities))
        _set(context, recobj, 'pycsw:Type', 'dataset')
        _set(context, recobj, 'pycsw:ParentIdentifier', identifier)
        _set(context, recobj, 'pycsw:Title', md.contents[layer].title)
        _set(context, recobj, 'pycsw:Abstract', md.contents[layer].abstract)
        _set(context, recobj, 'pycsw:Keywords', ','.join(md.contents[layer].keywords))

        bbox = md.contents[layer].boundingBoxWGS84
        if bbox is not None:
            tmp = '%s,%s,%s,%s' % (bbox[0], bbox[1], bbox[2], bbox[3])
            _set(context, recobj, 'pycsw:BoundingBox', util.bbox2wktpolygon(tmp))
            _set(context, recobj, 'pycsw:CRS', 'urn:ogc:def:crs:EPSG:6.11:4326')
            _set(context, recobj, 'pycsw:Denominator', 'degrees')
        else:
            bbox = md.contents[layer].boundingBox
            if bbox:
                tmp = '%s,%s,%s,%s' % (bbox[0], bbox[1], bbox[2], bbox[3])
                _set(context, recobj, 'pycsw:BoundingBox', util.bbox2wktpolygon(tmp))
                _set(context, recobj, 'pycsw:CRS', 'urn:ogc:def:crs:EPSG:6.11:%s' % \
                bbox[-1].split(':')[1])

        recobjs.append(recobj)

    return recobjs
Exemple #27
0
def _parse_wms(context, repos, record, identifier):

    from owslib.wms import WebMapService

    recobjs = []
    serviceobj = repos.dataset()

    md = WebMapService(record)

    # generate record of service instance
    _set(context, serviceobj, 'pycsw:Identifier', identifier)
    _set(context, serviceobj, 'pycsw:Typename', 'csw:Record')
    _set(context, serviceobj, 'pycsw:Schema', 'http://www.opengis.net/wms')
    _set(context, serviceobj, 'pycsw:MdSource', record)
    _set(context, serviceobj, 'pycsw:InsertDate', util.get_today_and_now())
    _set(context, serviceobj, 'pycsw:XML', md.getServiceXML())
    _set(context, serviceobj, 'pycsw:AnyText', util.get_anytext(md.getServiceXML()))
    _set(context, serviceobj, 'pycsw:Type', 'service')
    _set(context, serviceobj, 'pycsw:Title', md.identification.title)
    _set(context, serviceobj, 'pycsw:Abstract', md.identification.abstract)
    _set(context, serviceobj, 'pycsw:Keywords', ','.join(md.identification.keywords))
    _set(context, serviceobj, 'pycsw:Creator', md.provider.contact.name)
    _set(context, serviceobj, 'pycsw:Publisher', md.provider.contact.name)
    _set(context, serviceobj, 'pycsw:Contributor', md.provider.contact.name)
    _set(context, serviceobj, 'pycsw:OrganizationName', md.provider.contact.name)
    _set(context, serviceobj, 'pycsw:AccessConstraints', md.identification.accessconstraints)
    _set(context, serviceobj, 'pycsw:OtherConstraints', md.identification.fees)
    _set(context, serviceobj, 'pycsw:Source', record)
    _set(context, serviceobj, 'pycsw:Format', md.identification.type)
    for c in md.contents:
        if md.contents[c].parent is None:
            bbox = md.contents[c].boundingBoxWGS84
            tmp = '%s,%s,%s,%s' % (bbox[0], bbox[1], bbox[2], bbox[3])
            _set(context, serviceobj, 'pycsw:BoundingBox', util.bbox2wktpolygon(tmp))
            break
    _set(context, serviceobj, 'pycsw:CRS', 'urn:ogc:def:crs:EPSG:6.11:4326')
    _set(context, serviceobj, 'pycsw:DistanceUOM', 'degrees')
    _set(context, serviceobj, 'pycsw:ServiceType', md.identification.type)
    _set(context, serviceobj, 'pycsw:ServiceTypeVersion', md.identification.version)
    _set(context, serviceobj, 'pycsw:Operation', ','.join([d.name for d in md.operations]))
    _set(context, serviceobj, 'pycsw:OperatesOn', ','.join(list(md.contents)))
    _set(context, serviceobj, 'pycsw:CouplingType', 'tight')

    links = [
        '%s,OGC-WMS Web Map Service,OGC:WMS,%s' % (identifier, md.url),
        '%s,OGC-WMS Capabilities service (ver 1.1.1),OGC:WMS-1.1.1-http-get-capabilities,%s' % (identifier, build_get_url(md.url, {'service': 'WMS', 'version': '1.1.1', 'request': 'GetCapabilities'})),
    ]

    _set(context, serviceobj, 'pycsw:Links', '^'.join(links))

    recobjs.append(serviceobj) 
         
    # generate record foreach layer

    LOGGER.debug('Harvesting %d WMS layers' % len(md.contents))

    for layer in md.contents:
        recobj = repos.dataset()
        identifier2 = '%s-%s' % (identifier, md.contents[layer].name)
        _set(context, recobj, 'pycsw:Identifier', identifier2)
        _set(context, recobj, 'pycsw:Typename', 'csw:Record')
        _set(context, recobj, 'pycsw:Schema', 'http://www.opengis.net/wms')
        _set(context, recobj, 'pycsw:MdSource', record)
        _set(context, recobj, 'pycsw:InsertDate', util.get_today_and_now())
        _set(context, recobj, 'pycsw:XML', md.getServiceXML())
        _set(context, recobj, 'pycsw:AnyText', util.get_anytext(md._capabilities))
        _set(context, recobj, 'pycsw:Type', 'dataset')
        _set(context, recobj, 'pycsw:ParentIdentifier', identifier)
        _set(context, recobj, 'pycsw:Title', md.contents[layer].title)
        _set(context, recobj, 'pycsw:Abstract', md.contents[layer].abstract)
        _set(context, recobj, 'pycsw:Keywords', ','.join(md.contents[layer].keywords))

        bbox = md.contents[layer].boundingBoxWGS84
        if bbox is not None:
            tmp = '%s,%s,%s,%s' % (bbox[0], bbox[1], bbox[2], bbox[3])
            _set(context, recobj, 'pycsw:BoundingBox', util.bbox2wktpolygon(tmp))
            _set(context, recobj, 'pycsw:CRS', 'urn:ogc:def:crs:EPSG:6.11:4326')
            _set(context, recobj, 'pycsw:Denominator', 'degrees')
        else:
            bbox = md.contents[layer].boundingBox
            if bbox:
                tmp = '%s,%s,%s,%s' % (bbox[0], bbox[1], bbox[2], bbox[3])
                _set(context, recobj, 'pycsw:BoundingBox', util.bbox2wktpolygon(tmp))
                _set(context, recobj, 'pycsw:CRS', 'urn:ogc:def:crs:EPSG:6.11:%s' % \
                bbox[-1].split(':')[1])

        params = {
            'service': 'WMS',
            'version': '1.1.1',
            'request': 'GetMap',
            'layers': md.contents[layer].name,
            'format': 'image/png',
            'height': '200',
            'width': '200',
            'srs': 'EPSG:4326',
            'bbox':  '%s,%s,%s,%s' % (bbox[0], bbox[1], bbox[2], bbox[3]),
            'styles': ''
        }

        links = [
            '%s,Web image thumbnail (URL),WWW:LINK-1.0-http--image-thumbnail,%s' % (md.contents[layer].name, build_get_url(md.url, params))
        ]

        _set(context, recobj, 'pycsw:Links', '^'.join(links))

        recobjs.append(recobj)

    return recobjs
Exemple #28
0
from owslib.wms import WebMapService
wms = WebMapService('http://212.26.144.110/geowebcache/service/wms', version='1.1.1')

wms.getfeatureinfo(layers='kadastr', query_layers='kadastr',styles='',
                   info_format='application/vnd.ogc.gml',srs='EPSG:900913')
Exemple #29
0
def test_service(record, output, format_type):
    """Test given service based on configuration record
    dictionary with at least 'url' attribute
    """

    url = record["url"]
    # version = '1.3.0'
    # if record.get('version'):
    #    version = record['version']

    log_file = open(LOG, "a")
    log_file.write(url + "\n")
    log_file.close()

    exception = None
    result = True
    layers = []
    service = None
    title = None

    try:
        service = WebMapService(url)
    except Exception as e:
        result = False
        exception = traceback.format_exc()

    if "title" in record:
        title = record["title"]

    if service:

        if record.get("use_service_url"):
            method = next(
                (
                    getmap_method
                    for getmap_method in service.getOperationByName("GetMap").methods
                    if getmap_method["type"].lower() == "get"
                )
            )
            method["url"] = service.url

        layers = None
        if "layers" in record:
            layers = record["layers"]
        layers = test_layers(service, layers)
        for layer in layers:
            if not layers[layer]["is_image"]:
                result = False

    result = {
        "id": str(uuid.uuid4()),
        "url": url,
        "title": title,
        "layers": layers,
        "passed": result,
        "exception": exception,
    }

    make_report(output, result, format_type)

    return result
Exemple #30
0
        <LayerSRS>WGS84</LayerSRS>
        <GeometryField encoding="PointFromColumns" x="%s" y="%s"/>
    </OGRVRTLayer>
</OGRVRTDataSource>
        '''
    fname = iname.strip().split('.')[0]
    oname = fname+".vrt"
    output = template % (fname,iname,lon,lat)
    # opens an text file to write the output to
    outFileHandle = open(oname, "w")
    outFileHandle.write(output)
    outFileHandle.close()

if __name__ == '__main__':

    wms = WebMapService('http://bhuvan5.nrsc.gov.in/bhuvan/wms')
    '''
    # learn on WMS services  
    print(wms.identification.type)
    print(wms.identification.version)
    print(wms.identification.title)
    print(wms.identification.abstract)
    print(list(wms.contents))
    print(wms['vector:AS_LULC50K_1112'].title)
    print(wms['vector:AS_LULC50K_1112'].boundingBoxWGS84)
    print(wms['vector:AS_LULC50K_1112'].crsOptions)
    print(wms['vector:AS_LULC50K_1112'].styles)
    '''
    # download WMS image for the study area
    # consider spliting large area - high resolution/large data may end with download failure
    pixsize = 0.0002  # put the desired resolution (in the SRS unit), 0.0002 deg = approx. 20m