<commit_before># Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

try:
    import simplejson as json
except:
    import json

from libcloud.utils.py3 import httplib, urlparse
from libcloud.common.types import MalformedResponseError, LibcloudError
from libcloud.common.types import LazyList
from libcloud.common.base import Response

from rackspace_monitoring.providers import Provider
from rackspace_monitoring.utils import to_underscore_separated
from rackspace_monitoring.utils import value_to_bool

from rackspace_monitoring.base import (MonitoringDriver, Entity,
                                       NotificationPlan, MonitoringZone,
                                       Notification, CheckType, Alarm, Check,
                                       NotificationType, AlarmChangelog,
                                       LatestAlarmState, Agent, AgentToken,
                                       AgentConnection, Metric, DataPoint)

from libcloud.common.rackspace import AUTH_URL_US
from libcloud.common.openstack import OpenStackBaseConnection
from libcloud.common.openstack import OpenStackDriverMixin


class RackspaceMonitoringValidationError(LibcloudError):

    def __init__(self, code, type, message, details, driver):
        self.code = code
        self.type = type
        self.message = message
        self.details = details
        super(RackspaceMonitoringValidationError, self).__init__(value=message,
                                                                 driver=driver)

    def __str__(self):
        return self.__repr__()

    def __repr__(self):
        string = '<ValidationError type=%s, ' % (self.type)
        string += 'message="%s", details=%s>' % (self.message, self.details)
        return string.encode('utf-8')


class RackspaceMonitoringResponse(Response):

    valid_response_codes = [httplib.CONFLICT]

    def success(self):
        i = int(self.status)
        return i >= 200 and i <= 299 or i in self.valid_response_codes

    def parse_body(self):
        if not self.body:
            return None

        if 'content-type' in self.headers:
            key = 'content-type'
        elif 'Content-Type' in self.headers:
            key = 'Content-Type'
        else:
            raise LibcloudError('Missing content-type header')

        content_type = self.headers[key]
        if content_type.find(';') != -1:
            content_type = content_type.split(';')[0]

        if content_type == 'application/json':
            try:
                data = json.loads(self.body)
            except:
                raise MalformedResponseError('Failed to parse JSON',
                                             body=self.body,
                                             driver=RackspaceMonitoringDriver)
        elif content_type == 'text/plain':
            data = self.body
        else:
            data = self.body

        return data

    def parse_error(self):
        body = self.parse_body()
        if self.status == httplib.BAD_REQUEST:
            error = RackspaceMonitoringValidationError(message=body['message'],
                                                       code=body['code'],
                                                       type=body['type'],
                                                       details=body['details'],
                                                   driver=self.connection.driver)
            raise error

        return body


class RackspaceMonitoringConnection(OpenStackBaseConnection):
    """
    Base connection class for the Rackspace Monitoring driver.
    """

    type = Provider.RACKSPACE
    responseCls = RackspaceMonitoringResponse
    auth_url = AUTH_URL_US

    service_name = 'cloudMonitoring'
    service_type = 'rax:monitor'

    def __init__(self, user_id, key, secure=False, ex_force_base_url=None,
                 ex_force_auth_url=None, ex_force_auth_version='2.0',
                 ex_force_auth_token=None):
        self.accept_format = 'application/json'
        super(RackspaceMonitoringConnection, self).__init__(user_id, key,
                                secure=secure,
                                ex_force_base_url=ex_force_base_url,
                                ex_force_auth_url=ex_force_auth_url,
                                ex_force_auth_version=ex_force_auth_version,
                                ex_force_auth_token=ex_force_auth_token)

    def request(self, action, params=None, data='', headers=None, method='GET',
                raw=False):
        if not headers:
            headers = {}
        if not params:
            params = {}

        headers['Accept'] = 'application/json'

        if method in ['POST', 'PUT']:
            headers['Content-Type'] = 'application/json; charset=UTF-8'
            data = json.dumps(data)

        return super(RackspaceMonitoringConnection, self).request(
            action=action,
            params=params, data=data,
            method=method, headers=headers,
            raw=raw
        )


class RackspaceMonitoringDriver(MonitoringDriver, OpenStackDriverMixin):
    """
    Base Rackspace Monitoring driver.

    """
    name = 'Rackspace Monitoring'
    connectionCls = RackspaceMonitoringConnection

    def __init__(self, *args, **kwargs):
        # Remove trailing slash from the ex_force_base_url
        if 'ex_force_base_url' in kwargs:
            if kwargs['ex_force_base_url'][-1] == '/':
                kwargs['ex_force_base_url'] = kwargs['ex_force_base_url'][:-1]

        OpenStackDriverMixin.__init__(self, *args, **kwargs)
        super(RackspaceMonitoringDriver, self).__init__(*args, **kwargs)

        # Don't require user to pass in tenant id if specifying a custom api
        # url
        ex_force_base_url = kwargs.pop('ex_force_base_url', None)
        ex_force_auth_token = kwargs.pop('ex_force_auth_token', None)

        if ex_force_base_url and not ex_force_auth_token:
            self.connection._populate_hosts_and_request_paths()
            ep = self.connection.service_catalog \
                     .get_endpoint(name=self.connection.service_name,
                                   service_type=self.connection.service_type,
                                   region=None)

            tenant_id = ep['tenantId']
            self.connection._ex_force_base_url = '%s/%s' % (<commit_msg>Refactor it in a separate method.<commit_after># Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

try:
    import simplejson as json
except:
    import json

from libcloud.utils.py3 import httplib, urlparse
from libcloud.common.types import MalformedResponseError, LibcloudError
from libcloud.common.types import LazyList
from libcloud.common.base import Response

from rackspace_monitoring.providers import Provider
from rackspace_monitoring.utils import to_underscore_separated
from rackspace_monitoring.utils import value_to_bool

from rackspace_monitoring.base import (MonitoringDriver, Entity,
                                       NotificationPlan, MonitoringZone,
                                       Notification, CheckType, Alarm, Check,
                                       NotificationType, AlarmChangelog,
                                       LatestAlarmState, Agent, AgentToken,
                                       AgentConnection, Metric, DataPoint)

from libcloud.common.rackspace import AUTH_URL_US
from libcloud.common.openstack import OpenStackBaseConnection
from libcloud.common.openstack import OpenStackDriverMixin


class RackspaceMonitoringValidationError(LibcloudError):

    def __init__(self, code, type, message, details, driver):
        self.code = code
        self.type = type
        self.message = message
        self.details = details
        super(RackspaceMonitoringValidationError, self).__init__(value=message,
                                                                 driver=driver)

    def __str__(self):
        return self.__repr__()

    def __repr__(self):
        string = '<ValidationError type=%s, ' % (self.type)
        string += 'message="%s", details=%s>' % (self.message, self.details)
        return string.encode('utf-8')


class RackspaceMonitoringResponse(Response):

    valid_response_codes = [httplib.CONFLICT]

    def success(self):
        i = int(self.status)
        return i >= 200 and i <= 299 or i in self.valid_response_codes

    def parse_body(self):
        if not self.body:
            return None

        if 'content-type' in self.headers:
            key = 'content-type'
        elif 'Content-Type' in self.headers:
            key = 'Content-Type'
        else:
            raise LibcloudError('Missing content-type header')

        content_type = self.headers[key]
        if content_type.find(';') != -1:
            content_type = content_type.split(';')[0]

        if content_type == 'application/json':
            try:
                data = json.loads(self.body)
            except:
                raise MalformedResponseError('Failed to parse JSON',
                                             body=self.body,
                                             driver=RackspaceMonitoringDriver)
        elif content_type == 'text/plain':
            data = self.body
        else:
            data = self.body

        return data

    def parse_error(self):
        body = self.parse_body()
        if self.status == httplib.BAD_REQUEST:
            error = RackspaceMonitoringValidationError(message=body['message'],
                                                       code=body['code'],
                                                       type=body['type'],
                                                       details=body['details'],
                                                   driver=self.connection.driver)
            raise error

        return body


class RackspaceMonitoringConnection(OpenStackBaseConnection):
    """
    Base connection class for the Rackspace Monitoring driver.
    """

    type = Provider.RACKSPACE
    responseCls = RackspaceMonitoringResponse
    auth_url = AUTH_URL_US

    service_name = 'cloudMonitoring'
    service_type = 'rax:monitor'

    def __init__(self, user_id, key, secure=False, ex_force_base_url=None,
                 ex_force_auth_url=None, ex_force_auth_version='2.0',
                 ex_force_auth_token=None):
        self.accept_format = 'application/json'
        super(RackspaceMonitoringConnection, self).__init__(user_id, key,
                                secure=secure,
                                ex_force_base_url=ex_force_base_url,
                                ex_force_auth_url=ex_force_auth_url,
                                ex_force_auth_version=ex_force_auth_version,
                                ex_force_auth_token=ex_force_auth_token)

    def request(self, action, params=None, data='', headers=None, method='GET',
                raw=False):
        if not headers:
            headers = {}
        if not params:
            params = {}

        headers['Accept'] = 'application/json'

        if method in ['POST', 'PUT']:
            headers['Content-Type'] = 'application/json; charset=UTF-8'
            data = json.dumps(data)

        return super(RackspaceMonitoringConnection, self).request(
            action=action,
            params=params, data=data,
            method=method, headers=headers,
            raw=raw
        )


class RackspaceMonitoringDriver(MonitoringDriver, OpenStackDriverMixin):
    """
    Base Rackspace Monitoring driver.

    """
    name = 'Rackspace Monitoring'
    connectionCls = RackspaceMonitoringConnection

    def __init__(self, *args, **kwargs):
        # Remove trailing slash from the ex_force_base_url
        if 'ex_force_base_url' in kwargs:
            if kwargs['ex_force_base_url'][-1] == '/':
                kwargs['ex_force_base_url'] = kwargs['ex_force_base_url'][:-1]

        OpenStackDriverMixin.__init__(self, *args, **kwargs)
        super(RackspaceMonitoringDriver, self).__init__(*args, **kwargs)

        self._initialize_connection_base_url(constructor_kwargs=kwargs)

    def _initialize_connection_base_url(self, constructor_kwargs):
        # If user specifies a custom API url (ex_force_base_url variable),
        # don't require him to pass in tenant it and automatically retrieve it
        # from the service catalog.
        #
        # Note: If user specifies both ex_force_base_url and
        # ex_force_auth_token, ex_force_base_url must contain full URL
        # including a tenant id.
        ex_force_base_url = constructor_kwargs.pop('ex_force_base_url', None)
        ex_force_auth_token = constructor_kwargs.pop('ex_force_auth_token', None)

        if ex_force_base_url and not ex_force_auth_token:
            self.connection._populate_hosts_and_request_paths()
            ep = self.connection.service_catalog \
                     .get_endpoint(name=self.connection.service_name,
                                   service_type=self.connection.service_type,
                                   region=None)

            tenant_id = ep['tenantId']
            self.connection._ex_force_base_url = '%s/%s' % (
{'fraction_non_alphanumeric': 0.07828524545330234, 'fraction_numerical': 0.0025981129495419118, 'mean_word_length': 2.104202037351443, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 42, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1446954', 'n_tokens_mistral': 3808, 'n_tokens_neox': 3678, 'n_words': 949}