def get_child_nodes(self, targetNode_rid, edgetype='Containment'):
        '''
        Retrieve all of targetNode_rid's immediate connected records/vertices (maxdepth=1 and filterdepth = 1)
        via INCOMING edges.

        targetNode_rid <- child

        :param str targetNode_rid:  target record/vertex
        :param str edgetype:        edge type
        :return:                    None or orientdb record objects
        :raises BrassException:     source of exception is set to the function name
        '''

        try:
            if targetNode_rid is None:
                return None

            return self.get_connected_nodes(targetNode_rid,
                                            maxdepth=1,
                                            filterdepth=1,
                                            direction='in',
                                            edgetype=edgetype)
        except:
            raise BrassException(sys.exc_info()[1],
                                 'BrassOrientDBHelper.get_child_nodes')
    def get_parent_nodes(self, targetNode_rid, edgetype='Containment'):
        '''
        Retrieve all of targetNode_rid's immediate connected records/vertices (maxdepth=1 and filterdepth = 1)
        via OUTGOING edges.

        parent <- targetNode_rid

        :param str targetNode_rid:      target record/vertex
        :param str edgetype:            edge type
        :return:                        None or orientdb record objects
        :raises BrassException:             source of exception is set to the function name
        '''

        try:
            if targetNode_rid is None:
                return None

            #sql command
            #select from (traverse out('Containment') from #109:0 maxdepth 1) where $depth >=1
            #print select_sql( traverse_sql(targetNode_rid, direction='out', edgetype=edgetype, maxdepth=maxdepth), condition_str(lh='$depth', rh=1, op='>='))

            return self.get_connected_nodes(targetNode_rid,
                                            maxdepth=1,
                                            filterdepth=1,
                                            direction='out',
                                            edgetype=edgetype)
        except:
            raise BrassException(sys.exc_info()[1],
                                 'BrassOrientDBHelper.get_parent_nodes')
Beispiel #3
0
    def create_node(self,
                    node_type,
                    properties={},
                    transaction=False,
                    cluster_id=None):
        """
        Creates a new node of a specific vertex type and with the properties defined by properties dictionary.

        :param str node_type:                    string that specifies the type of vertex class
        :param dictionary properties:       dictionary containing properties and values to set for the new node
        :param bool transaction             boolean that defines if node is created via sql or record transactions
        :param int cluster_id               integer that defines which cluster the node should be stored
        :return:
        :raises BrassException:             source of exception is set to the function name
        """
        try:
            if not transaction:
                sql_cmd = insert_sql(node_type, **properties)
                self.log.debug(sql_cmd)
                self._orientdb_client.run_command(sql_cmd)
            elif transaction:
                data = {}
                class_name = '@%s' % node_type
                data[class_name] = properties
                self._orientdb_client.run_transaction(
                    record=data,
                    transaction_type='Create',
                    cluster_id=cluster_id)
        except:
            raise BrassException(sys.exc_info()[1],
                                 'BrassOrientDBHelper.create_node')
Beispiel #4
0
    def delete_node_by_rid(self, rid=None, transaction=False, cluster_id=None):
        """
        Removes a node from the database with rid.
        rid is a string that begins with a # followed by 2 numbers separated by a colon.

        :param str rid:                     Remove a node with this rid. Examples: #1244:3, #30:0
        :return:
        :raises BrassException:             source of exception is set to the function name
        """
        try:
            if len(self.get_node_by_rid(rid)) == 0:
                self.log.warning('[ERROR] Unable to delete node {0} because it does not exist in the database [SOURCE] {1}'.\
                    format(rid, 'BrassOrientDBHelper.delete_node_by_rid'))
                return False
            else:
                if not transaction:
                    sql_cmd = delete_v_sql(rid)
                    self.log.debug(sql_cmd)
                    return self._orientdb_client.run_command(sql_cmd)
                elif transaction:
                    return self._orientdb_client.run_transaction(
                        cluster_id=cluster_id,
                        rid=rid,
                        transaction_type='Delete')
        except:
            raise BrassException(sys.exc_info()[1],
                                 'BrassOrientDBHelper.delete_node_by_rid')
Beispiel #5
0
 def get_class(self, odb_class):
     try:
         target_name = '(select expand(classes) from metadata:schema)'
         class_condition = condition_str('name', odb_class)
         sql_cmd = select_sql(target_name, [class_condition])
         return self._orientdb_client.run_command(sql_cmd)
     except:
         raise BrassException(sys.exc_info()[1],
                              'BrassOrientDBHelper.get_class')
    def __init__(self,
                 database_name=None,
                 config_file=None,
                 orientdb_client=None):
        if orientdb_client is not None:
            self._orientdb_client = orientdb_client
        else:
            if database_name is None:
                raise BrassException('database is None',
                                     'BrassOrientDBHelper.__init__')

            if not os.path.exists(config_file):
                raise BrassException(
                    'config file [{0}] does NOT exist'.format(config_file),
                    'BrassOrientDBHelper.__init__')

            self._orientdb_client = BrassOrientDBClient(
                database_name, config_file)
Beispiel #7
0
 def create_node_property(self,
                          target_name,
                          property_name,
                          property_type,
                          link_type=None):
     try:
         sql_cmd = create_property_sql(target_name, property_name,
                                       property_type, link_type)
         self.log.debug(sql_cmd)
         self._orientdb_client.run_command(sql_cmd)
     except:
         raise BrassException(sys.exc_info()[1],
                              'BrassOrientDBHelper.create_node_property')
    def create_node(self, node_type, properties={}):
        """
        Creates a new node of a specific vertex type and with the properties defined by properties dictionary.

        :param str node_type:                    string that specifies the type of vertex class
        :param dictionary properties:       dictionary containing properties and values to set for the new node
        :return:
        :raises BrassException:             source of exception is set to the function name
        """
        try:
            sql_cmd = insert_sql(node_type, **properties)
            self._orientdb_client.run_command(sql_cmd)
        except:
            raise BrassException(sys.exc_info()[1],
                                 'BrassOrientDBHelper.create_node')
    def validate_mdl(self, xmlfile_path, mdl_schema):
        """
        Validates a xml file given by xmlfile_path against the mdl_schema.

        Todo: Still to need to make this work for the MDL exporter.

        :param str xmlfile_path:        name and path of xml file to validate
        :param str mdl_schema:          name of mdl_schema
        :return Boolean status:         result of validation (True or False)
        :raises BrassException:         throws any exception encountered
        """
        from lxml import etree

        BASE_DIR = os.path.dirname(os.path.realpath(__file__))
        mdl_schema = "{0}/../include/mdl_xsd/{1}".format(BASE_DIR, mdl_schema)

        status = None
        try:
            schema_doc = etree.parse(mdl_schema)
            schema = etree.XMLSchema(schema_doc)

            with open(xmlfile_path) as f:
                doc = etree.parse(f)

            status = schema.validate(doc)

        except etree.XMLSchemaParseError as e:
            status = False
            raise BrassException('Invalid MDL Schema File: ' + e.message,
                                 'xml_util.validate_mdl')
        except etree.DocumentInvalid as e:
            status = False
            raise BrassException('Invalide MDL XML File: ' + e.message,
                                 'xml_util.validate_mdl')
        finally:
            return status
    def connect_server(self):
        """
        Connects to the orientdb server.
        Must connect to the server first before opening a database.

        :param:     None
        :return:    None
        :raises BrassException:     source of the exception is set to the name of this function
        """
        try:
            self._session_id = self._client.connect(self._server_username,
                                                    self._server_password)
        except:
            raise BrassException(sys.exc_info()[1],
                                 'BrassOrientDBClient.connect_server')
    def create_edge_class(self, name):
        """
        Creates a new type of edge in the database.

        :param str name:        name of the new edge class in string
        :return:
        :raises BrassException:             source of exception is set to the function name
        """
        try:
            sql_cmd = create_class_sql(name, 'E')
            print(sql_cmd)
            self._orientdb_client.run_command(sql_cmd)
        except:
            raise BrassException(sys.exc_info()[1],
                                 'BrassOrientDBHelper.create_edge_class')
    def get_nodes_by_properties(self, property_conditions=[]):
        """
        Get nodes that fit the property conditions specified.

        :param list property_conditions:         list of property condition strings in the form of:
                                            name='MDL Description', description='This is a scenario 1'
                                            Use orientdb_sql.condition_str() to help create condition strings.
        :return:                            list of orient record objects
        :raises BrassException:             source of exception is set to the function name
        """
        try:
            sql_cmd = select_sql(property_conditions)
            return self._orientdb_client.run_command(sql_cmd)
        except:
            raise BrassException(sys.exc_info()[1],
                                 'BrassOrientDBHelper.get_node_by_properties')
Beispiel #13
0
    def update_node(self,
                    targetNode_rid,
                    *args,
                    node_type=None,
                    transaction=False,
                    version=None):
        '''
        Updates the target record/vertex (targetNode_rid) by the properties and corresponding values
        specified in args.

        :param str targetNode_rid:      The record/vertex to update.
        :param list args:               List of strings that contains the properties and values to set (e.g. EncryptionKeyID='gabah gabah', Name='gabah gabah')
        :param list args:               List of dicts that contain the properties and values to be set if using transactions (e.g. {'EncryptionKeyID':'gabah gabah'}, {'Name':'gabah gabah'}
        :return:                        None
        :raises BrassException:         source of exception is set to the function name
        '''

        #sql command
        #print update_sql(targetNode_rid, *args)

        try:
            if not transaction:
                sql_cmd = update_sql(targetNode_rid, *args)
                self.log.debug(sql_cmd)
                self._orientdb_client.run_command(sql_cmd)
                return True
            elif transaction:
                data = {}
                class_name = '@%s' % node_type
                properties = {}
                for i in args:
                    for key in i:
                        properties[key] = i[key]
                data[class_name] = properties
                self.log.debug(data)
                self._orientdb_client.run_transaction(
                    record=data,
                    transaction_type='Update',
                    rid=targetNode_rid,
                    version=version)

        except:
            raise BrassException(sys.exc_info()[1],
                                 'BrassOrientDBHelper.update_node')
    def delete_nodes_by_rid(self, rid_list):
        """
        Removes multiple nodes each given by a rid string in the rid_list.

        :param list rid_list:            list of nodes to remove
        :return:
        :raises BrassException:             source of exception is set to the function name
        """
        status = True
        try:
            # unfortunately the delete vertex command in orientdb doesn't let you delete a list of rids
            for r in rid_list:
                if not self.delete_node_by_rid(r):
                    status = False
            return status

        except:
            raise BrassException(sys.exc_info()[1],
                                 'BrassOrientDBHelper.delete_nodes_by_rid')
    def get_referent_node(self, targetNode_rid=None):
        '''
        Retrieves the node that targetNode_rid refers to.

        :param str targetNode_rid:      target node's rid
        :return:                        list of orient record objects
        :raises BrassException:             source of exception is set to the function name
        '''

        try:
            return self.get_connected_nodes(targetNode_rid,
                                            maxdepth=1,
                                            filterdepth=1,
                                            direction='out',
                                            edgetype='Reference')

        except:
            raise BrassException(sys.exc_info()[1],
                                 'BrassOrientDBHelper.get_referent_node')
    def get_node_by_rid(self, targetNode_rid):
        '''
        Retrieves a record/vertex that has the targetNode_rid.

        :param str targetNode_rid:  orientdb record id of a record/vertex
        :return:                    list of orientdb record objects
        :raises BrassException: source of exception is set to the function name
        '''

        # sql command
        #select from V where @rid=#93:0
        #print select_sql('V', condition_str('rid', targetNode_rid))

        try:
            sql_cmd = select_sql('V', [condition_str('rid', targetNode_rid)])
            return self._orientdb_client.run_command(sql_cmd)
        except:
            raise BrassException(sys.exc_info()[1],
                                 'BrassOrientDBHelper.get_node_by_rid')
    def get_nodes_by_type(self, type=None):
        '''
        Retrieves all records/vertices of a specific type.

        :param str type:    The type of record/vertex to retrieve e.g. TestMission, RadioLink, QoSPolicy
        :return:            list of orientdb record objects
        :raises BrassException: source of exception is set to the function name
        '''

        if type is None:
            return None

        #sql command
        # select from TestMissions => where 'TestMissions' is the type
        #print select_sql(type)

        try:
            sql_cmd = select_sql(type)
            return self._orientdb_client.run_command(sql_cmd)
        except:
            raise BrassException(sys.exc_info()[1],
                                 'BrassOrientDBHelper.get_nodes_by_type')
    def update_node(self, targetNode_rid, *args):
        '''
        Updates the target record/vertex (targetNode_rid) by the properties and corresponding values
        specified in args.

        :param str targetNode_rid:      The record/vertex to update.
        :param list args:               List of strings that contains the properties and values to set (e.g. EncryptionKeyID='gabah gabah', Name='gabah gabah')
        :return:                        None
        :raises BrassException:         source of exception is set to the function name
        '''

        #sql command
        #print update_sql(targetNode_rid, *args)

        try:
            sql_cmd = update_sql(targetNode_rid, *args)
            self._orientdb_client.run_command(sql_cmd)
            return True

        except:
            raise BrassException(sys.exc_info()[1],
                                 'BrassOrientDBHelper.update_node')
    def open_database(self, over_write=False):
        """
        Opens the orientDB database.

        :param boolean over_write:          set to True to drop existing database and create a new one,
                                    set to False top open an existing database if it exists
        :return:                    None
        :raises BrassException:     source of the exception is set to the name of this function
        """

        try:
            if over_write:
                if self._client.db_exists(self._db_name):
                    self.drop_database()
                self.create_database()
            else:
                if self._client.db_exists(self._db_name):
                    self._client.db_open(self._db_name, self._db_username,
                                         self._db_password)
                else:
                    self.create_database()
        except:
            raise BrassException(sys.exc_info()[1],
                                 'BrassOrientDBClient.open_database')
    def get_connected_nodes(self,
                            targetNode_rid,
                            direction='in',
                            edgetype='Containment',
                            maxdepth=1,
                            filterdepth=None,
                            strategy='DEPTH_FIRST'):
        '''
        Traverse and retrieve all records/vertices connected to the target record/vertices by the
        egdge/relationship set by "edgetype". Traversal depth is set by "maxdepth".
        Direction of traversal is set by "direction". "filterdepth" restricts the level of records
        to return. Below is an example topology along with a table showing query results for various
        parameter values:


        `MDLRoot <- TestMissions <- TestMission <- RadioLinks <- QoSPolicies`



        +-----------------+-------------+----------+--------------+------------------------------------+
        | targetNode      | direction   | max      | filter       |     returns                        |
        | rid             |             | depth    | depth        |                                    |
        +=================+=============+==========+==============+====================================+
        |TestMissions     |     in      |  2       |  >0          |TestMission, RadioLinks, QoSPolicies|
        +-----------------+-------------+----------+--------------+------------------------------------+
        |TestMissions     |     in      |  2       |  =2          |RadioLinks, QoSPolicies             |
        +-----------------+-------------+----------+--------------+------------------------------------+
        |TestMissions     |     in      | 2        |  =1          |TestMission                         |
        +-----------------+-------------+----------+--------------+------------------------------------+
        |RadioLinks       |     out     | 3        |  >0          |TestMission, TestMissions, MDLRoot  |
        +-----------------+-------------+----------+--------------+------------------------------------+
        |RadioLinks       |     out     | 3        |  =3          |MDLRoot                             |
        +-----------------+-------------+----------+--------------+------------------------------------+


        :param str targetNode_rid:  orientdb record id of the starting record/vertex
        :param str direction:       Direction of the edge/relationship
        :param str edgetype:        The relationship to use for traversal
        :param int maxdepth:        Defines the maximum depth of the traversal
        :param int filterdepth:     Defines the depth of the records to return. If none is set, then will return records up to the maxdepth (>0)
        :return:                    list of orientdb record objects
        :raises BrassException: source of exception is set to the function name
        '''

        if targetNode_rid is None:
            return None

        if filterdepth > maxdepth:
            print(
                "[WARNING] filterdepth is greater than maxdepth. No results will be returned from query. [SOURCE] BrassOrientDBHelper.get_connected_nodes"
            )
            return None

        if filterdepth is None:
            filterdepth_condition = condition_str(lh='$depth', rh=0, op='>')
        else:
            filterdepth_condition = condition_str(lh='$depth', rh=filterdepth)

        #sql command
        #select from (traverse in('Containment') from #109:0 maxdepth 1) where $depth >=1
        #print select_sql(
        #    traverse_sql(targetNode_rid, direction=direction, edgetype=edgetype, maxdepth=maxdepth),
        #    filterdepth_condition
        #)

        try:
            sql_cmd = select_sql(
                traverse_sql(targetNode_rid,
                             direction=direction,
                             edgetype=edgetype,
                             maxdepth=maxdepth), [filterdepth_condition])
            print(sql_cmd)
            return self._orientdb_client.run_command(sql_cmd)
        except:
            raise BrassException(sys.exc_info()[1],
                                 'BrassOrientDBHelper.get_child_nodes')