Example #1
0
def getLocations(graph):
    locations = []
    global rdf, rdfs, ndl, bindings, rdfcompatmode
    sparqlGrph = SPARQLGraph(graph)
    for loc in graph.subjects(predicate=rdf["type"], object=ndl["Location"]):
        select = ("?hostName")
        where = [
            GraphPattern([
                ("?hostUri", ndl["locatedAt"], loc),
                ("?hostUri", ndl["name"], "?hostName"),
            ]),
            GraphPattern([
                ("?hostUri", ndl["locatedAt"], loc),
                ("?hostUri", rdfs["label"], "?hostName"),
            ])
        ]
        # Create a SPARQLGraph wrapper object out of the normal Graph
        # Make the query
        if rdfcompatmode:
            result = sparqlGrph.query(select, where)
        else:
            result = Query.query(sparqlGrph,
                                 select,
                                 where,
                                 initialBindings=bindings)
        if result:
            locations.append(result)
    return locations
Example #2
0
def getHostName(graph, ifUri):
    """
    Given a URI of an interface, return the name of the host
    If the host has a 'name' property, return that value.
    Otherwise, strip off the first part of the URI (until '#') and return the last part.
    """
    global rdf, rdfs, ndl, bindings, rdfcompatmode
    select = ("?hostUri", "?hostName")
    where = [
        GraphPattern([
            ("?hostUri", ndl["hasInterface"], ifUri),
            ("?hostUri", ndl["name"], "?hostName"),
        ]),
        GraphPattern([
            ("?hostUri", ndl["hasInterface"], ifUri),
            ("?hostUri", rdfs["label"], "?hostName"),
        ])
    ]
    # Create a SPARQLGraph wrapper object out of the normal Graph
    sparqlGrph = SPARQLGraph(graph)
    # Make the query
    if rdfcompatmode:
        result = sparqlGrph.query(select, where)
    else:
        result = Query.query(sparqlGrph,
                             select,
                             where,
                             initialBindings=bindings)
    if result:
        hostUri, hostName = result[0]
        ifName = ifUri.replace(hostUri + ":", "")
        return (hostName, ifName)
    else:
        return (ifUri[ifUri.find("#"):], "")
Example #3
0
    def getGeoPosition(self, foaf, sha1mail):
        """
        Obtain geography information from foaf
        
        @param foaf: a foaf uri
        @param sha1mail: mail addess enconded
        @return: coordinates      
        """

        sparqlGr = self.__getGraph(foaf)

        if (sparqlGr != None):

            select = ('?lat', '?long')
            where = GraphPattern([('?x', RDF['type'], FOAF['Person']),
                                  ('?x', FOAF['mbox_sha1sum'], sha1mail),
                                  ('?x', FOAF['based_near'], '?y'),
                                  ('?y', GEO['lat'], '?lat'),
                                  ('?y', GEO['long'], '?long')])

            result = sparqlGr.query(select, where)

            for one in result:
                return [one[0], one[1]]

        return [None, None]
Example #4
0
    def query(self):
        """
        Make a SPARQL query

        @return: posts result
        """

        sparqlGr = SPARQLGraph(self.graph)
        select = ('?post', '?postTitle', '?date', '?userName', '?content',
                  '?parent')
        where = GraphPattern([('?post', RDF['type'], SIOC['Post']),
                              ('?post', DC['title'], '?postTitle'),
                              ('?post', DCTERMS['created'], '?date'),
                              ('?post', SIOC['content'], '?content'),
                              ('?post', SIOC['has_creator'], '?user'),
                              ('?user', SIOC['name'], '?userName')])
        opt = GraphPattern([('?post', SIOC['reply_of'], '?parent')])
        posts = Query.query(sparqlGr, select, where, opt)
        return self.orderByDate(posts)
Example #5
0
    def process(self, input, output=None):
        """
        Process
        
        @param input: input file
        @param output: output file
        """

        if (output == None):
            output = '.'.join(input.split('.')[:-1]) + '.kml'

        graph = self.parse(input)

        #sparql query
        sparqlGr = sparqlGraph.SPARQLGraph(graph)
        select = ('?name', '?lat', '?lon', '?pic')
        where = GraphPattern([('?x', RDF['type'], SIOC['User']),
                              ('?x', SIOC['name'], '?name'),
                              ('?x', FOAF['based_near'], "?y"),
                              ('?y', GEO['long'], '?lon'),
                              ('?y', GEO['lat'], '?lat')])
        opt = GraphPattern([('?x', SIOC['avatar'], "?pic")])
        users = sparqlGr.query(select, where, opt)

        n = len(users)
        if (n > 0):
            kml = KML()

            #create places
            for (name, lat, lon, pic) in users:
                kml.addPlace(lat, lon, str(name), pic)

            #and dump to disk
            try:
                kml_file = open(output, 'w+')
                kml.write(kml_file)
                kml_file.flush()
                kml_file.close()
                print 'new KML file created in', output, 'with', n, 'points'
            except IOError, detail:
                print 'Error exporting coordinates to KML: ' + str(detail)
Example #6
0
 def query(self):
     """
     Make a SPARQL query
     
     @return: posts result
     """
     
     try:    
         sparqlGr = sparqlGraph.SPARQLGraph(self.graph)
         select = ('?post', '?postTitle', '?date', '?userName', '?content', '?parent')            
         where  = GraphPattern([('?post',    RDF['type'],            SIOC['Post']),
                                       ('?post',    DC['title'],            '?postTitle'),
                                       ('?post',    DCTERMS['created'],     '?date'),
                                       ('?post',    SIOC['content'],        '?content'),
                                       ('?post',    SIOC['has_creator'],    '?user'),
                                       ('?user',    SIOC['name'],           '?userName')])
         opt    = GraphPattern([('?post',    SIOC['reply_of'],       '?parent')])
         posts  = sparqlGr.query(select, where, opt)
         return self.orderByDate(posts)
     except Exception, details:
         print 'parsing exception:', str(details)
         return None
Example #7
0
 def enriched(self, graph):
     """
     Find if the graph is enriched with FOAF
     
     @param graph: graph
     @return: graph enriched (True/False)
     """
     
     sparqlGr = sparqlGraph.SPARQLGraph(graph)
     select = ('?foaf')
     where = GraphPattern(
                                  [('?user', RDF['type'], SIOC['User']),
                                   ('?user', RDFS['seeAlso'], '?foaf')])
     foafs = sparqlGr.query(select, where)
     
     return (len(foafs) > 0)
Example #8
0
def getConnections(graph):
    """
    Given a NDL triplet graph, return lists of external and
    internal connections.
    
    The method runs a SPARQL query on the graph.
    Next step is to filter out the equivalent connections, which is done using a
    stack, because lists cannot be altered while iterating over them.
    
    Difference between internal and external is currently based on whether the
    symmetric connectedTo property is present in the graph.
    
    The results are beautified using the getHostName method.
    """
    global rdf, rdfs, ndl, bindings, rdfcompatmode
    select = ("?ifA", "?ifB")
    where = GraphPattern([
        ("?ifA", ndl["connectedTo"], "?ifB"),
        ("?ifB", ndl["connectedTo"], "?ifA"),
    ])
    # Create a SPARQLGraph wrapper object out of the normal Graph
    sparqlGrph = SPARQLGraph(graph)
    # Make the query
    if rdfcompatmode:
        result = sparqlGrph.query(select, where)
    else:
        result = Query.query(sparqlGrph,
                             select,
                             where,
                             initialBindings=bindings)
    #print "Found %d connections" % len(result)
    internalConnections = []
    externalConnections = []
    while len(result) > 0:
        ifA, ifB = result.pop()
        if (ifB, ifA) in result:
            result.remove((ifB, ifA))
            internalConnections.append(
                (getHostName(graph, ifA), getHostName(graph, ifB)))
        else:
            externalConnections.append(
                (getHostName(graph, ifA), getHostName(graph, ifB)))
    locations = getLocations(graph)
    return internalConnections, externalConnections, locations
Example #9
0
def _buildGraphPattern(triples):
    # split strings into tuples of strings
    triples = map((lambda x: tuple(re.split(" ", x))), triples)
    # convert tuples of strings into tuples of RDFLib objects
    isIRI = lambda x: x[0] == "<" and x[-1] == ">"
    isLit = lambda x: x[0] == "'" and x[-1] == "'" or x[0] == '"' and x[
        -1] == '"'
    for i in range(len(triples)):
        sub = triples[i][0]
        pred = triples[i][1]
        obj = triples[i][2]
        # unescape and define objects for IRIs and literals
        if isIRI(sub): sub = URIRef(_unescape(sub[1:-1]))
        if isIRI(pred): pred = URIRef(_unescape(pred[1:-1]))
        if isIRI(obj): obj = URIRef(_unescape(obj[1:-1]))
        elif isLit(obj): obj = _unescape(obj[1:-1])
        # build final triple
        triples[i] = (sub, pred, obj)
    return GraphPattern(triples)
Example #10
0
    def getPic(self, foaf, sha1mail):
        """
        Get picture from FOAF
        
        @param foaf: a foaf uri
        @param sha1mail: mail addess enconded
        @return: picture url        
        """
        sparqlGr = self.__getGraph(foaf)

        if (sparqlGr != None):

            select = ('?pic')
            where = GraphPattern([('?x', RDF['type'], FOAF['Person']),
                                  ('?x', FOAF['mbox_sha1sum'], sha1mail),
                                  ('?x', FOAF['depiction'], '?pic')])

            result = sparqlGr.query(select, where)

            for one in result:
                return one

        return None
Example #11
0
 def __listPosts(self):
     """
     List post at cache
     """
     
     try:    
         sparqlGr = sparqlGraph.SPARQLGraph(self.graph)
         select = ('?post', '?title')            
         where  = GraphPattern([('?post', RDF['type'],   SIOC['Post']),
                                       ('?post', DC['title'], '?title')])
         posts  = sparqlGr.query(select, where)
         
         print len(posts), 'posts:'
         
         for post, title in posts:
             print post, 
             try:
                 print title
             except:
                 print '(bad formed title)'
             
     except Exception, details:
         print 'parsing exception:', str(details)
         return None
Example #12
0
   xmlns:foaf="http://xmlns.com/foaf/0.1/"
   xmlns:ns = "http://example.org/ns#"
>
        <foaf:Person>
                <foaf:name>Alice</foaf:name>
                <foaf:homepage rdf:resource="http://work.example.org"/>	
        </foaf:Person>
        <foaf:Person>
                <foaf:name>Bob</foaf:name>
                <foaf:mbox rdf:resource="mailto:[email protected]"/>
        </foaf:Person>
</rdf:RDF>
"""

select = ["?name", "?mbox", "?hpage"]
pattern = GraphPattern([("?x", ns_foaf["name"], "?name")])
#optional    = None
optional = [
    GraphPattern([("?x", ns_foaf["mbox"], "?mbox")]),
    GraphPattern([("?x", ns_foaf["homepage"], "?hpage")])
]
tripleStore = None
expected = '''
  ?name:  Alice
  ?mbox:  None
  ?hpage: http://work.example.org

  ?name:  Bob
  ?mbox:  mailto:[email protected]
  ?hpage: None
'''
Example #13
0
>
        <rdf:Description>
                <ns:p rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">42</ns:p>
                <ns:p rdf:datatype="http://example.org/datatype#specialDatatype">abc</ns:p>
                <ns:p>2005-02-27</ns:p>
                <ns:p xml:lang="en">cat</ns:p>
        </rdf:Description>
</rdf:RDF>


"""

from testSPARQL import ns_rdf
from testSPARQL import ns_rdfs
from testSPARQL import ns_dc
from testSPARQL import ns_foaf
from testSPARQL import ns_ns

from rdflib.Literal import Literal
import datetime
from rdflib.sparql.graphPattern import GraphPattern

select = ["?v"]
#pattern     = GraphPattern([("?v","?p",Literal("abc",datatype="http://example.org/datatype#specialDatatype"))])
pattern = GraphPattern([("?v", "?p", "abc")])
optional = []
tripleStore = None
expected = '''
EMPTY
'''
Example #14
0
   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:foaf="http://xmlns.com/foaf/0.1/"
   xmlns:ns = "http://example.org/ns#"
   xmlns:book = "http://example.org/book"
>
        <rdf:Description rdf:ID="book1">
                <dc:title>SPARQL Tutorial</dc:title>
                <ns:price rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">42</ns:price>
        </rdf:Description>
        <rdf:Description rdf:ID="book2">
                <dc:title>The Semantic Web</dc:title>
                <ns:price rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">23</ns:price>
        </rdf:Description>
</rdf:RDF>
"""

select = ["?title", "?price"]
pattern = GraphPattern([("?x", ns_dc["title"], "?title")])
optional = GraphPattern([("?x", ns_ns["price"], "?price")])
optional.addConstraint(lt("?price", 30))
tripleStore = None
expected = '''
  ?title: SPARQL Tutorial
  ?price: None

  ?title: The Semantic Web
  ?price: 23
'''
Example #15
0
>
        <rdf:Description rdf:ID="book1">
                <dc:title>SPARQL Tutorial</dc:title>
                <ns:price rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">42</ns:price>
        </rdf:Description>
        <rdf:Description rdf:ID="book2">
                <dc:title>The Semantic Web</dc:title>
                <ns:price rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">23</ns:price>
        </rdf:Description>
        <rdf:Description rdf:ID="book3">
                <dc:title>The Semantic Web Old</dc:title>
                <dc:date rdf:datatype="http://www.w3.org/2001/XMLSchema#date">2000-03-12</dc:date>
        </rdf:Description>
        <rdf:Description rdf:ID="book4">
                <dc:title>The Semantic Web New</dc:title>
                <dc:date rdf:datatype="http://www.w3.org/2001/XMLSchema#date">2005-03-02</dc:date>
        </rdf:Description>
</rdf:RDF>
"""

select = ["?title", "?price"]
pattern = GraphPattern([("?x", ns_dc["title"], "?title"),
                        ("?x", ns_ns["price"], "?price")])
pattern.addConstraint(lt("?price", 30))
optional = []
tripleStore = None
expected = '''
  ?title: The Semantic Web
  ?price: 23
'''
Example #16
0
        <rdf:Description>
                <foaf:name>Bob</foaf:name>
                <foaf:mbox>[email protected]</foaf:mbox>
        </rdf:Description>
</rdf:RDF>
"""


from testSPARQL import ns_rdf
from testSPARQL import ns_rdfs
from testSPARQL import ns_dc
from testSPARQL import ns_foaf
from testSPARQL import ns_ns
from testSPARQL import ns_book

from rdflib.Literal import Literal
from rdflib.sparql.graphPattern import GraphPattern

from rdflib.sparql.sparqlOperators import isURI


select = ["?name", "?mbox"]
pattern = GraphPattern([("?x", ns_foaf["name"], "?name"), ("?x", ns_foaf["mbox"], "?mbox")])
pattern.addConstraint(isURI("?mbox"))
optional = []
tripleStore = None
expected = """
  ?name: Alice
  ?mbox: mailto:[email protected]
"""
Example #17
0
                <dc:title>SPARQL Tutorial</dc:title>
                <ns:price rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">42</ns:price>
        </rdf:Description>
        <rdf:Description rdf:ID="book2">
                <dc:title>The Semantic Web</dc:title>
                <ns:price rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">23</ns:price>
        </rdf:Description>
        <rdf:Description rdf:ID="book3">
                <dc:title>The Semantic Web Old</dc:title>
                <dc:date rdf:datatype="http://www.w3.org/2001/XMLSchema#date">2000-03-12</dc:date>
        </rdf:Description>
        <rdf:Description rdf:ID="book4">
                <dc:title>The Semantic Web New</dc:title>
                <dc:date rdf:datatype="http://www.w3.org/2001/XMLSchema#date">2005-03-02</dc:date>
        </rdf:Description>
</rdf:RDF>
"""

select      = ["?title", "?price"]
pattern     = GraphPattern([("?x", ns_dc["title"],"?title"),("?x",ns_ns["price"],"?price")])
pattern.addConstraint(lt("?price",30))
optional    = []
tripleStore = None
expected = '''
  ?title: The Semantic Web
  ?price: 23
'''



Example #18
0
 def process(self, input, output=None):
     """
     Enrichement process
     
     @param input: input file
     @param output: output file
     """
     
     graph = self.parse(input)
     
     if not self.enriched(graph):
         
         if (output == None):
             output = '.'.join(input.split('.')[:-1]) + '.foaf.enrichment.rdf'
         
         #sparql query
         sparqlGr = sparqlGraph.SPARQLGraph(graph)
         select = ('?user', '?email_sha1sum')
         where = GraphPattern(
             [('?user', RDF['type'], SIOC['User']),
              ('?user', SIOC['email_sha1sum'], '?email_sha1sum')])
         users = sparqlGr.query(select, where)
         
         if (len(users) > 0):
             foafserv = FOAFS()
             n = 0
             
             graph.bind('foaf', FOAF)
             graph.bind('sioc', SIOC)
             graph.bind('geo', GEO)
             graph.bind('rdfs', RDFS)
             
             for (user, email_sha1sum) in users:
                 foaf = foafserv.getFoafFromSha(email_sha1sum)
                 if (foaf != None):
                     n += 1
                     
                     graph.add((user, RDFS['seeAlso'], URIRef(foaf)))
                     
                     lat, lon = foafserv.getGeoPosition(foaf, email_sha1sum)
                     if (lat != None and lon != None):                        
                         geo = BNode()
                         graph.add((user, FOAF['based_near'], geo))
                         graph.add((geo, RDF.type, GEO['Point']))        
                         graph.add((geo, GEO['lat'], Literal(lat)))
                         graph.add((geo, GEO['long'], Literal(lon)))
                 
                     pic = foafserv.getPic(foaf, email_sha1sum)
                     if (pic != None):
                         graph.add((user, SIOC['avatar'], URIRef(pic)))
 
                     
             #and dump to disk
             try:
                 rdf_file = open(output, 'w+')
                 graph.serialize(destination=rdf_file, format="pretty-xml")
                 rdf_file.flush()
                 rdf_file.close()
                 print 'new subscriber RDF file created in', output, 'enriched with', n, 'FOAF files'
             except IOError, detail:
                 print 'Error exporting subscriber to RDF: ' + str(detail)
                 
         else:
             print 'Nobody with FOAF description available in', input
Example #19
0
   xmlns:foaf="http://xmlns.com/foaf/0.1/"
   xmlns:ns = "http://example.org/ns#"
   xmlns:book = "http://example.org/book"
>
        <rdf:Description rdf:ID="book1">
                <dc:title>SPARQL Tutorial</dc:title>
                <ns:price rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">42</ns:price>
        </rdf:Description>
        <rdf:Description rdf:ID="book2">
                <dc:title>The Semantic Web</dc:title>
                <ns:price rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">23</ns:price>
        </rdf:Description>
</rdf:RDF>
"""

select      = ["?title", "?price"]
pattern     = GraphPattern([("?x", ns_dc["title"],"?title")])
optional    = GraphPattern([("?x",ns_ns["price"],"?price")])
optional.addConstraint(lt("?price",30))
tripleStore = None
expected = '''
  ?title: SPARQL Tutorial
  ?price: None

  ?title: The Semantic Web
  ?price: 23
'''



Example #20
0
rdfData = """<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:foaf="http://xmlns.com/foaf/0.1/"
   xmlns:ns = "http://example.org/ns#"
>
        <foaf:Person>
                <foaf:name>Alice</foaf:name>
                <foaf:mbox rdf:resource="mailto:[email protected]"/>
        </foaf:Person>
        <foaf:Person>
                <foaf:name>Bob</foaf:name>
        </foaf:Person>
</rdf:RDF>
"""

select = ["?name", "?mbox"]
pattern = GraphPattern([("?x", ns_foaf["name"], "?name")])
#optional    = None
optional = GraphPattern([("?x", ns_foaf["mbox"], "?mbox")])
tripleStore = None
expected = '''
  ?name: Alice
  ?mbox: mailto:[email protected]

  ?name: Bob
  ?mbox: None
'''
Example #21
0
   xmlns:dc   ="http://purl.org/dc/elements/1.1/"
   xmlns:foaf ="http://xmlns.com/foaf/0.1/"
   xmlns:ns   ="http://example.org/ns#"
   xmlns:dt   ="http://example.org/datatype#"
>
        <rdf:Description>
                <ns:p rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">42</ns:p>
                <ns:p rdf:datatype="http://example.org/datatype#specialDatatype">abc</ns:p>
                <ns:p>2005-02-27</ns:p>
                <ns:p xml:lang="en">cat</ns:p>
        </rdf:Description>
</rdf:RDF>
"""
from testSPARQL import ns_rdf
from testSPARQL import ns_rdfs
from testSPARQL import ns_dc
from testSPARQL import ns_foaf
from testSPARQL import ns_ns

from rdflib.Literal import Literal
import datetime
from rdflib.sparql.graphPattern import GraphPattern

select = ["?v"]
pattern = GraphPattern([("?v", "?p", Literal("cat", lang="en"))])
optional = []
tripleStore = None
expected = '''
?v : (some Bnode id)
'''
Example #22
0
from rdflib.sparql.graphPattern import GraphPattern

thresholdDate = datetime.date(2005, 01, 01)
rdfData = """<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:foaf="http://xmlns.com/foaf/0.1/"
   xmlns:ns = "http://example.org/ns#"
>
        <rdf:Description>
                <foaf:givenname>Alice</foaf:givenname>
                <foaf:family_name>Hacker</foaf:family_name>
        </rdf:Description>
        <rdf:Description>
                <foaf:givenname>Bob</foaf:givenname>
                <foaf:family_name>Hacker</foaf:family_name>
        </rdf:Description>
</rdf:RDF>
"""
select = []
pattern = GraphPattern([("?x", ns_foaf["givenname"], "?name"),
                        ("?x", ns_foaf["family_name"], "?fname")])
optional = []
bnode = BNode("v")  #PatternBNode("")
construct = GraphPattern([("?x", ns_vcard["N"], bnode),
                          (bnode, ns_vcard["givenName"], "?name"),
                          (bnode, ns_vcard["familyName"], "?fname")])
tripleStore = None
Example #23
0
rdfData = """<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
   xmlns:rdfs ="http://www.w3.org/2000/01/rdf-schema#"
   xmlns:rdf  ="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:dc   ="http://purl.org/dc/elements/1.1/"
   xmlns:foaf ="http://xmlns.com/foaf/0.1/"
   xmlns:ns   ="http://example.org/ns#"
   xmlns:dt   ="http://example.org/datatype#"
>
        <rdf:Description>
                <ns:p rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">42</ns:p>
                <ns:p rdf:datatype="http://example.org/datatype#specialDatatype">abc</ns:p>
                <ns:p>2005-02-27</ns:p>
                <ns:p xml:lang="en">cat</ns:p>
        </rdf:Description>
</rdf:RDF>
"""

from rdflib.Literal import Literal
import datetime
from rdflib.sparql.graphPattern import GraphPattern

select = ["?v"]
pattern = GraphPattern([("?v", "?p", "cat")])
optional = []
tripleStore = None
expected = '''
EMPTY
'''
Example #24
0
        </rdf:Description>
        <rdf:Description>
                <foaf:name>Bob</foaf:name>
                <foaf:mbox>[email protected]</foaf:mbox>
        </rdf:Description>
</rdf:RDF>
"""

from testSPARQL import ns_rdf
from testSPARQL import ns_rdfs
from testSPARQL import ns_dc
from testSPARQL import ns_foaf
from testSPARQL import ns_ns
from testSPARQL import ns_book

from rdflib.Literal import Literal
from rdflib.sparql.graphPattern import GraphPattern

from rdflib.sparql.sparqlOperators import isURI

select = ["?name", "?mbox"]
pattern = GraphPattern([("?x", ns_foaf["name"], "?name"),
                        ("?x", ns_foaf["mbox"], "?mbox")])
pattern.addConstraint(isURI("?mbox"))
optional = []
tripleStore = None
expected = '''
  ?name: Alice
  ?mbox: mailto:[email protected]
'''
Example #25
0
   xmlns:dt   ="http://example.org/datatype#"
>
        <rdf:Description>
                <ns:p rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">42</ns:p>
                <ns:p rdf:datatype="http://example.org/datatype#specialDatatype">abc</ns:p>
                <ns:p>2005-02-27</ns:p>
                <ns:p xml:lang="en">cat</ns:p>
        </rdf:Description>
</rdf:RDF>
"""

from testSPARQL import ns_rdf
from testSPARQL import ns_rdfs
from testSPARQL import ns_dc
from testSPARQL import ns_foaf
from testSPARQL import ns_ns

from rdflib.Literal import Literal
import datetime
from rdflib.sparql.graphPattern import GraphPattern

select      = ["?v"]
pattern     = GraphPattern([("?v","?p",42)])
optional    = []
tripleStore = None
expected = '''
?v : (some bnode id)
'''


Example #26
0
   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:dc0="http://purl.org/dc/elements/1.0/"
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:foaf="http://xmlns.com/foaf/0.1/"
   xmlns:ns = "http://example.org/ns#"
   xmlns:book = "http://example.org/book"
>
        <rdf:Description rdf:ID="book2">
                <dc0:title>SPARQL Query Language Tutorial</dc0:title>
                <dc0:creator>Alice</dc0:creator>
        </rdf:Description>
        <rdf:Description rdf:ID="book1">
                <dc:title>SPARQL Protocol Tutorial</dc:title>
                <dc:creator>Bob</dc:creator>
        </rdf:Description>
</rdf:RDF>
"""

select = ["?title"]
patt1 = GraphPattern([("?book", ns_dc0["title"], "?title")])
patt2 = GraphPattern([("?book", ns_dc["title"], "?title")])
pattern = [patt1, patt2]
optional = []
tripleStore = None
expected = '''
  ?title: SPARQL Query Language Tutorial

  ?title: SPARQL Protocol Tutorial
'''
Example #27
0
        </rdf:Description>
        <rdf:Description>
                <foaf:name>Bob</foaf:name>
                <foaf:mbox rdf:resource="mailto:[email protected]"/>
        </rdf:Description>
</rdf:RDF>
"""

from testSPARQL import ns_rdf
from testSPARQL import ns_rdfs
from testSPARQL import ns_dc
from testSPARQL import ns_foaf
from testSPARQL import ns_ns
from testSPARQL import ns_book

from rdflib.Literal import Literal

from rdflib.sparql.graphPattern import GraphPattern

select = ["?x", "?name"]
pattern = GraphPattern([("?x", ns_foaf["name"], "?name")])
optional = []
tripleStore = None
expected = '''
  ?x:   (some bnode)
  ?name: Alice

  ?x:   (some bnode)
  ?name: Bob
'''
Example #28
0
from rdflib.sparql.graphPattern import GraphPattern


# Careful to keep the <?xml declaration at the very beginning, otherwise the parser will fail...
rdfData ="""<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:foaf="http://xmlns.com/foaf/0.1/"
>
        <rdf:Description>
                <foaf:name>Johny Lee Outlaw</foaf:name>	
                <foaf:mbox rdf:resource="mailto:[email protected]"/>
        </rdf:Description>
</rdf:RDF>
"""

select      = ["?mbox","?junk"]
pattern     = GraphPattern([("?x",ns_foaf["name"],"Johny Lee Outlaw"),("?x",ns_foaf["mbox"],"?mbox")])
optional    = None
tripleStore = None
expected = '''
?mbox: mailto:[email protected]
?junk: None
'''



Example #29
0
from rdflib.Literal     import Literal
from rdflib.sparql.sparqlOperators import lt, ge
import datetime
from rdflib.sparql.graphPattern import GraphPattern

thresholdDate = datetime.date(2005,01,01)

rdfData = """<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:foaf="http://xmlns.com/foaf/0.1/"
   xmlns:ns = "http://example.org/ns#"
>
        <rdf:Description>
                <foaf:name>Alice</foaf:name>
                <foaf:mbox rdf:resource="mailto:[email protected]"/>
        </rdf:Description>
</rdf:RDF>
"""

select      = []
pattern     = GraphPattern([("?x",ns_foaf["name"],"?name")])
optional    = []
construct   = GraphPattern([(ns_person["Alice"],ns_vcard["FN"],"?name")])
tripleStore = None