コード例 #1
0
def get_entities():
    """ Get details for all Entities
    """
    query = '''
        PREFIX prov: <http://www.w3.org/ns/prov#>
        PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
        PREFIX proms: <http://promsns.org/def/proms#>
        SELECT DISTINCT ?e ?l
        WHERE {
            GRAPH ?g {
                { ?e a prov:Entity . }
                UNION
                { ?e a prov:Plan . }
                OPTIONAL { ?e rdfs:label ?l . }
            }
        }
        ORDER BY ?e
    '''
    entities = queries.query(query)
    entity_items = []
    # Check if nothing is returned
    if entities and 'results' in entities:
        for entity in entities['results']['bindings']:
            ret = {
                'e': urllib.parse.quote(str(entity['e']['value'])),
                'e_u': str(entity['e']['value']),
            }
            if entity.get('l'):
                ret['l'] = str(entity['l']['value'])
            entity_items.append(ret)
    return entity_items
コード例 #2
0
    def __init__(self, g):
        self.passed = True
        self.fail_reasons = []
        reporting_system_uri = None

        # get the ReportingSystem URI
        qres = g.query('''
        PREFIX proms: <http://promsns.org/def/proms#>
        SELECT ?rs
        WHERE {
            ?r proms:wasReportedBy ?rs .
        }
        ''')
        for r in qres:
            reporting_system_uri = str(r['rs'])

        # check to see if this ReportingSystem already exists in the provenance database
        q = '''
            PREFIX proms: <http://promsns.org/def/proms#>
            ASK
            WHERE { GRAPH ?g {
                <%(reporting_system_uri)s> ?p proms:ReportingSystem .
            }}
        ''' % {
            'reporting_system_uri': reporting_system_uri
        }
        if not queries.query(q)['boolean']:
            self.fail_reasons.append(
                'The Report does not refer to an existing ReportingSystem within the '
                'provenance database')
            self.passed = False

        Rule.__init__(
            self,
            'Report\'s Reporting System',
            'Reports can only be lodged for ReportingSystems already in the provenance database',
            'PROMS system',
            self.passed,
            self.fail_reasons,
            1,  # the number of individual tests
            len(self.fail_reasons)  # the number of tests failed
        )
コード例 #3
0
def get_agents():
    """ Get all Agents in the provenance database"""

    q = '''
        PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
        PREFIX prov: <http://www.w3.org/ns/prov#>
        SELECT ?ag ?label
        WHERE { GRAPH ?g {
            ?ag a prov:Agent ;
                rdfs:label ?label .
          }
        }
        '''
    agents = []
    for row in queries.query(q)['results']['bindings']:
        agents.append({
            'uri': row['ag']['value'],
            'label': row['label']['value']
        })

    return agents
コード例 #4
0
def get_reportingsystems():
    """ Get all ReportingSystem details"""
    query = '''
        PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
        PREFIX proms: <http://promsns.org/def/proms#>
        SELECT ?rs ?t
        WHERE {
          ?rs a proms:ReportingSystem .
          ?rs rdfs:label ?t .
        }
    '''
    reportingsystems = queries.query(query)
    reportingsystem_items = []
    # Check if nothing is returned
    if reportingsystems and 'results' in reportingsystems:
        for reportingsystem in reportingsystems['results']['bindings']:
            ret = {
                'rs': urllib.parse.quote(str(reportingsystem['rs']['value'])),
                'rs_u': str(reportingsystem['rs']['value'])
            }
            if reportingsystem.get('t'):
                ret['t'] = str(reportingsystem['t']['value'])
            reportingsystem_items.append(ret)
    return reportingsystem_items
コード例 #5
0
def sparql():
    # Query submitted
    if request.method == 'POST':
        '''
        Pass on the SPARQL query to the underlying system PROMS is using (Fuseki etc.)
        '''
        query = None
        if request.content_type == 'application/x-www-form-urlencoded':
            '''
            https://www.w3.org/TR/2013/REC-sparql11-protocol-20130321/#query-via-post-urlencoded

            2.1.2 query via POST with URL-encoded parameters

            Protocol clients may send protocol requests via the HTTP POST method by URL encoding the parameters. When
            using this method, clients must URL percent encode all parameters and include them as parameters within the
            request body via the application/x-www-form-urlencoded media type with the name given above. Parameters must
            be separated with the ampersand (&) character. Clients may include the parameters in any order. The content
            type header of the HTTP request must be set to application/x-www-form-urlencoded.
            '''
            if request.form.get('query') is None:
                return api_functions.client_error_response(
                    'Your POST request to PROMS\' SPARQL endpoint must contain a \'query\' parameter if form '
                    'posting is used.')
            else:
                query = request.form.get('query')
        elif request.content_type == 'application/sparql-query':
            '''
            https://www.w3.org/TR/2013/REC-sparql11-protocol-20130321/#query-via-post-direct

            2.1.3 query via POST directly

            Protocol clients may send protocol requests via the HTTP POST method by including the query directly and
            unencoded as the HTTP request message body. When using this approach, clients must include the SPARQL query
            string, unencoded, and nothing else as the message body of the request. Clients must set the content type
            header of the HTTP request to application/sparql-query. Clients may include the optional default-graph-uri
            and named-graph-uri parameters as HTTP query string parameters in the request URI. Note that UTF-8 is the
            only valid charset here.
            '''
            query = request.data  # get the raw request
            if query is None:
                return api_functions.client_error_response(
                    'Your POST request to PROMS\' SPARQL endpoint must contain the query in plain text in the '
                    'POST body if the Content-Type \'application/sparql-query\' is used.'
                )

        # sorry, we only return JSON results. See the service description!
        try:
            query_result = queries.query(query)
        except ValueError as e:
            return render_template('function_sparql.html',
                                   query=query,
                                   query_result='No results: ' + str(e)), 400
        except ConnectionError:
            return render_template('error_db_connection.html'), 500

        if query_result and 'results' in query_result:
            query_result = json.dumps(query_result['results']['bindings'])
        else:
            query_result = json.dumps(query_result)

        # resond to a form or with a raw result
        if 'form' in request.values and request.values['form'].lower(
        ) == 'true':
            return render_template('function_sparql.html',
                                   query=query,
                                   query_result=query_result)
        else:
            return Response(json.dumps(query_result),
                            status=200,
                            mimetype="application/sparql-results+json")
    # No query, display form
    else:  # GET
        if request.args.get('query') is not None:
            # SPARQL GET request
            '''
            https://www.w3.org/TR/2013/REC-sparql11-protocol-20130321/#query-via-get

            2.1.1 query via GET

            Protocol clients may send protocol requests via the HTTP GET method. When using the GET method, clients must
            URL percent encode all parameters and include them as query parameter strings with the names given above.

            HTTP query string parameters must be separated with the ampersand (&) character. Clients may include the
            query string parameters in any order.

            The HTTP request MUST NOT include a message body.
            '''
            # following check invalid due to higher order if/else
            # if request.args.get('query') is None:
            #     return Response(
            #         'Your GET request to PROMS\' SPARQL endpoint must contain a \'query\' query string argument.',
            #         status=400,
            #         mimetype="text/plain")
            query = request.args.get('query')
            query_result = queries.query(query)
            return Response(json.dumps(query_result),
                            status=200,
                            mimetype="application/sparql-results+json")
        else:
            # SPARQL Service Description
            '''
            https://www.w3.org/TR/sparql11-service-description/#accessing

            SPARQL services made available via the SPARQL Protocol should return a service description document at the
            service endpoint when dereferenced using the HTTP GET operation without any query parameter strings
            provided. This service description must be made available in an RDF serialization, may be embedded in
            (X)HTML by way of RDFa, and should use content negotiation if available in other RDF representations.
            '''

            acceptable_mimes = [x[0] for x in LDAPI.MIMETYPES_PARSERS
                                ] + ['text/html']
            best = request.accept_mimetypes.best_match(acceptable_mimes)
            if best == 'text/html':
                # show the SPARQL query form
                query = request.args.get('query')
                return render_template('function_sparql.html', query=query)
            elif best is not None:
                return Response(api_functions.get_sparql_service_description([
                    item for item in LDAPI.MIMETYPES_PARSERS if item[0] == best
                ]),
                                status=200,
                                mimetype=best)
            else:
                return api_functions.client_error_response(
                    'Accept header must be one of ' +
                    ', '.join(acceptable_mimes) + '.')