# Path: monasca_api/v2/common/exceptions.py
# class HTTPUnprocessableEntityError(HTTPError):
#     def __init__(self, title, description, **kwargs):
#         HTTPError.__init__(self, '422 Unprocessable Entity', title, description, **kwargs)
# 
# Path: monasca_api/v2/common/validation.py
# VALID_ALARM_STATES = ["ALARM", "OK", "UNDETERMINED"]
# VALID_ALARM_DEFINITION_SEVERITIES = ["LOW", "MEDIUM", "HIGH", "CRITICAL"]
# EMAIL_PATTERN = '^.+@.+$'
# def validate_alarm_state(state):
# def validate_alarm_definition_severity(severity):
# def validate_severity_query(severity_str):
# def validate_sort_by(sort_by_list, allowed_sort_by):
# def validate_email_address(email):
# 
# Path: monasca_api/v2/reference/alarming.py
# LOG = log.getLogger(__name__)
# class Alarming(object):
#     def __init__(self):
#     def _send_alarm_transitioned_event(self, tenant_id, alarm_id,
#                                        alarm_definition_row,
#                                        alarm_metric_rows,
#                                        old_state, new_state,
#                                        link, lifecycle_state,
#                                        time_ms):
#     def _build_metric(self, alarm_metric_row):
#     def _send_alarm_event(self, event_type, tenant_id, alarm_definition_id,
#                           alarm_metric_rows, sub_alarm_rows, link, lifecycle_state,
#                           extra_info=None):
#     def _build_sub_alarm_event_msg(self, sub_alarm_dict, alarm_id):
#     def send_event(self, message_queue, event_msg):
# 
# Path: monasca_api/v2/reference/helpers.py
# LOG = log.getLogger(__name__)
# CONF = conf.CONF
# def from_json(req):
# def to_json(data):
# def validate_json_content_type(req):
# def validate_authorization(http_request, authorized_rules_list):
# def validate_payload_size(content_length):
# def get_x_tenant_or_tenant_id(http_request, delegate_authorized_rules_list):
# def get_query_param(req, param_name, required=False, default_val=None):
# def get_query_name(req, name_required=False):
# def get_query_dimensions(req, param_key='dimensions'):
# def get_query_starttime_timestamp(req, required=True):
# def get_query_endtime_timestamp(req, required=True):
# def validate_start_end_timestamps(start_timestamp, end_timestamp=None):
# def _convert_time_string(date_time_string):
# def get_query_statistics(req):
# def get_query_period(req):
# def get_query_group_by(req):
# def validate_query_name(name):
# def validate_query_dimensions(dimensions):
# def paginate(resource, uri, limit):
# def paginate_with_no_id(dictionary_list, uri, offset, limit):
# def _truncate_with_offset(resource, value_list, offset):
# def paginate_alarming(resource, uri, limit):
# def paginate_dimension_values(dimvals, uri, offset, limit):
# def _truncate_dimension_values(values, limit, offset):
# def paginate_measurements(measurements, uri, limit):
# def _get_old_query_params(parsed_uri):
# def _get_old_query_params_except_offset(new_query_params, parsed_uri):
# def paginate_statistics(statistics, uri, limit):
# def create_alarms_count_next_link(uri, offset, limit):
# def build_base_uri(parsed_uri):
# def get_link(uri, resource_id, rel='self'):
# def add_links_to_resource(resource, uri, rel='self'):
# def add_links_to_resource_list(resourcelist, uri):
# def raise_not_found_exception(resource_name, resource_id, tenant_id):
# def str_2_bool(s):


import re
import falcon
import six
from monasca_common.simport import simport
from oslo_config import cfg
from oslo_log import log
from monasca_api.api import alarms_api_v2
from monasca_api.common.repositories import exceptions
from monasca_api.v2.common.exceptions import HTTPUnprocessableEntityError
from monasca_api.v2.common.schemas import alarm_update_schema as schema_alarm
from monasca_api.v2.common import validation
from monasca_api.v2.reference import alarming
from monasca_api.v2.reference import helpers
from monasca_api.v2.reference import resource

LOG = log.getLogger(__name__)


class Alarms(alarms_api_v2.AlarmsV2API,
             alarming.Alarming):
    def __init__(self):
        try:
            super(Alarms, self).__init__()
            self._region = cfg.CONF.region
            self._alarms_repo = simport.load(
                cfg.CONF.repositories.alarms_driver)()

        except Exception as ex:
            LOG.exception(ex)
            raise exceptions.RepositoryException(ex)

    @resource.resource_try_catch_block
    def on_put(self, req, res, alarm_id):

        helpers.validate_authorization(req, ['api:alarms:put'])

        alarm = helpers.from_json(req)
        schema_alarm.validate(alarm)

        # Validator makes state optional, so check it here
        if 'state' not in alarm or not alarm['state']:
            raise HTTPUnprocessableEntityError('Unprocessable Entity',
                                               "Field 'state' is required")
        if 'lifecycle_state' not in alarm or not alarm['lifecycle_state']:

# Path: monasca_api/v2/common/exceptions.py
# class HTTPUnprocessableEntityError(HTTPError):
#     def __init__(self, title, description, **kwargs):
#         HTTPError.__init__(self, '422 Unprocessable Entity', title, description, **kwargs)
# 
# Path: monasca_api/v2/common/validation.py
# VALID_ALARM_STATES = ["ALARM", "OK", "UNDETERMINED"]
# VALID_ALARM_DEFINITION_SEVERITIES = ["LOW", "MEDIUM", "HIGH", "CRITICAL"]
# EMAIL_PATTERN = '^.+@.+$'
# def validate_alarm_state(state):
# def validate_alarm_definition_severity(severity):
# def validate_severity_query(severity_str):
# def validate_sort_by(sort_by_list, allowed_sort_by):
# def validate_email_address(email):
# 
# Path: monasca_api/v2/reference/alarming.py
# LOG = log.getLogger(__name__)
# class Alarming(object):
#     def __init__(self):
#     def _send_alarm_transitioned_event(self, tenant_id, alarm_id,
#                                        alarm_definition_row,
#                                        alarm_metric_rows,
#                                        old_state, new_state,
#                                        link, lifecycle_state,
#                                        time_ms):
#     def _build_metric(self, alarm_metric_row):
#     def _send_alarm_event(self, event_type, tenant_id, alarm_definition_id,
#                           alarm_metric_rows, sub_alarm_rows, link, lifecycle_state,
#                           extra_info=None):
#     def _build_sub_alarm_event_msg(self, sub_alarm_dict, alarm_id):
#     def send_event(self, message_queue, event_msg):
# 
# Path: monasca_api/v2/reference/helpers.py
# LOG = log.getLogger(__name__)
# CONF = conf.CONF
# def from_json(req):
# def to_json(data):
# def validate_json_content_type(req):
# def validate_authorization(http_request, authorized_rules_list):
# def validate_payload_size(content_length):
# def get_x_tenant_or_tenant_id(http_request, delegate_authorized_rules_list):
# def get_query_param(req, param_name, required=False, default_val=None):
# def get_query_name(req, name_required=False):
# def get_query_dimensions(req, param_key='dimensions'):
# def get_query_starttime_timestamp(req, required=True):
# def get_query_endtime_timestamp(req, required=True):
# def validate_start_end_timestamps(start_timestamp, end_timestamp=None):
# def _convert_time_string(date_time_string):
# def get_query_statistics(req):
# def get_query_period(req):
# def get_query_group_by(req):
# def validate_query_name(name):
# def validate_query_dimensions(dimensions):
# def paginate(resource, uri, limit):
# def paginate_with_no_id(dictionary_list, uri, offset, limit):
# def _truncate_with_offset(resource, value_list, offset):
# def paginate_alarming(resource, uri, limit):
# def paginate_dimension_values(dimvals, uri, offset, limit):
# def _truncate_dimension_values(values, limit, offset):
# def paginate_measurements(measurements, uri, limit):
# def _get_old_query_params(parsed_uri):
# def _get_old_query_params_except_offset(new_query_params, parsed_uri):
# def paginate_statistics(statistics, uri, limit):
# def create_alarms_count_next_link(uri, offset, limit):
# def build_base_uri(parsed_uri):
# def get_link(uri, resource_id, rel='self'):
# def add_links_to_resource(resource, uri, rel='self'):
# def add_links_to_resource_list(resourcelist, uri):
# def raise_not_found_exception(resource_name, resource_id, tenant_id):
# def str_2_bool(s):


# Path: monasca_api/v2/reference/alarms.py
import re
import falcon
import six
from monasca_common.simport import simport
from oslo_config import cfg
from oslo_log import log
from monasca_api.api import alarms_api_v2
from monasca_api.common.repositories import exceptions
from monasca_api.v2.common.exceptions import HTTPUnprocessableEntityError
from monasca_api.v2.common.schemas import alarm_update_schema as schema_alarm
from monasca_api.v2.common import validation
from monasca_api.v2.reference import alarming
from monasca_api.v2.reference import helpers
from monasca_api.v2.reference import resource


LOG = log.getLogger(__name__)


class Alarms(alarms_api_v2.AlarmsV2API,
             alarming.Alarming):
    def __init__(self):
        try:
            super(Alarms, self).__init__()
            self._region = cfg.CONF.region
            self._alarms_repo = simport.load(
                cfg.CONF.repositories.alarms_driver)()

        except Exception as ex:
            LOG.exception(ex)
            raise exceptions.RepositoryException(ex)

    @resource.resource_try_catch_block
    def on_put(self, req, res, alarm_id):

        helpers.validate_authorization(req, ['api:alarms:put'])

        alarm = helpers.from_json(req)
        schema_alarm.validate(alarm)

        # Validator makes state optional, so check it here
        if 'state' not in alarm or not alarm['state']:
            raise HTTPUnprocessableEntityError('Unprocessable Entity',
                                               "Field 'state' is required")
        if 'lifecycle_state' not in alarm or not alarm['lifecycle_state']:

            raise HTTPUnprocessableEntityError('Unprocessable Entity',