<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) 2015-2018:
#   <NAME>, <EMAIL>
#
# This file is part of (AlignakApp).
#
# (AlignakApp) is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# (AlignakApp) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with (AlignakApp).  If not, see <http://www.gnu.org/licenses/>.

"""
    Backend
    +++++++
    Backend manage connection and access to Alignak backend. It also fill
    :class:`DataManager <alignak_app.backend.datamanager.DataManager>`.
"""

import json

from logging import getLogger

from alignak_backend_client.client import Backend, BackendException

from alignak_app.backend.datamanager import data_manager

from alignak_app.items.daemon import Daemon
from alignak_app.items.event import Event
from alignak_app.items.history import History
from alignak_app.items.host import Host
from alignak_app.items.livesynthesis import LiveSynthesis
from alignak_app.items.service import Service
from alignak_app.items.user import User
from alignak_app.items.realm import Realm
from alignak_app.items.period import Period

from alignak_app.utils.config import settings

logger = getLogger(__name__)


class BackendClient(object):
    """
        Class who collect informations with Backend-Client and returns data for Alignak-App.
    """

    connection_status = {
        True: 'Success',
        False: 'Failure'
    }

    def __init__(self):
        self.start = False
        self.backend = None
        self.connected = False
        self.user = {}

    def login(self, username=None, password=None, check=False):
        """
        Connect to alignak backend

        :param username: name or token of user
        :type username: str
        :param password: password of user. If token given, this parameter is useless
        :type password: str
        :param check: define if login is a check or a first login
        :type check: bool
        :return: True if connected or False if not
        :rtype: bool
        """

        # Credentials
        if not username and not password:
            if 'token' in self.user:
                username = self.user['token']

        # Create Backend object
        backend_url = settings.get_config('Alignak', 'backend')
        processes = int(settings.get_config('Alignak', 'processes'))

        self.backend = Backend(backend_url, processes=processes)

        logger.debug('Backend URL : %s', backend_url)
        if not check:
            logger.info('Try to connect to the Alignak backend...')

        if username and password:
            # Username & password : not recommended, without login QDialog
            try:
                self.connected = self.backend.login(username, password)
                if self.connected:
                    self.user['username'] = username
                    self.user['token'] = self.backend.token
                logger.info('Connection by password: %s', self.connection_status[self.connected])
            except BackendException:  # pragma: no cover
                logger.error('Connection to Backend has failed !')
        elif username and not password:
            # Username as token : recommended
            self.backend.authenticated = True
            if 'token' in self.user:
                self.backend.token = self.user['token']
            else:
                self.backend.token = username
                self.user['token'] = username

            # Make backend connected to test token
            self.connected = True
            connection_test = self.get('alignak', {'projection': json.dumps({'name': 1})})

            self.connected = bool(connection_test)
            if not check:
                logger.info('Connection by token: %s', self.connection_status[self.connected])
        else:
            logger.warning(
                'Connection to Backend has failed.\n'<commit_msg>Use "set_token()" function of Backend client<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) 2015-2018:
#   <NAME>, <EMAIL>
#
# This file is part of (AlignakApp).
#
# (AlignakApp) is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# (AlignakApp) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with (AlignakApp).  If not, see <http://www.gnu.org/licenses/>.

"""
    Backend
    +++++++
    Backend manage connection and access to Alignak backend. It also fill
    :class:`DataManager <alignak_app.backend.datamanager.DataManager>`.
"""

import json

from logging import getLogger

from alignak_backend_client.client import Backend, BackendException

from alignak_app.backend.datamanager import data_manager

from alignak_app.items.daemon import Daemon
from alignak_app.items.event import Event
from alignak_app.items.history import History
from alignak_app.items.host import Host
from alignak_app.items.livesynthesis import LiveSynthesis
from alignak_app.items.service import Service
from alignak_app.items.user import User
from alignak_app.items.realm import Realm
from alignak_app.items.period import Period

from alignak_app.utils.config import settings

logger = getLogger(__name__)


class BackendClient(object):
    """
        Class who collect informations with Backend-Client and returns data for Alignak-App.
    """

    connection_status = {
        True: 'Success',
        False: 'Failure'
    }

    def __init__(self):
        self.start = False
        self.backend = None
        self.connected = False
        self.user = {}

    def login(self, username=None, password=None, check=False):
        """
        Connect to alignak backend

        :param username: name or token of user
        :type username: str
        :param password: password of user. If token given, this parameter is useless
        :type password: str
        :param check: define if login is a check or a first login
        :type check: bool
        :return: True if connected or False if not
        :rtype: bool
        """

        # Credentials
        if not username and not password:
            if 'token' in self.user:
                username = self.user['token']

        # Create Backend object
        backend_url = settings.get_config('Alignak', 'backend')
        processes = int(settings.get_config('Alignak', 'processes'))

        self.backend = Backend(backend_url, processes=processes)

        logger.debug('Backend URL : %s', backend_url)
        if not check:
            logger.info('Try to connect to the Alignak backend...')

        if username and password:
            # Username & password : not recommended, without login QDialog
            try:
                self.connected = self.backend.login(username, password)
                if self.connected:
                    self.user['username'] = username
                    self.user['token'] = self.backend.token
                logger.info('Connection by password: %s', self.connection_status[self.connected])
            except BackendException:  # pragma: no cover
                logger.error('Connection to Backend has failed !')
        elif username and not password:
            # Username as token : recommended
            if 'token' in self.user:
                self.backend.set_token(self.user['token'])
            else:
                self.backend.set_token(username)
                self.user['token'] = username

            # Make backend connected to test token
            self.connected = True
            connection_test = self.get('alignak', {'projection': json.dumps({'name': 1})})

            self.connected = bool(connection_test)
            if not check:
                logger.info('Connection by token: %s', self.connection_status[self.connected])
        else:
            logger.warning(
                'Connection to Backend has failed.\n'
{'fraction_non_alphanumeric': 0.08654177680726353, 'fraction_numerical': 0.0025284450063211127, 'mean_word_length': 2.5417175417175417, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, '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': '2110061', 'n_tokens_mistral': 2326, 'n_tokens_neox': 2249, 'n_words': 796}