<commit_before># -*- coding: ISO-8859-15 -*-
# =============================================================================
# Copyright (c) 2004, 2006 <NAME>
# Copyright (c) 2007 STFC <http://www.stfc.ac.uk>
#
# Authors : 
#          <NAME> <<EMAIL>>
#
# Contact email: <EMAIL>
# =============================================================================

from wcsBase import WCSBase, WCSCapabilitiesReader, RereadableURL
from urllib import urlencode
from urllib2 import urlopen
from owslib.etree import etree
import os, errno

#  function to save writing out WCS namespace in full each time
def ns(tag):
    return '{http://www.opengis.net/wcs}'+tag

class ServiceException(Exception):
    pass


class WebCoverageService_1_0_0(WCSBase):
    """Abstraction for OGC Web Coverage Service (WCS), version 1.0.0
    Implements IWebCoverageService.
    """
    def __getitem__(self,name):
        ''' check contents dictionary to allow dict like access to service layers'''
        if name in self.__getattribute__('contents').keys():
            return self.__getattribute__('contents')[name]
        else:
            raise KeyError, "No content named %s" % name
    
    def __init__(self,url,xml):
        self.version='1.0.0'
        self.url = url   
        # initialize from saved capability document or access the server
        reader = WCSCapabilitiesReader(self.version)
        if xml:
            self._capabilities = reader.readString(xml)
        else:
            self._capabilities = reader.read(self.url)

        #serviceIdentification metadata
        subelem=self._capabilities.find(ns('Service/'))
        self.identification=ServiceIdenfication(subelem)                               
                   
        #serviceProvider metadata
        self.provider=None
        subelem=self._capabilities.find(ns('Service/')+ns('responsibleParty'))
        if subelem is not None:
            self.provider=ServiceProvider(subelem)   
        
        #serviceOperations metadata
        self.operations=[]
        for elem in self._capabilities.find(ns('Capability/')+ns('Request')).getchildren():
            self.operations.append(OperationMetadata(elem))
          
        #serviceContents metadata
        self.contents={}
        for elem in self._capabilities.findall(ns('ContentMetadata/')+ns('CoverageOfferingBrief')): 
            cm=ContentMetadata(elem, self)
            self.contents[cm.id]=cm
        
        #exceptions
        self.exceptions = [f.text for f \
                in self._capabilities.findall('Capability/Exception/Format')]
    
    
    def items(self):
        '''supports dict-like items() access'''
        items=[]
        for item in self.contents:
            items.append((item,self.contents[item]))
        return items
    
      
  
    def getCoverage(self, identifier=None, bbox=None, time=None, format = None,  crs=None, width=None, height=None, resx=None, resy=None, resz=None,parameter=None,method='Get',**kwargs):
        """Request and return a coverage from the WCS as a file-like object
        note: additional **kwargs helps with multi-version implementation
        core keyword arguments should be supported cross version
        example:
        cvg=wcs.getCoverage(identifier=['TuMYrRQ4'], timeSequence=['2792-06-01T00:00:00.0'], bbox=(-112,36,-106,41),format='cf-netcdf')

        is equivalent to:
        http://myhost/mywcs?SERVICE=WCS&REQUEST=GetCoverage&IDENTIFIER=TuMYrRQ4&VERSION=1.1.0&BOUNDINGBOX=-180,-90,180,90&TIMESEQUENCE=['2792-06-01T00:00:00.0']&FORMAT=cf-netcdf
           
        """
        
        self.log.debug('WCS 1.0.0 DEBUG: Parameters passed to GetCoverage: identifier=%s, bbox=%s, time=%s, format=%s, crs=%s, width=%s, height=%s, resx=%s, resy=%s, resz=%s, parameter=%s, method=%s, other_arguments=%s'%(identifier, bbox, time, format, crs, width, height, resx, resy, resz, parameter, method, str(kwargs)))
                
        base_url = self.getOperationByName('GetCoverage').methods[method]['url']
        
        self.log.debug('WCS 1.0.0 DEBUG: base url of server: %s'%base_url)
        
        #process kwargs
        request = {'version': self.version, 'request': 'GetCoverage', 'service':'WCS'}
        assert len(identifier) > 0
        request['Coverage']=identifier
        #request['identifier'] = ','.join(identifier)
        if bbox:
            request['BBox']=','.join([str(x) for x in bbox])
        else:
            request['BBox']=None
        if time:
            request['time']=','.join(time)
        if crs:
            request['crs']=crs
        request['format']=format
        if width:
            request['width']=width
        if height:
            request['height']=height
        if resx:
            request['resx']=resx
        if resy:
            request['resy']=resy
        if resz:
            request['resz']=resz
        
        #anything else e.g. vendor specific parameters must go through kwargs
        if kwargs:
            for kw in kwargs:
                request[kw]=kwargs[kw]
        
        #encode and request
        data = urlencode(request)
        self.log.debug('WCS 1.0.0 DEBUG: Second part of URL: %s'%data)
        try:
            u = urlopen(base_url+data)
            self.log.debug('WCS 1.0.0 DEBUG: called urlopen(base_url+data)')
        except:  
            u = urlopen(base_url, data=data)    
            self.log.debug('WCS 1.0.0 DEBUG: called urlopen(base_url, data=data)')
        
        self.log.debug('WCS 1.0.0 DEBUG: GetCoverage request made: %s'%u.url)
        self.log.debug('WCS 1.0.0 DEBUG: Headers returned: %s'%str(u.headers))
        # check for service exceptions, and return #TODO - test this bit properly.
        if u.info()['Content-Type'] == 'text/xml':          
            #going to have to read the xml to see if it's an exception report.
            #wrap the url stram in a extended StringIO object so it's re-readable<commit_msg>some servers set the http header to 400 when returning an OGC service exception. This trips up urllib2.urlopen. Changed wcs to report back service exception message.<commit_after># -*- coding: ISO-8859-15 -*-
# =============================================================================
# Copyright (c) 2004, 2006 <NAME>
# Copyright (c) 2007 STFC <http://www.stfc.ac.uk>
#
# Authors : 
#          <NAME> <<EMAIL>>
#
# Contact email: <EMAIL>
# =============================================================================

from wcsBase import WCSBase, WCSCapabilitiesReader, RereadableURL
from urllib import urlencode
from urllib2 import urlopen, HTTPError
from owslib.etree import etree
import os, errno

#  function to save writing out WCS namespace in full each time
def ns(tag):
    return '{http://www.opengis.net/wcs}'+tag

class ServiceException(Exception):
    pass


class WebCoverageService_1_0_0(WCSBase):
    """Abstraction for OGC Web Coverage Service (WCS), version 1.0.0
    Implements IWebCoverageService.
    """
    def __getitem__(self,name):
        ''' check contents dictionary to allow dict like access to service layers'''
        if name in self.__getattribute__('contents').keys():
            return self.__getattribute__('contents')[name]
        else:
            raise KeyError, "No content named %s" % name
    
    def __init__(self,url,xml):
        self.version='1.0.0'
        self.url = url   
        # initialize from saved capability document or access the server
        reader = WCSCapabilitiesReader(self.version)
        if xml:
            self._capabilities = reader.readString(xml)
        else:
            self._capabilities = reader.read(self.url)

        #serviceIdentification metadata
        subelem=self._capabilities.find(ns('Service/'))
        self.identification=ServiceIdenfication(subelem)                               
                   
        #serviceProvider metadata
        self.provider=None
        subelem=self._capabilities.find(ns('Service/')+ns('responsibleParty'))
        if subelem is not None:
            self.provider=ServiceProvider(subelem)   
        
        #serviceOperations metadata
        self.operations=[]
        for elem in self._capabilities.find(ns('Capability/')+ns('Request')).getchildren():
            self.operations.append(OperationMetadata(elem))
          
        #serviceContents metadata
        self.contents={}
        for elem in self._capabilities.findall(ns('ContentMetadata/')+ns('CoverageOfferingBrief')): 
            cm=ContentMetadata(elem, self)
            self.contents[cm.id]=cm
        
        #exceptions
        self.exceptions = [f.text for f \
                in self._capabilities.findall('Capability/Exception/Format')]
    
    
    def items(self):
        '''supports dict-like items() access'''
        items=[]
        for item in self.contents:
            items.append((item,self.contents[item]))
        return items
    
      
  
    def getCoverage(self, identifier=None, bbox=None, time=None, format = None,  crs=None, width=None, height=None, resx=None, resy=None, resz=None,parameter=None,method='Get',**kwargs):
        """Request and return a coverage from the WCS as a file-like object
        note: additional **kwargs helps with multi-version implementation
        core keyword arguments should be supported cross version
        example:
        cvg=wcs.getCoverage(identifier=['TuMYrRQ4'], timeSequence=['2792-06-01T00:00:00.0'], bbox=(-112,36,-106,41),format='cf-netcdf')

        is equivalent to:
        http://myhost/mywcs?SERVICE=WCS&REQUEST=GetCoverage&IDENTIFIER=TuMYrRQ4&VERSION=1.1.0&BOUNDINGBOX=-180,-90,180,90&TIMESEQUENCE=['2792-06-01T00:00:00.0']&FORMAT=cf-netcdf
           
        """
        
        self.log.debug('WCS 1.0.0 DEBUG: Parameters passed to GetCoverage: identifier=%s, bbox=%s, time=%s, format=%s, crs=%s, width=%s, height=%s, resx=%s, resy=%s, resz=%s, parameter=%s, method=%s, other_arguments=%s'%(identifier, bbox, time, format, crs, width, height, resx, resy, resz, parameter, method, str(kwargs)))
                
        base_url = self.getOperationByName('GetCoverage').methods[method]['url']
        
        self.log.debug('WCS 1.0.0 DEBUG: base url of server: %s'%base_url)
        
        #process kwargs
        request = {'version': self.version, 'request': 'GetCoverage', 'service':'WCS'}
        assert len(identifier) > 0
        request['Coverage']=identifier
        #request['identifier'] = ','.join(identifier)
        if bbox:
            request['BBox']=','.join([str(x) for x in bbox])
        else:
            request['BBox']=None
        if time:
            request['time']=','.join(time)
        if crs:
            request['crs']=crs
        request['format']=format
        if width:
            request['width']=width
        if height:
            request['height']=height
        if resx:
            request['resx']=resx
        if resy:
            request['resy']=resy
        if resz:
            request['resz']=resz
        
        #anything else e.g. vendor specific parameters must go through kwargs
        if kwargs:
            for kw in kwargs:
                request[kw]=kwargs[kw]
        
        #encode and request
        data = urlencode(request)
        self.log.debug('WCS 1.0.0 DEBUG: Second part of URL: %s'%data)
        
        try:
            u = urlopen(base_url + data)
        except HTTPError, e: #Some servers may set the http header to 400 if returning an OGC service exception.
            if e.code == 400:
                raise ServiceException, e.read()+data
  
        
        self.log.debug('WCS 1.0.0 DEBUG: GetCoverage request made: %s'%u.url)
        self.log.debug('WCS 1.0.0 DEBUG: Headers returned: %s'%str(u.headers))
        # check for service exceptions, and return #TODO - test this bit properly.
        if u.info()['Content-Type'] == 'text/xml':          
            #just in case 400 headers were not set, going to have to read the xml to see if it's an exception report.
            #wrap the url stram in a extended StringIO object so it's re-readable
{'fraction_non_alphanumeric': 0.1434012253684385, 'fraction_numerical': 0.017966550753436, 'mean_word_length': 2.5082776648271854, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 10}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1650205', 'n_tokens_mistral': 3666, 'n_tokens_neox': 3490, 'n_words': 863}