<commit_before># Copyright 2012,  <NAME>,  NTT MCL,  Inc.
# All rights reserved.

# Licensed 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.

"""
Forms for starting Watcher Audits.
"""
import logging

from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _

from horizon import exceptions
from horizon import forms
from horizon import messages

from watcher_dashboard.api import watcher

LOG = logging.getLogger(__name__)


class CreateForm(forms.SelfHandlingForm):
    audit_template = forms.ChoiceField(label=_("Audit Template"))
    audit_type = forms.ChoiceField(label=_("Audit Type"),
                                   choices=[(None, _("Select Audit Type")),
                                            ('oneshot', _('ONESHOT')),
                                            ('continuous', _('CONTINUOUS'))],
                                   widget=forms.Select(attrs={
                                       'class': 'switchable',
                                       'data-slug': 'audit_type'
                                   }))
    interval = forms.DurationField(initial="01:00:00",
                                   label=_("Interval (format hh:mm:ss)"),
                                   help_text=_("Interval in format hh:mm:ss "
                                               "for CONTINUOUS audit"),
                                   widget=forms.TextInput(attrs={
                                       'class': 'switched',
                                       'data-switch-on': 'audit_type',
                                       'data-audit_type-continuous':
                                       _("Interval (format hh:mm:ss)")}))
    failure_url = 'horizon:admin:audits:index'
    auto_trigger = forms.BooleanField(label=_("Auto Trigger"),
                                      required=False)

    def __init__(self, request, *args, **kwargs):
        super(CreateForm, self).__init__(request, *args, **kwargs)
        audit_templates = self._get_audit_template_list(request)

        if audit_templates:
            self.fields['audit_template'].choices = audit_templates
        else:
            del self.fields['audit_template']

    def _get_audit_template_list(self, request):
        try:
            audit_templates = watcher.AuditTemplate.list(self.request)
        except Exception:
            msg = _('Failed to get audit template list.')
            LOG.info(msg)
            messages.warning(request, msg)
            audit_templates = []

        choices = [
            (audit_template.uuid, audit_template.name or audit_template.uuid)
            for audit_template in audit_templates
        ]

        if choices:
            choices.insert(0, ("", _("Select Audit Template")))
        return choices

    def handle(self, request, data):
        try:
            params = {'audit_template_uuid': data['audit_template']}
            params['audit_type'] = data['audit_type'].upper()
            params['auto_trigger'] = data['auto_trigger']
            if data['audit_type'] == 'continuous':
                params['interval'] = int(data['interval'].total_seconds())
            else:
                params['interval'] = None
            audit = watcher.Audit.create(request, **params)
            message = _('Audit was successfully created.')
            messages.success(request, message)
            return audit
        except Exception as exc:
            if exc.http_status == 409:
                msg = _('Quota exceeded for resource audit.')
            else:<commit_msg>Fix exception error when creating audit without audit template<commit_after># Copyright 2012,  <NAME>,  NTT MCL,  Inc.
# All rights reserved.

# Licensed 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.

"""
Forms for starting Watcher Audits.
"""
import logging

from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _

from horizon import exceptions
from horizon import forms
from horizon import messages

from watcher_dashboard.api import watcher

LOG = logging.getLogger(__name__)


class CreateForm(forms.SelfHandlingForm):
    audit_template = forms.ChoiceField(label=_("Audit Template"))
    audit_type = forms.ChoiceField(label=_("Audit Type"),
                                   choices=[(None, _("Select Audit Type")),
                                            ('oneshot', _('ONESHOT')),
                                            ('continuous', _('CONTINUOUS'))],
                                   widget=forms.Select(attrs={
                                       'class': 'switchable',
                                       'data-slug': 'audit_type'
                                   }))
    interval = forms.DurationField(initial="01:00:00",
                                   label=_("Interval (format hh:mm:ss)"),
                                   help_text=_("Interval in format hh:mm:ss "
                                               "for CONTINUOUS audit"),
                                   widget=forms.TextInput(attrs={
                                       'class': 'switched',
                                       'data-switch-on': 'audit_type',
                                       'data-audit_type-continuous':
                                       _("Interval (format hh:mm:ss)")}))
    failure_url = 'horizon:admin:audits:index'
    auto_trigger = forms.BooleanField(label=_("Auto Trigger"),
                                      required=False)

    def __init__(self, request, *args, **kwargs):
        super(CreateForm, self).__init__(request, *args, **kwargs)
        audit_templates = self._get_audit_template_list(request)

        if audit_templates:
            self.fields['audit_template'].choices = audit_templates
        else:
            del self.fields['audit_template']

    def _get_audit_template_list(self, request):
        try:
            audit_templates = watcher.AuditTemplate.list(self.request)
        except Exception:
            msg = _('Failed to get audit template list.')
            LOG.info(msg)
            messages.warning(request, msg)
            audit_templates = []

        choices = [
            (audit_template.uuid, audit_template.name or audit_template.uuid)
            for audit_template in audit_templates
        ]

        if choices:
            choices.insert(0, ("", _("Select Audit Template")))
        return choices

    def handle(self, request, data):
        try:
            params = {'audit_template_uuid': data.get('audit_template')}
            params['audit_type'] = data['audit_type'].upper()
            params['auto_trigger'] = data['auto_trigger']
            if data['audit_type'] == 'continuous':
                params['interval'] = int(data['interval'].total_seconds())
            else:
                params['interval'] = None
            audit = watcher.Audit.create(request, **params)
            message = _('Audit was successfully created.')
            messages.success(request, message)
            return audit
        except Exception as exc:
            if exc.http_status == 409:
                msg = _('Quota exceeded for resource audit.')
            else:
{'fraction_non_alphanumeric': 0.09837467921300257, 'fraction_numerical': 0.004399364536233655, 'mean_word_length': 1.8416666666666666, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 38, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6070603', 'n_tokens_mistral': 2063, 'n_tokens_neox': 2006, 'n_words': 547}