Example #1
0
    def delete_apikey(self, key):
        """delete an apikey"""

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        query_laucher.process_query(sqa.delete_apikey(key).query)
Example #2
0
    def positionable_attr(self):
        """
        Return the positionable attributes in common between two positionable entity
        """
        #FIXEME: Rewrite this ugly method

        body = self.request.json_body
        data = {}

        sqb = SparqlQueryBuilder(self.settings, self.request.session)
        ql = QueryLauncher(self.settings, self.request.session)

        # Check if the two entity are positionable
        positionable1 = ql.process_query(sqb.get_if_positionable(body['node']).query)
        positionable2 = ql.process_query(sqb.get_if_positionable(body['node']).query)

        if positionable1 == 0 or positionable2 == 0:
            data['error'] = 'not positionable nodes'
            return data

        results = ql.process_query(sqb.get_common_positionable_attributes(body['node'], body['second_node']).query)
        self.log.debug(results)

        data['results'] = {}

        list_pos_attr = []

        for elem in results:
            if elem['pos_attr'] not in list_pos_attr:
                list_pos_attr.append(elem['pos_attr'].replace("http://www.semanticweb.org/irisa/ontologies/2016/1/igepp-ontology#", ""))

        for elem in list_pos_attr:
            data['results'][elem] = False not in [bool(int(p['status'])) for p in results if p['pos_attr'] == "http://www.semanticweb.org/irisa/ontologies/2016/1/igepp-ontology#"+elem]

        return data
Example #3
0
    def delete_askograph(self):
        """Delete the askomics graph"""

        sqb = SparqlQueryGraph(self.settings, self.request.session)
        query_laucher = QueryLauncher(self.settings, self.request.session)

        query_laucher.process_query(sqb.get_drop_named_graph('urn:sparql:test_askomics').query)
Example #4
0
    def delete_galaxy(self):
        """Delete galaxy triple for the user"""

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        query_laucher.process_query(sqa.delete_galaxy(self.username).query)
Example #5
0
    def delete_apikey(self, key):
        """delete an apikey"""

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        query_laucher.process_query(sqa.delete_apikey(key).query)
Example #6
0
    def delete_askograph(self):
        """Delete the askomics graph"""

        sqb = SparqlQueryGraph(self.settings, self.request.session)
        query_laucher = QueryLauncher(self.settings, self.request.session)

        query_laucher.process_query(sqb.get_drop_named_graph('urn:sparql:test_askomics'))
Example #7
0
    def update_email(self):
        """
        change the mail of a user
        """
        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        query_laucher.process_query(sqa.update_mail(self.username, self.email).query)
Example #8
0
    def update_passwd(self):
        """
        Change the password of a user, and his randomsalt
        """
        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        query_laucher.process_query(sqa.update_passwd(self.username, self.sha256_pw, self.randomsalt).query)
Example #9
0
    def delete_galaxy(self):
        """Delete galaxy triple for the user"""


        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        query_laucher.process_query(sqa.delete_galaxy(self.username).query)
Example #10
0
    def update_email(self):
        """
        change the mail of a user
        """
        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        query_laucher.process_query(
            sqa.update_mail(self.username, self.email).query)
Example #11
0
    def update_passwd(self):
        """
        Change the password of a user, and his randomsalt
        """
        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        query_laucher.process_query(
            sqa.update_passwd(self.username, self.sha256_pw,
                              self.randomsalt).query)
Example #12
0
    def statistics(self):
        """ Get information about triplet store """
        self.log.debug("== STATS ==")
        data = {}
        pm = ParamManager(self.settings, self.request.session)

        sqb = SparqlQueryBuilder(self.settings, self.request.session)
        ql = QueryLauncher(self.settings, self.request.session)
        tse = TripleStoreExplorer(self.settings, self.request.session)

        results = ql.process_query(sqb.get_statistics_number_of_triples().query)
        data["ntriples"] = results[0]["no"]

        results = ql.process_query(sqb.get_statistics_number_of_entities().query)
        data["nentities"] = results[0]["no"]

        results = ql.process_query(sqb.get_statistics_distinct_classes().query)
        data["nclasses"] = results[0]["no"]

        # Get the list of classes
        res_list_classes = ql.process_query(sqb.get_statistics_list_classes().query)

        data["class"] = {}
        for obj in res_list_classes:
            class_name = pm.remove_prefix(obj['class'])
            data["class"][class_name] = {}

        # Get the number of instances by class
        res_nb_instances = ql.process_query(sqb.get_statistics_nb_instances_by_classe().query)

        for obj in res_nb_instances:
            if 'class' in obj:
                class_name = pm.remove_prefix(obj['class'])
                data["class"][class_name]["count"] = obj['count']

        # Get details on relations for each classes
        for obj in res_list_classes:
            if 'class' in obj:
                class_name = pm.remove_prefix(obj['class'])
                uri = obj['class']

                shortcuts_list = tse.has_setting(uri, 'shortcut')

                src = Node(class_name, # We don't care about counter in stats
                    uri,
                    class_name,
                    shortcuts_list)

                attributes, nodes, links = tse.get_neighbours_for_node(src, None)

                data["class"][class_name]["attributes"] = [a.to_dict() for a in attributes]
                data["class"][class_name]["neighbours"] = [n.to_dict() for n in nodes]
                data["class"][class_name]["relations"] = [l.to_dict() for l in links]

        return data
Example #13
0
    def add_apikey(self, keyname):
        """Add an api key

        :param keyname: the keyname
        :type keyname: string
        """

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        query_laucher.process_query(sqa.add_apikey(self.username, keyname).query)
Example #14
0
    def add_apikey(self, keyname):
        """Add an api key

        :param keyname: the keyname
        :type keyname: string
        """

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        query_laucher.process_query(
            sqa.add_apikey(self.username, keyname).query)
Example #15
0
    def test_triple_presence(self, graph, triple):
        """Test the presence of a triple in the triplestore

        get if a triple is present in a specific graph of the triplestore
        :param graph: the named graph
        :type graph: string
        :param triple: the triple to test
        :type triple: string
        :returns: Result of the test
        :rtype: bool
        """

        sqb = SparqlQueryGraph(self.settings, self.request.session)
        query_laucher = QueryLauncher(self.settings, self.request.session)

        query = sqb.prepare_query("""
            SELECT count(*) AS ?count
            WHERE {
                GRAPH <""" + graph + """> {
                    """ + triple + """ .
                }
            }
            """)

        res = query_laucher.process_query(query)

        print(bool(int(res[0]['count'])))

        return bool(int(res[0]['count']))
Example #16
0
    def compare_file_to_database(self, headers):
        """ Ask the database to compare the headers of a file to convert to the corresponding class in the database """
        curr_entity = headers[0]
        sqb = SparqlQueryBuilder(self.settings, self.session)
        ql = QueryLauncher(self.settings, self.session)
        sparql_template = self.get_template_sparql(self.ASKOMICS_get_class_info_from_abstraction_queryFile)
        query = sqb.load_from_file(sparql_template, {"#nodeClass#": curr_entity}).query

        results = ql.process_query(query)
        if results == []:
            return [], headers, []
        bdd_relations, new_headers, missing_headers, present_headers = [], [], [], []
        for result in results:
            bdd_relation = result["relation"].replace(self.get_param("askomics.prefix"), "").replace("has_", "")
            bdd_relations.append(bdd_relation)
            if bdd_relation not in headers:
                self.log.warning('Relation "%s" not found in tables columns: %s.', bdd_relation, repr(headers))
                missing_headers.append(bdd_relation)
        for header in headers:
            if header != curr_entity:
                if header not in bdd_relations:
                    self.log.info('Adding column "%s".', header)
                    new_headers.append(header)
                elif header not in missing_headers:
                    present_headers.append(header)
        return missing_headers, new_headers, present_headers
Example #17
0
    def build_sparql_query_from_json(self,
                                     fromgraphs,
                                     variates,
                                     constraintes_relations,
                                     limit,
                                     send_request_to_tps=True):
        """
        Build a sparql query from JSON constraints
        """

        select = ' '.join(variates)

        sqb = SparqlQueryBuilder(self.settings, self.session)
        query_launcher = QueryLauncher(self.settings, self.session)
        query = self.build_recursive_block('', constraintes_relations)

        # if limit != None and limit > 0:
        #     query += ' LIMIT ' + str(limit)

        if send_request_to_tps:
            results = query_launcher.process_query(
                sqb.custom_query(fromgraphs, select, query).query)
        else:
            results = []

        return results, sqb.custom_query(fromgraphs, select, query).query
Example #18
0
    def test_triple_presence(self, graph, triple):
        """Test the presence of a triple in the triplestore

        get if a triple is present in a specific graph of the triplestore
        :param graph: the named graph
        :type graph: string
        :param triple: the triple to test
        :type triple: string
        :returns: Result of the test
        :rtype: bool
        """

        sqb = SparqlQueryGraph(self.settings, self.request.session)
        query_laucher = QueryLauncher(self.settings, self.request.session)


        query = sqb.prepare_query("""
            SELECT count(*) AS ?count
            WHERE {
                GRAPH <""" + graph + """> {
                    """ + triple + """ .
                }
            }
            """)

        res = query_laucher.process_query(query)

        print(bool(int(res[0]['count'])))

        return bool(int(res[0]['count']))
Example #19
0
    def get_start_points(self):
        """
        Get the possible starting points for your graph.

        :return: List of starting points
        :rtype: Node list
        """
        self.log.debug(" =========== TripleStoreExplorer:get_start_points ===========")
        nodes = []

        sqg = SparqlQueryGraph(self.settings, self.session)
        ql = QueryLauncher(self.settings, self.session)
        results = ql.process_query(sqg.get_start_point().query)

        for result in results:
            g  = result["g"]
            uri = result["nodeUri"]
            label = result["nodeLabel"]

            if 'private' in result['accesLevel']:
                public = False
                private = True
            else:
                public = True
                private = False

            nodes.append({'g': g, 'uri': uri, 'label': label, 'public': public, 'private': private})

        return nodes
Example #20
0
    def empty(self):
        """Delete all test data

        Get the list of all public and private graphs and delete them
        """

        sqb = SparqlQueryGraph(self.settings, self.request.session)
        query_laucher = QueryLauncher(self.settings, self.request.session)
        private_graphs = self.list_private_graphs()
        public_graphs = self.list_public_graphs()

        for graph in private_graphs:
            query_laucher.process_query(sqb.get_delete_query_string(graph))

        for graph in public_graphs:
            query_laucher.process_query(sqb.get_delete_query_string(graph))
Example #21
0
    def empty(self):
        """Delete all test data

        Get the list of all public and private graphs and delete them
        """

        sqb = SparqlQueryGraph(self.settings, self.request.session)
        query_laucher = QueryLauncher(self.settings, self.request.session)
        private_graphs = self.list_private_graphs()
        public_graphs = self.list_public_graphs()

        for graph in private_graphs:
            query_laucher.process_query(sqb.get_delete_query_string(graph))

        for graph in public_graphs:
            query_laucher.process_query(sqb.get_delete_query_string(graph))
Example #22
0
    def positionable_attr(self):
        """
        Return the positionable attributes in common between two positionable entity
        """
        #FIXEME: Rewrite this ugly method

        body = self.request.json_body
        data = {}

        sqb = SparqlQueryBuilder(self.settings, self.request.session)
        ql = QueryLauncher(self.settings, self.request.session)

        # Check if the two entity are positionable
        positionable1 = ql.process_query(
            sqb.get_if_positionable(body['node']).query)
        positionable2 = ql.process_query(
            sqb.get_if_positionable(body['node']).query)

        if positionable1 == 0 or positionable2 == 0:
            data['error'] = 'not positionable nodes'
            return data

        results = ql.process_query(
            sqb.get_common_positionable_attributes(body['node'],
                                                   body['second_node']).query)
        self.log.debug(results)

        data['results'] = {}

        list_pos_attr = []

        for elem in results:
            if elem['pos_attr'] not in list_pos_attr:
                list_pos_attr.append(elem['pos_attr'].replace(
                    "http://www.semanticweb.org/irisa/ontologies/2016/1/igepp-ontology#",
                    ""))

        for elem in list_pos_attr:
            data['results'][elem] = False not in [
                bool(int(p['status'])) for p in results if p['pos_attr'] ==
                "http://www.semanticweb.org/irisa/ontologies/2016/1/igepp-ontology#"
                + elem
            ]

        return data
Example #23
0
    def check_galaxy(self):
        """Check if user have galaxy triples"""

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(sqa.check_galaxy(self.username).query)

        return ParamManager.Bool(result[0]['status'])
Example #24
0
    def set_username_by_email(self):
        """Get the username of a user by his email"""

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(sqa.get_username_by_email(self.email).query)

        # return result[0]['username']
        self.username = result[0]['username']
Example #25
0
    def check_galaxy(self):
        """Check if user have galaxy triples"""

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(
            sqa.check_galaxy(self.username).query)

        return ParamManager.Bool(result[0]['status'])
Example #26
0
    def get_galaxy_infos(self):
        """Get Galaxy url and apikey of a user"""

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(sqa.get_galaxy_infos(self.username).query)

        if result:
            return result[0]
        return []
Example #27
0
    def set_username_by_email(self):
        """Get the username of a user by his email"""

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(
            sqa.get_username_by_email(self.email).query)

        # return result[0]['username']
        self.username = result[0]['username']
Example #28
0
    def get_galaxy_infos(self):
        """Get Galaxy url and apikey of a user"""

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(
            sqa.get_galaxy_infos(self.username).query)

        if result:
            return result[0]
        return []
Example #29
0
    def getGraphUser(self, removeGraph=[]):
        self.log.debug("=== setGraphUser ===")
        settings = {}
        #finding all private graph graph

        qu = self.build_query_on_the_fly({
            'select': '?g',
            'query': 'GRAPH ?g {\n'+\
            "?g dc:creator '" + self.session['username'] + "' . } ",
            'post_action': 'GROUP BY ?g'
        }, True)

        ql = QueryLauncher(self.settings, self.session)
        results = ql.process_query(qu.query)
        settings['private'] = []

        for elt in results:
            if 'g' not in elt:
                continue
            if elt['g'] in removeGraph:
                continue
            settings['private'].append(elt['g'])
        self.log.debug("setting['private']:\n" + str(settings['private']))

        #finding all public graph
        qu = self.build_query_on_the_fly(
            {
                'select': '?g',
                'query': 'GRAPH ?g {\n' + "?g :accessLevel 'public'. } "
            }, True)
        ql = QueryLauncher(self.settings, self.session)
        results = ql.process_query(qu.query)
        settings['public'] = []
        for elt in results:
            if elt['g'] in removeGraph:
                continue
            settings['public'].append(elt['g'])

        self.log.debug("setting['public']:\n" + str(settings['public']))
        return settings
Example #30
0
    def getGraphUser(self,removeGraph=[]):
        self.log.debug("=== setGraphUser ===")
        settings = {}
        #finding all private graph graph

        qu = self.build_query_on_the_fly({
            'select': '?g',
            'query': 'GRAPH ?g {\n'+\
            "?g dc:creator '" + self.session['username'] + "' . } ",
            'post_action': 'GROUP BY ?g'
        }, True)

        ql = QueryLauncher(self.settings, self.session)
        results = ql.process_query(qu.query)
        settings['private'] = []

        for elt in results:
            if 'g' not in elt:
                continue
            if elt['g'] in removeGraph:
                continue
            settings['private'].append(elt['g'])
        self.log.debug("setting['private']:\n"+str(settings['private']))

        #finding all public graph
        qu = self.build_query_on_the_fly({
            'select': '?g',
            'query': 'GRAPH ?g {\n'+
            "?g :accessLevel 'public'. } "
        }, True)
        ql = QueryLauncher(self.settings, self.session)
        results = ql.process_query(qu.query)
        settings['public'] = []
        for elt in results:
            if elt['g'] in removeGraph:
                continue
            settings['public'].append(elt['g'])

        self.log.debug("setting['public']:\n"+str(settings['public']))
        return settings
Example #31
0
    def getUserAbstraction(self, service):
        """
        Get the user abstraction (relation and entity as subject and object)

        :return:
        :rtype:
        """
        data = {}
        self.log.debug(
            " =========== TripleStoreExplorer:getUserAbstraction ===========")

        sqg = SparqlQueryGraph(self.settings, self.session)
        ql = QueryLauncher(self.settings, self.session)

        data['relations'] = ql.process_query(
            sqg.get_abstraction_relation('owl:ObjectProperty').query)
        data['subclassof'] = ql.process_query(
            sqg.get_isa_relation_entities().query)
        data['entities'] = ql.process_query(sqg.get_abstraction_entity().query)
        data['attributes'] = ql.process_query(
            sqg.get_abstraction_attribute_entity().query)
        data['categories'] = ql.process_query(
            sqg.get_abstraction_category_entity().query)
        data['positionable'] = ql.process_query(
            sqg.get_abstraction_positionable_entity().query)
        data['graph'] = sqg.getGraphUser()

        return data
Example #32
0
    def add_galaxy(self, url, key):
        """Connect a galaxy account to Askomics

        add triples for the url of galaxy, and the user api key

        :param self; url: the galaxy url
        :type self; url: string
        :param key: the galaxy user api key
        :type key: string
        """

        # try to connect to the galaxy server
        galaxy = GalaxyConnector(self.settings, self.session, url, key)
        try:
            galaxy.check_galaxy_instance()
        except Exception as e:
            raise e

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        query_laucher.process_query(sqa.add_galaxy(self.username, url, key).query)
Example #33
0
    def ckeck_key_belong_user(self, key):
        """Check if a key belong to a user"""

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(sqa.ckeck_key_belong_user(self.username, key).query)
        self.log.debug('---> result: ' + str(result))

        if len(result) <= 0:
            return False

        return ParamManager.Bool(result[0]['count'])
Example #34
0
    def check_email_in_database(self):
        """
        Check if the email is present in the TS
        """

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(sqa.check_email_presence(self.email).query)

        if len(result) <= 0:
            return False

        return ParamManager.Bool(result[0]['status'])
Example #35
0
    def launch_query(self):
        """ Converts the constraints table created by the graph to a sparql query, send it to the database and compile the results"""
        data = {}
        body = self.request.json_body

        export = bool(int(body['export']))
        sqb = SparqlQueryBuilder(self.settings, self.request.session)
        return_only_query = bool(int(body['return_only_query']))

        if body['uploaded'] != '':
            if export:
                query = body['uploaded'].replace('LIMIT 30', 'LIMIT 10000')
            else:
                query = body['uploaded']
        else:
            query = sqb.load_from_query_json(body).query

        if return_only_query:
            data['query'] = query
            return data

        ql = QueryLauncher(self.settings, self.request.session)
        rb = ResultsBuilder(self.settings, self.request.session)


        results = ql.process_query(query)

        if export:
            data['file'] = ql.format_results_csv(rb.build_csv_table(results))
        else:
            entity_name_list, entity_list_attributes = rb.organize_attribute_and_entity(results, body['constraint'])

            data['results_entity_name'] = entity_name_list
            data['results_entity_attributes'] = entity_list_attributes

            data['results'] = [
                {
                    k: res[k].replace(self.settings["askomics.prefix"], '')
                    for k in res.keys()
                }
                for res in results
            ]

        self.log.debug("== results ==")
        for elt in results:
            self.log.debug(elt)

    #    data['query'] = query

        return data
Example #36
0
    def get_number_of_users(self):
        """
        get the number of users in the TS
        """

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(sqa.get_number_of_users().query)

        if len(result) <= 0:
            return 0

        return int(result[0]['count'])
Example #37
0
    def add_galaxy(self, url, key):
        """Connect a galaxy account to Askomics

        add triples for the url of galaxy, and the user api key

        :param self; url: the galaxy url
        :type self; url: string
        :param key: the galaxy user api key
        :type key: string
        """

        # try to connect to the galaxy server
        galaxy = GalaxyConnector(self.settings, self.session, url, key)
        try:
            galaxy.check_galaxy_instance()
        except Exception as e:
            raise e

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        query_laucher.process_query(
            sqa.add_galaxy(self.username, url, key).query)
Example #38
0
    def get_admins_emails(self):
        """
        Get all admins emails
        """
        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(sqa.get_admins_emails().query)

        email_list = []
        for dic in result:
            email_list.append(re.sub(r'^mailto:', '', dic['email']))

        return email_list
Example #39
0
    def ckeck_key_belong_user(self, key):
        """Check if a key belong to a user"""

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(
            sqa.ckeck_key_belong_user(self.username, key).query)
        self.log.debug('---> result: ' + str(result))

        if len(result) <= 0:
            return False

        return ParamManager.Bool(result[0]['count'])
Example #40
0
    def get_number_of_users(self):
        """
        get the number of users in the TS
        """

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(sqa.get_number_of_users().query)

        if len(result) <= 0:
            return 0

        return int(result[0]['count'])
Example #41
0
    def get_admins_emails(self):
        """
        Get all admins emails
        """
        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(sqa.get_admins_emails().query)

        email_list = []
        for dic in result:
            email_list.append(re.sub(r'^mailto:', '', dic['email']))

        return email_list
Example #42
0
    def moStateOnTPS(self):
        '''
            check if module files state is saved on the TPS.
            if not all modules files are saved with the unchecked status !
        '''
        sqb = SparqlQueryBuilder(self.settings, self.session)
        ql = QueryLauncher(self.settings, self.session)
        results = ql.process_query(
            sqb.build_query_on_the_fly(
                {
                    'select':
                    '?uri ?module ?comment ?version ?graph ?state',
                    'from': [self.graph_modules],
                    'query':
                    '{\n' + '?uri rdfs:label ?module .\n' +
                    '?uri rdfs:comment ?comment .\n' +
                    '?uri :module_version ?version .\n' +
                    '?uri :module_state ?state .\n' +
                    'OPTIONAL { ?uri :module_graph ?graph . } \n' + '}\n'
                }, True).query)

        self.log.debug(' ***** module on TPS ***** ')
        listMoOnTps = {}
        for result in results:
            result['checked'] = (result['state'] == "ok")
            result['wait'] = (result['state'] == "wait")
            listMoOnTps[result['module']] = 0
            self.log.debug('module : ' + result['module'])
            #=======================*************** A ENLEVER *********=======================================
            #pour debugger
            #if result['wait'] :
            #    result['wait'] = False
            #==============================================================

        self.log.debug(' ***** check Available Modules ***** ')

        requestAgain = False

        for mo in self.moduleFiles:
            self.log.debug(" --> module " + mo)
            if mo not in listMoOnTps:
                self.log.debug(" --====== > new module < =======")
                self.importMoSate(self.moduleFiles[mo], 'off')
                requestAgain = True

        if requestAgain:
            return False

        return results
Example #43
0
    def get_owner_of_apikey(self, key):
        """Get the owner of an API kei

        [description]
        :param key: The API key
        :type key: string
        """

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(sqa.get_owner_apikey(key).query)

        if result:
            self.username = result[0]['username']
Example #44
0
    def check_email_in_database(self):
        """
        Check if the email is present in the TS
        """

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(
            sqa.check_email_presence(self.email).query)

        if len(result) <= 0:
            return False

        return ParamManager.Bool(result[0]['status'])
Example #45
0
    def get_owner_of_apikey(self, key):
        """Get the owner of an API kei

        [description]
        :param key: The API key
        :type key: string
        """

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(sqa.get_owner_apikey(key).query)

        if result:
            self.username = result[0]['username']
Example #46
0
    def get_attributes_of(self, uri):
        """
        Get all attributes of a node class (identified by his uri). These
        attributes are known thanks to the domain knowledge of your RDF database.

        :param uri: Uri of the node class
        :type uri: str
        :return: All attributes of a node class
        :rtype: Attribute list
        """
        self.log.debug(" =========== TripleStoreExplorer:get_attributes_of ===========")
        attributes = []
        results = []

        sqb = SparqlQueryBuilder(self.settings, self.session)
        ql = QueryLauncher(self.settings, self.session)

        fragment = uri.rsplit('#', 1)[-1]
        parent = fragment + str(self.get_new_id(fragment))

        # Send a request to know all the neighbors of a node (from uri).
        sparql_template = self.get_template_sparql(self.ASKOMICS_neighbor_query_file)

        query = sqb.load_from_file(sparql_template, {
            "nodeClass": '<%s>' % uri,
            "neighborClass": "?nodeUri"
            }).query

        results = (ql.process_query(query))
        for result in results:
            neighbor_uri = result["relationUri"]
            if 'nodeLabel' in result:
                neighbor_label = result["nodeLabel"]
            else:
                neighbor_label = result["relationLabel"]

            neighbor_id = neighbor_label + str(self.get_new_id(neighbor_label))

            if self.has_setting(result["nodeUri"], 'attribute') or self.has_setting(neighbor_uri, 'attribute'):
                attributes.append(
                    Attribute(neighbor_id,
                        neighbor_uri,
                        result["nodeUri"],
                        neighbor_label,
                        parent)
                    )

        return attributes
Example #47
0
    def moStateOnTPS(self):
        '''
            check if module files state is saved on the TPS.
            if not all modules files are saved with the unchecked status !
        '''
        sqb = SparqlQueryBuilder(self.settings, self.session)
        ql = QueryLauncher(self.settings, self.session)
        results = ql.process_query(sqb.build_query_on_the_fly({
            'select': '?uri ?module ?comment ?version ?graph ?state',
            'from'  : [self.graph_modules],
            'query': '{\n'+
                     '?uri rdfs:label ?module .\n'+
                     '?uri rdfs:comment ?comment .\n'+
                     '?uri :module_version ?version .\n'+
                     '?uri :module_state ?state .\n'+
                     'OPTIONAL { ?uri :module_graph ?graph . } \n'+
                     '}\n'
        }, True).query)

        self.log.debug(' ***** module on TPS ***** ')
        listMoOnTps = {}
        for result in results:
            result['checked'] = (result['state'] == "ok")
            result['wait'] = (result['state'] == "wait")
            listMoOnTps[result['module']] = 0
            self.log.debug('module : '+result['module'])
            #=======================*************** A ENLEVER *********=======================================
            #pour debugger
            #if result['wait'] :
            #    result['wait'] = False
            #==============================================================

        self.log.debug(' ***** check Available Modules ***** ')

        requestAgain = False

        for mo in self.moduleFiles:
            self.log.debug(" --> module "+mo);
            if mo not in listMoOnTps:
                self.log.debug(" --====== > new module < =======");
                self.importMoSate(self.moduleFiles[mo],'off')
                requestAgain = True

        if requestAgain :
            return False

        return results
Example #48
0
    def check_email_password(self):
        """
        check if the password is the good password associate with the email
        """

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(sqa.get_password_with_email(self.email).query)

        ts_salt = result[0]['salt']
        ts_shapw = result[0]['shapw']

        concat = self.settings["askomics.salt"] + self.passwd + ts_salt
        shapw = hashlib.sha256(concat.encode('utf8')).hexdigest()

        return ts_shapw == shapw
Example #49
0
    def existing_relations(self):
        """
        Fetch from triplestore the existing relations if entities of the same name exist

        :return: a List of relation names
        :rtype: List
        """
        #FIXME: Useless function, always return an empty list
        self.log.debug("existing_relations")
        existing_relations = []

        sqg = SparqlQueryGraph(self.settings, self.session)
        ql = QueryLauncher(self.settings, self.session)

        results = ql.process_query(sqg.get_class_info_from_abstraction(self.headers[0]).query)

        return existing_relations
Example #50
0
    def list_private_graphs(self):
        """List the private graphs

        :returns: decription of the private graphs
        :rtype: dict
        """

        sqb = SparqlQueryGraph(self.settings, self.request.session)
        query_laucher = QueryLauncher(self.settings, self.request.session)

        res = query_laucher.process_query(sqb.get_user_graph_infos_with_count())

        named_graphs = []

        for index_result in range(len(res)):
            named_graphs.append(res[index_result]['g'])

        return named_graphs
Example #51
0
    def list_public_graphs(self):
        """list the public graphs

        :returns: description of the public graph
        :rtype: dict
        """

        sqb = SparqlQueryGraph(self.settings, self.request.session)
        query_laucher = QueryLauncher(self.settings, self.request.session)

        res = query_laucher.process_query(sqb.get_public_graphs())

        named_graphs = []
        print(res)
        for index_result in range(len(res)):
            named_graphs.append(res[index_result]['g'])

        return named_graphs
Example #52
0
    def existing_relations(self):
        """
        Fetch from triplestore the existing relations if entities of the same name exist

        :return: a List of relation names
        :rtype: List
        """
        #FIXME: Useless function, always return an empty list
        self.log.debug("existing_relations")
        existing_relations = []

        sqg = SparqlQueryGraph(self.settings, self.session)
        ql = QueryLauncher(self.settings, self.session)

        results = ql.process_query(
            sqg.get_class_info_from_abstraction(self.headers[0]).query)

        return existing_relations
Example #53
0
    def check_email_password(self):
        """
        check if the password is the good password associate with the email
        """

        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(
            sqa.get_password_with_email(self.email).query)

        ts_salt = result[0]['salt']
        ts_shapw = result[0]['shapw']

        concat = self.settings["askomics.salt"] + self.passwd + ts_salt
        shapw = hashlib.sha256(concat.encode('utf8')).hexdigest()

        return ts_shapw == shapw
Example #54
0
    def list_private_graphs(self):
        """List the private graphs

        :returns: decription of the private graphs
        :rtype: dict
        """

        sqb = SparqlQueryGraph(self.settings, self.request.session)
        query_laucher = QueryLauncher(self.settings, self.request.session)

        res = query_laucher.process_query(sqb.get_user_graph_infos_with_count().query)

        named_graphs = []

        for index_result in range(len(res)):
            named_graphs.append(res[index_result]['g'])

        return named_graphs
Example #55
0
    def list_public_graphs(self):
        """list the public graphs

        :returns: description of the public graph
        :rtype: dict
        """

        sqb = SparqlQueryGraph(self.settings, self.request.session)
        query_laucher = QueryLauncher(self.settings, self.request.session)

        res = query_laucher.process_query(sqb.get_public_graphs())

        named_graphs = []
        print(res)
        for index_result in range(len(res)):
            named_graphs.append(res[index_result]['g'])

        return named_graphs
Example #56
0
    def existing_relations(self):
        """
        Fetch from triplestore the existing relations if entities of the same name exist

        :return: a List of relation names
        :rtype: List
        """
        self.log.debug("existing_relations")
        existing_relations = []

        sqb = SparqlQueryBuilder(self.settings, self.session)
        ql = QueryLauncher(self.settings, self.session)

        sparql_template = self.get_template_sparql(self.ASKOMICS_get_class_info_from_abstraction_queryFile)
        query = sqb.load_from_file(sparql_template, {"nodeClass": self.headers[0]}).query

        results = ql.process_query(query)

        return existing_relations
Example #57
0
    def get_admin_blocked_by_email(self):
        """
        get the admin status of the user by his username
        """
        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(sqa.get_admin_blocked_by_email(self.email).query)

        results = {}

        if len(result) <= 0:
            results['blocked'] = True
            results['admin'] = True
        else:
            results['blocked'] = ParamManager.Bool(result[0]['blocked'])
            results['admin'] = ParamManager.Bool(result[0]['admin'])

        return results
Example #58
0
    def build_sparql_query_from_json(self, variates, constraintesRelations,
                                     limit, sendRequestToTPS):
        self.log.debug("variates")
        self.log.debug(variates)
        self.log.debug("constraintesRelations")
        self.log.debug(constraintesRelations)

        sqb = SparqlQueryBuilder(self.settings, self.session)
        ql = QueryLauncher(self.settings, self.session)
        res = ql.execute_query(sqb.get_list_named_graphs().query)

        namedGraphs = []

        #for indexResult in range(len(res['results']['bindings'])):
        #    namedGraphs.append(res['results']['bindings'][indexResult]['g']['value'])

        req = ""
        req += "SELECT DISTINCT " + ' '.join(variates) + "\n"
        #TODO OFI: External Service do not work and, anyway, graphes have to be selectionned by the user in the UI
        #
        #for graph in namedGraphs:
        #    req += "FROM "+ "<"+graph+ ">"+"\n"
        req += "WHERE \n"
        req += self.buildRecursiveBlock('', constraintesRelations)
        if limit != None and limit > 0:
            req += " LIMIT " + str(limit)

        sqb = SparqlQueryBuilder(self.settings, self.session)
        prefixes = sqb.header_sparql_config(req)
        query = prefixes + req

        results = {}

        if sendRequestToTPS:
            ql = QueryLauncher(self.settings, self.session)
            results = ql.process_query(query)
        else:
            # add comment inside query to inform user
            query = "# endpoint = " + self.get_param(
                "askomics.endpoint") + "\n" + query

        return results, query
Example #59
0
    def get_admin_blocked_by_email(self):
        """
        get the admin status of the user by his username
        """
        query_laucher = QueryLauncher(self.settings, self.session)
        sqa = SparqlQueryAuth(self.settings, self.session)

        result = query_laucher.process_query(
            sqa.get_admin_blocked_by_email(self.email).query)

        results = {}

        if len(result) <= 0:
            results['blocked'] = True
            results['admin'] = True
        else:
            results['blocked'] = ParamManager.Bool(result[0]['blocked'])
            results['admin'] = ParamManager.Bool(result[0]['admin'])

        return results
Example #60
0
    def get_prefix_uri(self):
        sqg = SparqlQueryGraph(self.settings, self.session)
        ql = QueryLauncher(self.settings, self.session)
        rs = ql.process_query(sqg.get_prefix_uri().query)
        results = {}
        r_buf = {}

        for r in rs:
            label = r['nodeLabel']
            prefix = r['prefUri']

            if label not in results:
                results[label] = []
                r_buf[label] = {}
                results[label].append(self.get_param("askomics.prefix"))
                r_buf[label][self.get_param("askomics.prefix")] = 0

            if prefix not in r_buf[label]:
                results[label].append(prefix)
                r_buf[label][prefix] = 0

        return results