コード例 #1
0
ファイル: config_utils.py プロジェクト: ollawone/stdm
class ConfigurationUtils():
    PROFILE = 'Profile'
    SOCIAL_TENURE = 'SocialTenure'
    CONFIGURATION = 'Configuration'

    def __init__(self, document):
        """
        A utility class for STDM configuration.
        :param document: The configuration
        :type document: QDomDocument
        """
        self.file_handler = FilePaths()
        self.log_file_path = '{}/logs/migration.log'.format(
            self.file_handler.localPath()
        )
        self.document = document

    def append_log(self, info):
        """
        Append info to a single file
        :param info: update information to save to file
        :type info: str
        """
        info_file = open(self.log_file_path, "a")
        time_stamp = datetime.datetime.now().strftime(
            '%d-%m-%Y %H:%M:%S'
        )
        info_file.write('\n')
        info_file.write('{} - '.format(time_stamp))
        info_file.write(info)
        info_file.write('\n')
        info_file.close()

    def check_config_file_exists(self, config_file):
        """
        Checks if config file exists
        :returns True if folder exists else False
        :rtype bool
        """
        if os.path.isfile(os.path.join(
                self.file_handler.localPath(),
                config_file)
        ):

            return True
        else:
            return False

    def read_stc(self, config_file_name):
        """
        Reads provided config file
        :returns QDomDocument, QDomDocument.documentElement()
        :rtype tuple
        """
        config_file_path = os.path.join(
            self.file_handler.localPath(),
            config_file_name
        )

        config_file_path = QFile(config_file_path)
        config_file = os.path.basename(config_file_name)
        if self.check_config_file_exists(config_file):

            self.document = QDomDocument()

            status, msg, line, col = self.document.setContent(config_file_path)
            if not status:
                error_message = 'Configuration file cannot be loaded: {0}'. \
                    format(msg)
                self.append_log(str(error_message))

                raise ConfigurationException(error_message)

            self.doc_element = self.document.documentElement()

    def find_node(self, name):
        """
        Get nodes inside a document by a tag name.
        :param document: The xml document
        :type document: QDomDocument
        :param name: the tag name
        :type name: String
        :return: The nodes list
        :rtype: List
        """
        node_list = self.document.elementsByTagName(name)
        nodes = []
        for i in range(node_list.length()):
            node = node_list.item(i)
            nodes.append(node)
        return nodes

    def add_attribute_to_nodes(self, nodes, attr, value):
        """
        Adds an attribute with value to node lists.
        :param nodes: List of nodes
        :type nodes: QNodeList
        :param attr: The attribute text
        :type attr: String
        :param value: The value of the attribute.
        :type value: String
        :return:
        :rtype:
        """
        for node in nodes:
            element = node.toElement()
            element.setAttribute(attr, value)

    def add_attribute_by_node_name(self, node_name, attr, value):
        """
        Add attribute with value to nodes by node name.
        :param node_name: The name of the node.
        :type node_name: Strong
        :param attr: The attribute text
        :type attr: String
        :param value: The value of the attribute.
        :type value: String
        :return:
        :rtype:
        """
        nodes = self.find_node(node_name)
        self.add_attribute_to_nodes(nodes, attr, value)

    def profile_first_child(self, tag_name):
        """
        Gets the first child of profile node
        with a specified tag name.
        :param tag_name: The tag name to be used
        to search the child.
        :type tag_name: String
        :return: Dictionary of parent (profile node) and
        the child element.
        :rtype: OrderedDict
        """
        profile_nodes = self.find_node(self.PROFILE)
        first_child = OrderedDict()
        for profile_node in profile_nodes:
            profile_child = profile_node.firstChildElement(
                tag_name
            )
            first_child[profile_node] = profile_child
        return first_child

    def social_tenure_elements(self):
        """
        Get all social tenure element in a dom_document.
        :return: List of social tenure element
        :rtype: OrderedDict
        """
        social_tenure_nodes = self.profile_first_child(
            self.SOCIAL_TENURE
        )
        return social_tenure_nodes

    def run(self):
        nodes = self.find_node('Entity')

        self.add_attribute_to_nodes(nodes, 'Test', 'One')
コード例 #2
0
ファイル: database_updaters.py プロジェクト: ollawone/stdm
class DatabaseUpdater(QObject):
    db_update_complete = pyqtSignal(QDomDocument)
    db_update_progress = pyqtSignal(str)

    def __init__(self, document, parent=None):
        QObject.__init__(self, parent)
        self.file_handler = FilePaths()
        self.log_file_path = '{}/logs/migration.log'.format(
            self.file_handler.localPath())
        self.document = document

        self.base_updater = DatabaseVersionUpdater(self.log_file_path)

    def version(self):
        # Load items afresh
        # Check tag and version attribute first
        doc_element = self.document.documentElement()
        # Check version
        config_version = doc_element.attribute('version')

        if config_version:
            config_version = float(config_version)
            self.append_log(
                'Detected configuration version {}'.format(config_version))

        else:
            # Fatal error
            self.append_log('Error extracting version '
                            'number from the '
                            'configuration file.')
        return config_version

    def version_updater(self):

        if self.version() in self.base_updater.UPDATERS:
            return self.base_updater.UPDATERS[self.version()]
        else:
            return None

    def append_log(self, info):
        """
        Append info to a single file
        :param info: update information to save to file
        :type info: str
        """
        info_file = open(self.log_file_path, "a")
        time_stamp = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
        info_file.write('\n')
        info_file.write('{} - '.format(time_stamp))

        info_file.write(info)
        info_file.write('\n')
        info_file.close()

    def upgrade_database(self):
        """
        Updates database to the configuration version one step newer.
        :return:
        :rtype:
        """
        updater = self.version_updater()
        updater_instance = updater(self.log_file_path)
        updater_instance.db_update_progress.connect(self.db_update_progress)

        updater_instance.exec_()

    def on_update_progress(self, message):
        """
        A slot raised when an update progress signal
        is emitted in the updaters.
        :return:
        :rtype:
        """
        self.db_update_progress.emit(message)

    def on_update_complete(self, document):
        """
        A slot raised when an update complete
        signal is emitted in the last updater.
        :param document: The updated dom document
        :type document: QDomDocument
        :return:
        :rtype:
        """
        self.db_update_complete.emit(document)

    def on_db_update_progress(self, message):
        """
        A slot raised when the database update progress signal is emitted.
        :param message: The progress message
        :type message: String
        """
        self.db_update_progress.emit(message)
コード例 #3
0
class ConfigurationUpdater(QObject):
    update_complete = pyqtSignal(QDomDocument)
    update_progress = pyqtSignal(str)
    version_updated = pyqtSignal(QDomDocument)

    def __init__(self, document, parent=None):
        """
        A wrapper class for configuration updaters. It starts the running of
        Configuration version updater that is the first updater.
        :param document: The QDomDocument of the configuration
        :type document: QDomDocument
        :param parent: The parent of the QObject, even though unused.
        :type parent: QWidget/NoneType
        """
        QObject.__init__(self, parent)
        self.file_handler = FilePaths()
        self.log_file_path = '{}/logs/migration.log'.format(
            self.file_handler.localPath())
        self.base_updater = ConfigurationVersionUpdater(
            document, self.log_file_path)
        self.document = document

    def append_log(self, info):
        """
        Append info to a single file
        :param info: update information to save to file
        :type info: str
        """
        info_file = open(self.log_file_path, "a")
        time_stamp = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
        info_file.write('\n')
        info_file.write('{} - '.format(time_stamp))

        info_file.write(info)
        info_file.write('\n')
        info_file.close()

    def version(self):
        """
        Gets the version of the configuration QDomDocument.
        :return: The version of the configuration
        :rtype: float
        """
        # Load items afresh
        # Check tag and version attribute first
        doc_element = self.document.documentElement()
        # Check version
        config_version = doc_element.attribute('version')

        if config_version:
            config_version = float(config_version)
            self.append_log(
                'Detected configuration version {}'.format(config_version))

        else:
            # Fatal error
            self.append_log('Error extracting version '
                            'number from the '
                            'configuration file.')
        return config_version

    def version_updater(self, version):
        """
        Selects and returns the current configuration version updater
        using the version of the configuration to be updated.
        :param version: The version of the configuration
        :type version: float
        :return: The updater class or None if not found.
        :rtype: Class/NoneType
        """
        if version in self.base_updater.UPDATERS:
            return self.base_updater.UPDATERS[version]
        else:
            return None

    def exec_(self):
        """
        Creates the instance of the updater and executes the updater.
        :return: A tuple containing the update status, the updated
        configuration QDomDocument, and the db updater class for
        the version upgraded.
        :rtype: Tuple
        """
        version = self.version()
        updater = self.version_updater(version)

        if not updater is None:
            self.append_log('Found updater - {}.'.format(updater))
            updater_instance = updater(self.document, self.log_file_path)

            updater_instance.update_complete.connect(self.on_update_complete)
            updater_instance.update_progress.connect(self.on_update_progress)
            updater_instance.version_updated.connect(self.on_version_updated)
            updater_instance.exec_()
            return True, self.document

        else:

            self.append_log('No updater found for this configuration '
                            'with version number {}.'.format(version))
            return False, None

    def on_update_progress(self, message):
        """
        A slot raised when an update progress signal
        is emitted in the updaters.
        :return:
        :rtype:
        """
        self.update_progress.emit(message)

    def on_update_complete(self, document):
        """
        A slot raised when an update complete
        signal is emitted in the last updater.
        :param document: The updated dom document
        :type document: QDomDocument
        :return:
        :rtype:
        """
        self.update_complete.emit(document)

    def on_version_updated(self, document):
        """
        A slot raised when a specific version of a configuration is updated.
        :param document: The updated dom document
        :type document: QDomDocument
        :return:
        :rtype:
        """
        self.version_updated.emit(document)
コード例 #4
0
ファイル: database_updaters.py プロジェクト: gltn/stdm
class DatabaseUpdater(QObject):
    db_update_complete = pyqtSignal(QDomDocument)
    db_update_progress = pyqtSignal(str)
    def __init__(self, document, parent=None):
        QObject.__init__(self, parent)
        self.file_handler = FilePaths()
        self.log_file_path = '{}/logs/migration.log'.format(
            self.file_handler.localPath()
        )
        self.document = document

        self.base_updater = DatabaseVersionUpdater(
            self.log_file_path
        )

    def version(self):
        # Load items afresh
        # Check tag and version attribute first
        doc_element = self.document.documentElement()
        # Check version
        config_version = doc_element.attribute('version')

        if config_version:
            config_version = float(config_version)
            self.append_log(
                'Detected configuration version {}'.format(
                    config_version
                )
            )

        else:
            # Fatal error
            self.append_log('Error extracting version '
                            'number from the '
                            'configuration file.'
            )
        return config_version
    def version_updater(self):

        if self.version() in self.base_updater.UPDATERS:
            return self.base_updater.UPDATERS[self.version()]
        else:
            return None


    def append_log(self, info):
        """
        Append info to a single file
        :param info: update information to save to file
        :type info: str
        """
        info_file = open(self.log_file_path, "a")
        time_stamp = datetime.now().strftime(
            '%d-%m-%Y %H:%M:%S'
        )
        info_file.write('\n')
        info_file.write('{} - '.format(time_stamp))

        info_file.write(info)
        info_file.write('\n')
        info_file.close()

    def upgrade_database(self):
        """
        Updates database to the configuration version one step newer.
        :return:
        :rtype:
        """
        updater = self.version_updater()
        updater_instance = updater(self.log_file_path)
        updater_instance.db_update_progress.connect(self.db_update_progress)

        updater_instance.exec_()

    def on_update_progress(self, message):
        """
        A slot raised when an update progress signal
        is emitted in the updaters.
        :return:
        :rtype:
        """
        self.db_update_progress.emit(message)

    def on_update_complete(self, document):
        """
        A slot raised when an update complete
        signal is emitted in the last updater.
        :param document: The updated dom document
        :type document: QDomDocument
        :return:
        :rtype:
        """
        self.db_update_complete.emit(document)

    def on_db_update_progress(self, message):
        """
        A slot raised when the database update progress signal is emitted.
        :param message: The progress message
        :type message: String
        """
        self.db_update_progress.emit(message)
コード例 #5
0
ファイル: config_utils.py プロジェクト: gltn/stdm
class ConfigurationUtils():
    PROFILE = 'Profile'
    SOCIAL_TENURE = 'SocialTenure'
    CONFIGURATION = 'Configuration'

    def __init__(self, document):
        """
        A utility class for STDM configuration.
        :param document: The configuration
        :type document: QDomDocument
        """
        self.file_handler = FilePaths()
        self.log_file_path = '{}/logs/migration.log'.format(
            self.file_handler.localPath()
        )
        self.document = document

    def append_log(self, info):
        """
        Append info to a single file
        :param info: update information to save to file
        :type info: str
        """
        info_file = open(self.log_file_path, "a")
        time_stamp = datetime.datetime.now().strftime(
            '%d-%m-%Y %H:%M:%S'
        )
        info_file.write('\n')
        info_file.write('{} - '.format(time_stamp))
        info_file.write(info)
        info_file.write('\n')
        info_file.close()

    def check_config_file_exists(self, config_file):
        """
        Checks if config file exists
        :returns True if folder exists else False
        :rtype bool
        """
        if os.path.isfile(os.path.join(
                self.file_handler.localPath(),
                config_file)
        ):

            return True
        else:
            return False

    def read_stc(self, config_file_name):
        """
        Reads provided config file
        :returns QDomDocument, QDomDocument.documentElement()
        :rtype tuple
        """
        config_file_path = os.path.join(
            self.file_handler.localPath(),
            config_file_name
        )

        config_file_path = QFile(config_file_path)
        config_file = os.path.basename(config_file_name)
        if self.check_config_file_exists(config_file):

            self.document = QDomDocument()

            status, msg, line, col = self.document.setContent(config_file_path)
            if not status:
                error_message = u'Configuration file cannot be loaded: {0}'.\
                    format(msg)
                self.append_log(str(error_message))

                raise ConfigurationException(error_message)

            self.doc_element = self.document.documentElement()

    def find_node(self, name):
        """
        Get nodes inside a document by a tag name.
        :param document: The xml document
        :type document: QDomDocument
        :param name: the tag name
        :type name: String
        :return: The nodes list
        :rtype: List
        """
        node_list = self.document.elementsByTagName(name)
        nodes = []
        for i in range(node_list.length()):
            node = node_list.item(i)
            nodes.append(node)
        return nodes

    def add_attribute_to_nodes(self, nodes, attr, value):
        """
        Adds an attribute with value to node lists.
        :param nodes: List of nodes
        :type nodes: QNodeList
        :param attr: The attribute text
        :type attr: String
        :param value: The value of the attribute.
        :type value: String
        :return:
        :rtype:
        """
        for node in nodes:
            element = node.toElement()
            element.setAttribute(attr, value)

    def add_attribute_by_node_name(self, node_name, attr, value):
        """
        Add attribute with value to nodes by node name.
        :param node_name: The name of the node.
        :type node_name: Strong
        :param attr: The attribute text
        :type attr: String
        :param value: The value of the attribute.
        :type value: String
        :return:
        :rtype:
        """
        nodes = self.find_node(node_name)
        self.add_attribute_to_nodes(nodes, attr, value)

    def profile_first_child(self, tag_name):
        """
        Gets the first child of profile node
        with a specified tag name.
        :param tag_name: The tag name to be used
        to search the child.
        :type tag_name: String
        :return: Dictionary of parent (profile node) and
        the child element.
        :rtype: OrderedDict
        """
        profile_nodes = self.find_node(self.PROFILE)
        first_child = OrderedDict()
        for profile_node in profile_nodes:
            profile_child = profile_node.firstChildElement(
                tag_name
            )
            first_child[profile_node] = profile_child
        return first_child

    def social_tenure_elements(self):
        """
        Get all social tenure element in a dom_document.
        :return: List of social tenure element
        :rtype: OrderedDict
        """
        social_tenure_nodes = self.profile_first_child(
            self.SOCIAL_TENURE
        )
        return social_tenure_nodes


    def run(self):
        nodes = self.find_node('Entity')

        self.add_attribute_to_nodes(nodes, 'Test', 'One')
コード例 #6
0
ファイル: config_updaters.py プロジェクト: gltn/stdm
class ConfigurationUpdater(QObject):
    update_complete = pyqtSignal(QDomDocument)
    update_progress = pyqtSignal(str)
    version_updated = pyqtSignal(QDomDocument)

    def __init__(self, document, parent=None):
        """
        A wrapper class for configuration updaters. It starts the running of
        Configuration version updater that is the first updater.
        :param document: The QDomDocument of the configuration
        :type document: QDomDocument
        :param parent: The parent of the QObject, even though unused.
        :type parent: QWidget/NoneType
        """
        QObject.__init__(self, parent)
        self.file_handler = FilePaths()
        self.log_file_path = '{}/logs/migration.log'.format(
            self.file_handler.localPath()
        )
        self.base_updater = ConfigurationVersionUpdater(
            document, self.log_file_path
        )
        self.document = document


    def append_log(self, info):
        """
        Append info to a single file
        :param info: update information to save to file
        :type info: str
        """
        info_file = open(self.log_file_path, "a")
        time_stamp = datetime.now().strftime(
            '%d-%m-%Y %H:%M:%S'
        )
        info_file.write('\n')
        info_file.write('{} - '.format(time_stamp))

        info_file.write(info)
        info_file.write('\n')
        info_file.close()

    def version(self):
        """
        Gets the version of the configuration QDomDocument.
        :return: The version of the configuration
        :rtype: float
        """
        # Load items afresh
        # Check tag and version attribute first
        doc_element = self.document.documentElement()
        # Check version
        config_version = doc_element.attribute('version')

        if config_version:
            config_version = float(config_version)
            self.append_log(
                'Detected configuration version {}'.format(
                    config_version
                )
            )

        else:
            # Fatal error
            self.append_log('Error extracting version '
                            'number from the '
                            'configuration file.'
            )
        return config_version

    def version_updater(self, version):
        """
        Selects and returns the current configuration version updater
        using the version of the configuration to be updated.
        :param version: The version of the configuration
        :type version: float
        :return: The updater class or None if not found.
        :rtype: Class/NoneType
        """
        if version in self.base_updater.UPDATERS:
            return self.base_updater.UPDATERS[version]
        else:
            return None

    def exec_(self):
        """
        Creates the instance of the updater and executes the updater.
        :return: A tuple containing the update status, the updated
        configuration QDomDocument, and the db updater class for
        the version upgraded.
        :rtype: Tuple
        """
        version = self.version()
        updater = self.version_updater(version)

        if updater is not None:
            self.append_log(
                'Found updater - {}.'.format(updater)
            )
            updater_instance = updater(
                self.document, self.log_file_path
            )

            updater_instance.update_complete.connect(
                self.on_update_complete
            )
            updater_instance.update_progress.connect(
                self.on_update_progress
            )
            updater_instance.version_updated.connect(
                self.on_version_updated
            )
            updater_instance.exec_()
            return True, self.document

        else:
            self.append_log(
                'No updater found for this configuration '
                'with version number {}.'.format(version)
            )
            return False, None

    def on_update_progress(self, message):
        """
        A slot raised when an update progress signal
        is emitted in the updaters.
        :return:
        :rtype:
        """
        self.update_progress.emit(message)

    def on_update_complete(self, document):
        """
        A slot raised when an update complete
        signal is emitted in the last updater.
        :param document: The updated dom document
        :type document: QDomDocument
        :return:
        :rtype:
        """
        self.update_complete.emit(document)

    def on_version_updated(self, document):
        """
        A slot raised when a specific version of a configuration is updated.
        :param document: The updated dom document
        :type document: QDomDocument
        :return:
        :rtype:
        """
        self.version_updated.emit(document)