def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to save a new Rule

        URL: rule/save/
        """
        try:
            self.log.info('Save rule to an environment')

            # User permission
            if not has_perm(user, AdminPermission.VIP_VALIDATION, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'There is no value to the networkapi tag  of XML request.')

            rule_map = networkapi_map.get('map')
            if rule_map is None:
                return self.response_error(3, u'There is no value to the environment_vip tag  of XML request.')

            # Get XML data
            id_env = rule_map['id_env']
            name = rule_map['name']
            contents = rule_map['contents'] if type(
                rule_map['contents']) is list else [rule_map['contents'], ]
            blocks_id = rule_map['blocks_id'] if type(
                rule_map['blocks_id']) is list else [rule_map['blocks_id'], ]

            if not is_valid_int_greater_zero_param(id_env):
                self.log.error(
                    u'The id_env parameter is not a valid value: %s.', id_env)
                raise InvalidValueError(None, 'id_env', id_env)

            if not name or len(name) > 80:
                self.log.error(
                    u'The name parameter is not a valid value: %s.', name)
                raise InvalidValueError(None, 'name', name)

            environment = Ambiente.get_by_pk(id_env)

            new_rule = Rule()
            new_rule.name = name
            new_rule.environment = environment
            new_rule.save()

            self.__save_rule_contents(
                contents, blocks_id, environment, new_rule, user)

            return self.response(dumps_networkapi({}))

        except AmbienteNotFoundError, e:
            self.log.error('Environment not found')
            return self.response_error(112)
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to save a new Rule

        URL: rule/save/
        """
        try:
            self.log.info("Save rule to an environment")

            # User permission
            if not has_perm(user, AdminPermission.VIP_VALIDATION, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'There is no value to the networkapi tag  of XML request.')

            rule_map = networkapi_map.get('map')
            if rule_map is None:
                return self.response_error(3, u'There is no value to the environment_vip tag  of XML request.')

            # Get XML data
            id_env = rule_map['id_env']
            name = rule_map['name']
            contents = rule_map['contents'] if type(
                rule_map['contents']) is list else [rule_map['contents'], ]
            blocks_id = rule_map['blocks_id'] if type(
                rule_map['blocks_id']) is list else [rule_map['blocks_id'], ]

            if not is_valid_int_greater_zero_param(id_env):
                self.log.error(
                    u'The id_env parameter is not a valid value: %s.', id_env)
                raise InvalidValueError(None, 'id_env', id_env)

            if not name or len(name) > 80:
                self.log.error(
                    u'The name parameter is not a valid value: %s.', name)
                raise InvalidValueError(None, 'name', name)

            environment = Ambiente.get_by_pk(id_env)

            new_rule = Rule()
            new_rule.name = name
            new_rule.environment = environment
            new_rule.save()

            self.__save_rule_contents(
                contents, blocks_id, environment, new_rule, user)

            return self.response(dumps_networkapi({}))

        except AmbienteNotFoundError, e:
            self.log.error('Environment not found')
            return self.response_error(112)
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to add block in vip rule.

        URLs: /vip/add_block/<id_vip>/<id_block>/<override>
        """

        self.log.info('Add block in rule vip')

        try:
            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VIP_ALTER_SCRIPT,
                            AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations
            id_vip = kwargs.get('id_vip')
            id_block = kwargs.get('id_block')
            override = kwargs.get('override')

            if not is_valid_int_greater_zero_param(id_vip):
                self.log.error(u'Parameter id_vip is invalid. Value: %s.',
                               id_vip)
                raise InvalidValueError(None, 'id_vip', id_vip)

            if not is_valid_int_greater_zero_param(id_block):
                self.log.error(u'Parameter id_block is invalid. Value: %s.',
                               id_block)
                raise InvalidValueError(None, 'id_block', id_block)

            if not is_valid_boolean_param(override, False):
                self.log.error(u'Parameter override is invalid. Value: %s.',
                               override)
                raise InvalidValueError(None, 'override', override)
            else:
                override = convert_string_or_int_to_boolean(override)

            vip = RequisicaoVips.get_by_pk(id_vip)
            vip_map = vip.variables_to_map()
            host = vip_map['host']
            rule_applied = vip.rule_applied

            # Vip must be created
            if not vip.vip_criado:
                self.log.error(
                    u'Block can not added because VIP has not been created yet.'
                )
                raise RequestVipsNotBeenCreatedError(None)

            ###################################################
            #         Vip Request has a rule applied          #
            ###################################################
            if rule_applied:
                block_in_rules = self.insert_block_in_rule(
                    id_block, rule_applied)

                # create new rule
                # make a copy
                new_rule_content = copy.copy(rule_applied)

                # remove the rule if is a vip rule and this rule is not applied
                if vip.rule:
                    if rule_applied != vip.rule and vip.rule.vip:
                        vip.rule.delete()

                # duplicate rule with new block
                new_rule_content.id = None
                new_rule_content.vip = vip
                count_rule_vip = Rule.objects.filter(vip=vip).count()
                diff_name = '(' + str(count_rule_vip) + \
                    ')' if count_rule_vip else ''
                new_rule_content.name = 'regra_' + host + diff_name
                new_rule_content.save(user, force_insert=True)

            ###################################################
            #        Vip Request hasn't a rule applied        #
            ###################################################
            else:
                block_in_rules, environment = self.generate_rule_contents(
                    vip, id_block)

                # create new rule
                new_rule_content = Rule()
                count_rule_vip = Rule.objects.filter(vip=vip).count()
                diff_name = '(' + str(count_rule_vip) + \
                    ')' if count_rule_vip else ''
                new_rule_content.name = 'regra_' + host + diff_name
                new_rule_content.vip = vip
                new_rule_content.environment = environment
                new_rule_content.save()

            new_content = '\n'.join(d['content'] for d in block_in_rules)

            # save contents with new rule
            for i in range(len(block_in_rules)):
                rule_content = RuleContent()
                rule_content.content = block_in_rules[i]['content']
                rule_content.order = i
                rule_content.rule = new_rule_content
                rule_content.save()

            if override or not vip.l7_filter:
                # update filter and rule with new block
                vip.l7_filter = new_content
                vip.rule = new_rule_content
                vip.filter_valid = True
                vip.save()
            else:
                self.log.error(
                    u'Block can not be added because there is already a rule to apply, and the value of zero is overwritten.'
                )
                raise AddBlockOverrideNotDefined(None)

            success_map = dict()
            success_map['codigo'] = 0
            success_map['descricao'] = u'Bloco incluído com sucesso'

            return self.response(dumps_networkapi({'sucesso': success_map}))

        except VipRequestBlockAlreadyInRule, e:
            self.log.error(e.message)
            return self.response_error(361)
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to add block in vip rule.

        URLs: /vip/add_block/<id_vip>/<id_block>/<override>
        """

        self.log.info('Add block in rule vip')

        try:
            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VIP_ALTER_SCRIPT, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations
            id_vip = kwargs.get('id_vip')
            id_block = kwargs.get('id_block')
            override = kwargs.get('override')

            if not is_valid_int_greater_zero_param(id_vip):
                self.log.error(
                    u'Parameter id_vip is invalid. Value: %s.', id_vip)
                raise InvalidValueError(None, 'id_vip', id_vip)

            if not is_valid_int_greater_zero_param(id_block):
                self.log.error(
                    u'Parameter id_block is invalid. Value: %s.', id_block)
                raise InvalidValueError(None, 'id_block', id_block)

            if not is_valid_boolean_param(override, False):
                self.log.error(
                    u'Parameter override is invalid. Value: %s.', override)
                raise InvalidValueError(None, 'override', override)
            else:
                override = convert_string_or_int_to_boolean(override)

            vip = RequisicaoVips.get_by_pk(id_vip)
            vip_map = vip.variables_to_map()
            host = vip_map['host']
            rule_applied = vip.rule_applied

            # Vip must be created
            if not vip.vip_criado:
                self.log.error(
                    u'Block can not added because VIP has not been created yet.')
                raise RequestVipsNotBeenCreatedError(None)

            ###################################################
            #         Vip Request has a rule applied          #
            ###################################################
            if rule_applied:
                block_in_rules = self.insert_block_in_rule(
                    id_block, rule_applied)

                # create new rule
                # make a copy
                new_rule_content = copy.copy(rule_applied)

                # remove the rule if is a vip rule and this rule is not applied
                if vip.rule:
                    if rule_applied != vip.rule and vip.rule.vip:
                        vip.rule.delete()

                # duplicate rule with new block
                new_rule_content.id = None
                new_rule_content.vip = vip
                count_rule_vip = Rule.objects.filter(vip=vip).count()
                diff_name = '(' + str(count_rule_vip) + \
                    ')' if count_rule_vip else ''
                new_rule_content.name = 'regra_' + host + diff_name
                new_rule_content.save(user, force_insert=True)

            ###################################################
            #        Vip Request hasn't a rule applied        #
            ###################################################
            else:
                block_in_rules, environment = self.generate_rule_contents(
                    vip, id_block)

                # create new rule
                new_rule_content = Rule()
                count_rule_vip = Rule.objects.filter(vip=vip).count()
                diff_name = '(' + str(count_rule_vip) + \
                    ')' if count_rule_vip else ''
                new_rule_content.name = 'regra_' + host + diff_name
                new_rule_content.vip = vip
                new_rule_content.environment = environment
                new_rule_content.save()

            new_content = '\n'.join(d['content'] for d in block_in_rules)

            # save contents with new rule
            for i in range(len(block_in_rules)):
                rule_content = RuleContent()
                rule_content.content = block_in_rules[i]['content']
                rule_content.order = i
                rule_content.rule = new_rule_content
                rule_content.save()

            if override or not vip.l7_filter:
                # update filter and rule with new block
                vip.l7_filter = new_content
                vip.rule = new_rule_content
                vip.filter_valid = True
                vip.save()
            else:
                self.log.error(
                    u'Block can not be added because there is already a rule to apply, and the value of zero is overwritten.')
                raise AddBlockOverrideNotDefined(None)

            success_map = dict()
            success_map['codigo'] = 0
            success_map['descricao'] = u'Bloco incluído com sucesso'

            return self.response(dumps_networkapi({'sucesso': success_map}))

        except VipRequestBlockAlreadyInRule, e:
            self.log.error(e.message)
            return self.response_error(361)