示例#1
0
class GraphTest(test.TestCase):
    """
    Testing the basic graph functionality.

    Heavily based on https://github.com/RDFLib/rdflib-postgresql/blob/master/test/graph_case.py
    """
    store_name = "Django"
    storetest = True
    path = ''
    create = True

    michel = URIRef(u'michel')
    tarek = URIRef(u'tarek')
    bob = URIRef(u'bob')
    likes = URIRef(u'likes')
    hates = URIRef(u'hates')
    pizza = URIRef(u'pizza')
    cheese = URIRef(u'cheese')

    def setUp(self):
        self.graph = Graph(store=self.store_name)
        self.graph.destroy(self.path)
        self.graph.open(self.path, create=self.create)

    def tearDown(self):
        self.graph.destroy(self.path)
        self.graph.close()

    def addStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese

        self.graph.add((tarek, likes, pizza))
        self.graph.add((tarek, likes, cheese))
        self.graph.add((michel, likes, pizza))
        self.graph.add((michel, likes, cheese))
        self.graph.add((bob, likes, cheese))
        self.graph.add((bob, hates, pizza))
        self.graph.add((bob, hates, michel))
        self.graph.commit()

    def removeStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese

        self.graph.remove((tarek, likes, pizza))
        self.graph.remove((tarek, likes, cheese))
        self.graph.remove((michel, likes, pizza))
        self.graph.remove((michel, likes, cheese))
        self.graph.remove((bob, likes, cheese))
        self.graph.remove((bob, hates, pizza))
        self.graph.remove((bob, hates, michel))

    def testAdd(self):
        self.addStuff()

    def testRemove(self):
        self.addStuff()
        self.removeStuff()

    def testTriples(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        triples = self.graph.triples
        Any = None

        self.addStuff()

        # unbound subjects
        self.assertEquals(len(list(triples((Any, likes, pizza)))), 2)
        self.assertEquals(len(list(triples((Any, hates, pizza)))), 1)
        self.assertEquals(len(list(triples((Any, likes, cheese)))), 3)
        self.assertEquals(len(list(triples((Any, hates, cheese)))), 0)

        # unbound objects
        self.assertEquals(len(list(triples((michel, likes, Any)))), 2)
        self.assertEquals(len(list(triples((tarek, likes, Any)))), 2)
        self.assertEquals(len(list(triples((bob, hates, Any)))), 2)
        self.assertEquals(len(list(triples((bob, likes, Any)))), 1)

        # unbound predicates
        self.assertEquals(len(list(triples((michel, Any, cheese)))), 1)
        self.assertEquals(len(list(triples((tarek, Any, cheese)))), 1)
        self.assertEquals(len(list(triples((bob, Any, pizza)))), 1)
        self.assertEquals(len(list(triples((bob, Any, michel)))), 1)

        # unbound subject, objects
        self.assertEquals(len(list(triples((Any, hates, Any)))), 2)
        self.assertEquals(len(list(triples((Any, likes, Any)))), 5)

        # unbound predicates, objects
        self.assertEquals(len(list(triples((michel, Any, Any)))), 2)
        self.assertEquals(len(list(triples((bob, Any, Any)))), 3)
        self.assertEquals(len(list(triples((tarek, Any, Any)))), 2)

        # unbound subjects, predicates
        self.assertEquals(len(list(triples((Any, Any, pizza)))), 3)
        self.assertEquals(len(list(triples((Any, Any, cheese)))), 3)
        self.assertEquals(len(list(triples((Any, Any, michel)))), 1)

        # all unbound
        self.assertEquals(len(list(triples((Any, Any, Any)))), 7)
        self.removeStuff()
        self.assertEquals(len(list(triples((Any, Any, Any)))), 0)

    def testConnected(self):
        graph = self.graph
        self.addStuff()
        self.assertEquals(True, graph.connected())

        jeroen = URIRef("jeroen")
        unconnected = URIRef("unconnected")

        graph.add((jeroen, self.likes, unconnected))

        self.assertEquals(False, graph.connected())

    def testSub(self):
        g1 = Graph()
        g2 = Graph()

        g1.add((self.tarek, self.likes, self.pizza))
        g1.add((self.bob, self.likes, self.cheese))

        g2.add((self.bob, self.likes, self.cheese))

        g3 = g1 - g2

        self.assertEquals(len(g3), 1)
        self.assertEquals((self.tarek, self.likes, self.pizza) in g3, True)
        self.assertEquals((self.tarek, self.likes, self.cheese) in g3, False)

        self.assertEquals((self.bob, self.likes, self.cheese) in g3, False)

        g1 -= g2

        self.assertEquals(len(g1), 1)
        self.assertEquals((self.tarek, self.likes, self.pizza) in g1, True)
        self.assertEquals((self.tarek, self.likes, self.cheese) in g1, False)

        self.assertEquals((self.bob, self.likes, self.cheese) in g1, False)

    def testGraphAdd(self):
        g1 = Graph()
        g2 = Graph()

        g1.add((self.tarek, self.likes, self.pizza))

        g2.add((self.bob, self.likes, self.cheese))

        g3 = g1 + g2

        self.assertEquals(len(g3), 2)
        self.assertEquals((self.tarek, self.likes, self.pizza) in g3, True)
        self.assertEquals((self.tarek, self.likes, self.cheese) in g3, False)

        self.assertEquals((self.bob, self.likes, self.cheese) in g3, True)

        g1 += g2

        self.assertEquals(len(g1), 2)
        self.assertEquals((self.tarek, self.likes, self.pizza) in g1, True)
        self.assertEquals((self.tarek, self.likes, self.cheese) in g1, False)

        self.assertEquals((self.bob, self.likes, self.cheese) in g1, True)

    def testGraphIntersection(self):
        g1 = Graph()
        g2 = Graph()

        g1.add((self.tarek, self.likes, self.pizza))
        g1.add((self.michel, self.likes, self.cheese))

        g2.add((self.bob, self.likes, self.cheese))
        g2.add((self.michel, self.likes, self.cheese))

        g3 = g1 * g2

        self.assertEquals(len(g3), 1)
        self.assertEquals((self.tarek, self.likes, self.pizza) in g3, False)
        self.assertEquals((self.tarek, self.likes, self.cheese) in g3, False)

        self.assertEquals((self.bob, self.likes, self.cheese) in g3, False)

        self.assertEquals((self.michel, self.likes, self.cheese) in g3, True)

        g1 *= g2

        self.assertEquals(len(g1), 1)

        self.assertEquals((self.tarek, self.likes, self.pizza) in g1, False)
        self.assertEquals((self.tarek, self.likes, self.cheese) in g1, False)

        self.assertEquals((self.bob, self.likes, self.cheese) in g1, False)

        self.assertEquals((self.michel, self.likes, self.cheese) in g1, True)
示例#2
0
class GraphTest(TestCase):
    """
    Testing the basic graph functionality.

    Heavily based on https://github.com/RDFLib/rdflib-postgresql/blob/master/test/graph_case.py
    """  # noqa: E501
    store_name = "Django"
    storetest = True
    path = ''
    create = True

    michel = URIRef(u'michel')
    tarek = URIRef(u'tarek')
    bob = URIRef(u'bob')
    likes = URIRef(u'likes')
    hates = URIRef(u'hates')
    pizza = URIRef(u'pizza')
    cheese = URIRef(u'cheese')

    def setUp(self):
        self.graph = Graph(store=self.store_name)
        self.graph.destroy(self.path)
        self.graph.open(self.path, create=self.create)

    def tearDown(self):
        self.graph.destroy(self.path)
        self.graph.close()

    def addStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese

        self.graph.add((tarek, likes, pizza))
        self.graph.add((tarek, likes, cheese))
        self.graph.add((michel, likes, pizza))
        self.graph.add((michel, likes, cheese))
        self.graph.add((bob, likes, cheese))
        self.graph.add((bob, hates, pizza))
        self.graph.add((bob, hates, michel))
        self.graph.commit()

    def removeStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese

        self.graph.remove((tarek, likes, pizza))
        self.graph.remove((tarek, likes, cheese))
        self.graph.remove((michel, likes, pizza))
        self.graph.remove((michel, likes, cheese))
        self.graph.remove((bob, likes, cheese))
        self.graph.remove((bob, hates, pizza))
        self.graph.remove((bob, hates, michel))

    def testAdd(self):
        self.addStuff()

    def testRemove(self):
        self.addStuff()
        self.removeStuff()

    def testTriples(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        triples = self.graph.triples
        Any = None

        self.addStuff()

        # unbound subjects
        self.assertEquals(len(list(triples((Any, likes, pizza)))), 2)
        self.assertEquals(len(list(triples((Any, hates, pizza)))), 1)
        self.assertEquals(len(list(triples((Any, likes, cheese)))), 3)
        self.assertEquals(len(list(triples((Any, hates, cheese)))), 0)

        # unbound objects
        self.assertEquals(len(list(triples((michel, likes, Any)))), 2)
        self.assertEquals(len(list(triples((tarek, likes, Any)))), 2)
        self.assertEquals(len(list(triples((bob, hates, Any)))), 2)
        self.assertEquals(len(list(triples((bob, likes, Any)))), 1)

        # unbound predicates
        self.assertEquals(len(list(triples((michel, Any, cheese)))), 1)
        self.assertEquals(len(list(triples((tarek, Any, cheese)))), 1)
        self.assertEquals(len(list(triples((bob, Any, pizza)))), 1)
        self.assertEquals(len(list(triples((bob, Any, michel)))), 1)

        # unbound subject, objects
        self.assertEquals(len(list(triples((Any, hates, Any)))), 2)
        self.assertEquals(len(list(triples((Any, likes, Any)))), 5)

        # unbound predicates, objects
        self.assertEquals(len(list(triples((michel, Any, Any)))), 2)
        self.assertEquals(len(list(triples((bob, Any, Any)))), 3)
        self.assertEquals(len(list(triples((tarek, Any, Any)))), 2)

        # unbound subjects, predicates
        self.assertEquals(len(list(triples((Any, Any, pizza)))), 3)
        self.assertEquals(len(list(triples((Any, Any, cheese)))), 3)
        self.assertEquals(len(list(triples((Any, Any, michel)))), 1)

        # all unbound
        self.assertEquals(len(list(triples((Any, Any, Any)))), 7)
        self.removeStuff()
        self.assertEquals(len(list(triples((Any, Any, Any)))), 0)

    def testConnected(self):
        graph = self.graph
        self.addStuff()
        self.assertEquals(True, graph.connected())

        jeroen = URIRef("jeroen")
        unconnected = URIRef("unconnected")

        graph.add((jeroen, self.likes, unconnected))

        self.assertEquals(False, graph.connected())

    def testSub(self):
        g1 = Graph()
        g2 = Graph()

        g1.add((self.tarek, self.likes, self.pizza))
        g1.add((self.bob, self.likes, self.cheese))

        g2.add((self.bob, self.likes, self.cheese))

        g3 = g1 - g2

        self.assertEquals(len(g3), 1)
        self.assertEquals((self.tarek, self.likes, self.pizza) in g3, True)
        self.assertEquals((self.tarek, self.likes, self.cheese) in g3, False)

        self.assertEquals((self.bob, self.likes, self.cheese) in g3, False)

        g1 -= g2

        self.assertEquals(len(g1), 1)
        self.assertEquals((self.tarek, self.likes, self.pizza) in g1, True)
        self.assertEquals((self.tarek, self.likes, self.cheese) in g1, False)

        self.assertEquals((self.bob, self.likes, self.cheese) in g1, False)

    def testGraphAdd(self):
        g1 = Graph()
        g2 = Graph()

        g1.add((self.tarek, self.likes, self.pizza))

        g2.add((self.bob, self.likes, self.cheese))

        g3 = g1 + g2

        self.assertEquals(len(g3), 2)
        self.assertEquals((self.tarek, self.likes, self.pizza) in g3, True)
        self.assertEquals((self.tarek, self.likes, self.cheese) in g3, False)

        self.assertEquals((self.bob, self.likes, self.cheese) in g3, True)

        g1 += g2

        self.assertEquals(len(g1), 2)
        self.assertEquals((self.tarek, self.likes, self.pizza) in g1, True)
        self.assertEquals((self.tarek, self.likes, self.cheese) in g1, False)

        self.assertEquals((self.bob, self.likes, self.cheese) in g1, True)

    def testGraphIntersection(self):
        g1 = Graph()
        g2 = Graph()

        g1.add((self.tarek, self.likes, self.pizza))
        g1.add((self.michel, self.likes, self.cheese))

        g2.add((self.bob, self.likes, self.cheese))
        g2.add((self.michel, self.likes, self.cheese))

        g3 = g1 * g2

        self.assertEquals(len(g3), 1)
        self.assertEquals((self.tarek, self.likes, self.pizza) in g3, False)
        self.assertEquals((self.tarek, self.likes, self.cheese) in g3, False)

        self.assertEquals((self.bob, self.likes, self.cheese) in g3, False)

        self.assertEquals((self.michel, self.likes, self.cheese) in g3, True)

        g1 *= g2

        self.assertEquals(len(g1), 1)

        self.assertEquals((self.tarek, self.likes, self.pizza) in g1, False)
        self.assertEquals((self.tarek, self.likes, self.cheese) in g1, False)

        self.assertEquals((self.bob, self.likes, self.cheese) in g1, False)

        self.assertEquals((self.michel, self.likes, self.cheese) in g1, True)
示例#3
0
class RDFStore:
	configString = "/var/tmp/rdfstore"
	def __init__(self):
		self.nsDict = {}
		pass
	
	def build_graph(self):
				
		self.nsDict['blog'] = Namespace('http://rdflib.net/blog/') 
		self.graph.bind("blog", "http://rdflib.net/blog/")				
		self.nsDict['blogger_id'] = Namespace('http://rdflib.net/blog/blogger_id/')
		self.graph.bind("blogger_id", "http://rdflib.net/blog/blogger_id/")	
		self.nsDict['blog_url'] = Namespace('http://rdflib.net/blog/blog_url/')
		self.graph.bind("blog_url", "http://rdflib.net/blog/blog_url/")	
		self.nsDict['dbpprop'] = Namespace('http://dbpedia.org/property/')
		self.graph.bind("dbpprop", "http://dbpedia.org/property/")		
		self.nsDict['foaf'] = Namespace('http://xmlns.com/foaf/0.1/')
		self.graph.bind("foaf", "http://xmlns.com/foaf/0.1/")	
		self.nsDict['owl']  = Namespace('http://www.w3.org/2002/07/owl#')
		self.graph.bind("owl", "http://www.w3.org/2002/07/owl#")		
		self.nsDict['dcterms'] = Namespace('http://purl.org/dc/terms/')
		self.graph.bind("dcterms", "http://purl.org/dc/terms/")		
		self.nsDict['dbpowl'] = Namespace('http://dbpedia.org/ontology/')
		self.graph.bind("dbpowl", "http://dbpedia.org/ontology/")		
		self.nsDict['rdfs']  = Namespace('http://www.w3.org/2000/01/rdf-schema#')
		self.graph.bind("rdfs", "http://www.w3.org/2000/01/rdf-schema#")		
		self.nsDict['rdf'] = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
		self.graph.bind("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
		 		
		#Prabhjeet
		blogger_id = self.nsDict['blogger_id']
		rdf = self.nsDict['rdf'] 
		owl = self.nsDict['owl'] 
		blog = self.nsDict['blog']
		dbpowl = self.nsDict['dbpowl']
		foaf = self.nsDict['foaf'] 
		self.graph.add((blogger_id, rdf['type'], owl['DatatypeProperty']))
		self.graph.add((blog[blogger_id], foaf['name'], Literal('name')))
		self.graph.add((blog[blogger_id], rdf['type'], owl['DatatypeProperty']))
		self.graph.add((dbpowl['blog'], rdf['type'], owl['ObjectProperty']))

		self.graph.commit()
	
	def parse_data(self,filename):
		#xmldoc = open(filename, "rU")
		#rss = parse(xmldoc)
                blog = self.nsDict['blog']
                foaf = self.nsDict['foaf']
                dcterms = self.nsDict['dcterms'] 
		ldict  = None
		with open(filename,'r') as f:
			ldict = json.loads(f.read())
		for post in ldict:
			text = post['post']
			id = post['id']
			blogger_id1 = post['id']
			#name1 = post['tags']
			date = post['date']
			title = post['title']
                        self.graph.add((blog,blogger_id1,Literal(blogger_id1)))
			#self.graph.add((blog[blogger_id1],foaf['name'],Literal(name1)))
			self.graph.add((blog[blogger_id1],dcterms['title'],Literal(title)))
			self.graph.add((blog[blogger_id1],dcterms['date'],Literal(date)))
		'''	
		for place in rss.getElementsByTagName('place'):
			name1 = place.getElementsByTagName('name1')[0].firstChild.nodeValue
			blogger_id1 = place.getElementsByTagName('blogger-id')[0].firstChild.nodeValue
			title1 = place.getElementsByTagName('title')[0].firstChild.nodeValue
			url1 = place.getElementsByTagName('url')[0].firstChild.nodeValue
			date1 = place.getElementsByTagName('date')[0].firstChild.nodeValue
			expense = place.getElementsByTagName('expense')[0].firstChild.nodeValue
			
			
			blog  = self.nsDict['blog']
			foaf = self.nsDict['foaf']
			dcterms = self.nsDict['dcterms'] 
			self.graph.add((blog,blogger_id1,Literal(blogger_id1)))
			self.graph.add((blog[blogger_id1],foaf['name'],Literal(name1)))
			self.graph.add((blog[blogger_id1],dcterms['title'],Literal(title1)))
			self.graph.add((blog[blogger_id1],dcterms['date'],Literal(date1)))
		'''
			
		self.graph.commit()

	def open_store(self):
		default_graph_uri = "http://rdflib.net/rdfstore"
		# open existing store or create new one
		#store = getStore() # if store does not exist, then new store returned
		
		# RDF store section:
		configString = "/var/tmp/rdfstore"
		
		# Get the Sleepycat plugin.
		store = plugin.get('Sleepycat', Store)('rdfstore')		
		# Open previously created store, or create it if it doesn't exist yet
		path = mkdtemp()
		rt = store.open('rdfstore', create=False)
		#print rt
		#print path
		
		if rt == NO_STORE:
			print "Creating new store"
			# There is no underlying Sleepycat infrastructure, create it
			store.open('rdfstore', create=True)        
		else:
			print "store exists "
			#assert rt == VALID_STORE, "The underlying store is corrupt"

		self.graph = Graph(store,identifier = URIRef(default_graph_uri))		
		self.build_graph()	
		        				        
		'''
		print_RDF_triples(graph)
		#print_RDF_XML(graph)
		graph.commit()
		#create_RDF_File(graph)
		graph.close(commit_pending_transaction=True)

		'''

	def run_Query(self,queryString):
		qres = self.graph.query(queryString,
							initNs=dict(foaf=Namespace("http://xmlns.com/foaf/0.1/"),
							blog = Namespace('http://rdflib.net/blog/'),
							blogger_id = Namespace('http://rdflib.net/blog/blogger_id/'))
							)
		for row in qres.result:
			print row
	
	
	def print_RDF_XML(self):
	    #print graph.serialize(format="pretty-xml")
	    print self.graph.serialize()

	def print_RDF_triples(self):
		print "Triples in graph after add: ", len(graph)
		
		#Iterate over triples in graph and print them out.
		print "--- printing raw triples ---"
		for s, p, o in self.graph:
		        print s, p, o

	def print_RDF_Maker(self):
	    # For each foaf:Project in the self.graph print out its maker.
	    print "--- printing MAKERS ---"
	    for game in self.graph.subjects(RDF.type, FOAF["Project"]):
	            for madeby in self.graph.objects(game, FOAF["maker"]):
	                    print madeby
			
	def removeFromStore(self):
		rdflib = Namespace('http://rdflib.net/games/')
		self.graph.bind("game", "http://rdflib.net/games/")
		self.graph.remove((rdflib['game:2'], rdflib['name'], Literal('Ignition')))
		self.graph.commit()
		#str(graph)

	def sample_query(self, querystring):
	    print "Query enter"
	    processor = plugin.get('sparql', rdflib.query.Processor)(self.graph)
	    result = plugin.get('sparql', rdflib.query.Result)
	    
	    ns = dict(self.graph.namespace_manager.namespaces())
	    return result(processor.query(querystring, initNs=ns))
示例#4
0
class TestLevelDBGraphCore(unittest.TestCase):
    def setUp(self):
        store = "LevelDB"
        self.graph = Graph(store=store)
        self.path = configString
        self.graph.open(self.path, create=True)

    def tearDown(self):
        self.graph.destroy(self.path)
        try:
            self.graph.close()
        except:
            pass
        if getattr(self, 'path', False) and self.path is not None:
            if os.path.exists(self.path):
                if os.path.isdir(self.path):
                    shutil.rmtree(self.path)
                elif len(self.path.split(':')) == 1:
                    os.unlink(self.path)
                else:
                    os.remove(self.path)

    def test_namespaces(self):
        self.graph.bind("dc", "http://http://purl.org/dc/elements/1.1/")
        self.graph.bind("foaf", "http://xmlns.com/foaf/0.1/")
        self.assert_(len(list(self.graph.namespaces())) == 5)
        self.assert_(('foaf', rdflib.term.URIRef(u'http://xmlns.com/foaf/0.1/')
                      ) in list(self.graph.namespaces()))

    def test_readable_index(self):
        print(readable_index(111))

    def test_create_db(self):
        michel = rdflib.URIRef(u'michel')
        likes = rdflib.URIRef(u'likes')
        pizza = rdflib.URIRef(u'pizza')
        cheese = rdflib.URIRef(u'cheese')
        self.graph.add((michel, likes, pizza))
        self.graph.add((michel, likes, cheese))
        self.graph.commit()
        self.graph.store.close()
        if getattr(self, 'path', False) and self.path is not None:
            if os.path.exists(self.path):
                if os.path.isdir(self.path):
                    shutil.rmtree(self.path)
                elif len(self.path.split(':')) == 1:
                    os.unlink(self.path)
                else:
                    os.remove(self.path)
        self.graph.store.open(self.path, create=True)
        ntriples = self.graph.triples((None, None, None))
        self.assert_(len(list(ntriples)) == 0)

    def test_missing_db_exception(self):
        self.graph.store.close()
        if getattr(self, 'path', False) and self.path is not None:
            if os.path.exists(self.path):
                if os.path.isdir(self.path):
                    shutil.rmtree(self.path)
                elif len(self.path.split(':')) == 1:
                    os.unlink(self.path)
                else:
                    os.remove(self.path)
        self.graph.store.open(self.path, create=True)
        ntriples = self.graph.triples((None, None, None))
        self.assert_(len(list(ntriples)) == 0)

    def test_reopening_db(self):
        michel = rdflib.URIRef(u'michel')
        likes = rdflib.URIRef(u'likes')
        pizza = rdflib.URIRef(u'pizza')
        cheese = rdflib.URIRef(u'cheese')
        self.graph.add((michel, likes, pizza))
        self.graph.add((michel, likes, cheese))
        self.graph.commit()
        self.graph.store.close()
        self.graph.store.open(self.path, create=False)
        ntriples = self.graph.triples((None, None, None))
        self.assert_(len(list(ntriples)) == 2)

    def test_reopening_missing_db(self):
        self.graph.store.close()
        self.assertRaises(ValueError,
                          self.graph.store.open, ('/tmp/NotAnExistingDB'),
                          create=False)

    def test_isopen_db(self):
        self.assert_(self.graph.store.is_open() == True)
        self.graph.store.close()
        self.assert_(self.graph.store.is_open() == False)
示例#5
0
class TestKyotoCabinetGraphCore(unittest.TestCase):
    def setUp(self):
        store = "KyotoCabinet"
        self.graph = Graph(store=store)
        self.path = configString
        self.graph.open(self.path, create=True)

    def tearDown(self):
        self.graph.destroy(self.path)
        try:
            self.graph.close()
        except:
            pass
        if getattr(self, "path", False) and self.path is not None:
            if os.path.exists(self.path):
                if os.path.isdir(self.path):
                    for f in os.listdir(self.path):
                        os.unlink(self.path + "/" + f)
                    os.rmdir(self.path)
                elif len(self.path.split(":")) == 1:
                    os.unlink(self.path)
                else:
                    os.remove(self.path)

    def test_namespaces(self):
        self.graph.bind("dc", "http://http://purl.org/dc/elements/1.1/")
        self.graph.bind("foaf", "http://xmlns.com/foaf/0.1/")
        self.assert_(len(list(self.graph.namespaces())) == 5)
        self.assert_(("foaf", rdflib.term.URIRef(u"http://xmlns.com/foaf/0.1/")) in list(self.graph.namespaces()))

    def test_play_journal(self):
        self.assertRaises(NotImplementedError, self.graph.store.play_journal, {"graph": self.graph})

    def test_readable_index(self):
        print(readable_index(111))

    def test_create_db(self):
        michel = rdflib.URIRef(u"michel")
        likes = rdflib.URIRef(u"likes")
        pizza = rdflib.URIRef(u"pizza")
        cheese = rdflib.URIRef(u"cheese")
        self.graph.add((michel, likes, pizza))
        self.graph.add((michel, likes, cheese))
        self.graph.commit()
        self.graph.store.close()
        if getattr(self, "path", False) and self.path is not None:
            if os.path.exists(self.path):
                if os.path.isdir(self.path):
                    for f in os.listdir(self.path):
                        os.unlink(self.path + "/" + f)
                    os.rmdir(self.path)
                elif len(self.path.split(":")) == 1:
                    os.unlink(self.path)
                else:
                    os.remove(self.path)
        self.graph.store.open(self.path, create=True)
        ntriples = self.graph.triples((None, None, None))
        self.assert_(len(list(ntriples)) == 0)

    def test_missing_db_exception(self):
        self.graph.store.close()
        if getattr(self, "path", False) and self.path is not None:
            if os.path.exists(self.path):
                if os.path.isdir(self.path):
                    for f in os.listdir(self.path):
                        os.unlink(self.path + "/" + f)
                    os.rmdir(self.path)
                elif len(self.path.split(":")) == 1:
                    os.unlink(self.path)
                else:
                    os.remove(self.path)
        self.graph.store.open(self.path, create=True)
        ntriples = self.graph.triples((None, None, None))
        self.assert_(len(list(ntriples)) == 0)

    def test_reopening_db(self):
        michel = rdflib.URIRef(u"michel")
        likes = rdflib.URIRef(u"likes")
        pizza = rdflib.URIRef(u"pizza")
        cheese = rdflib.URIRef(u"cheese")
        self.graph.add((michel, likes, pizza))
        self.graph.add((michel, likes, cheese))
        self.graph.commit()
        self.graph.store.close()
        self.graph.store.open(self.path, create=False)
        ntriples = self.graph.triples((None, None, None))
        self.assert_(len(list(ntriples)) == 2)

    def test_reopening_missing_db(self):
        self.graph.store.close()
        self.assertRaises(ValueError, self.graph.store.open, ("/tmp/NotAnExistingDB"), create=False)

    def test_isopen_db(self):
        self.assert_(self.graph.store.is_open() == True)
        self.graph.store.close()
        self.assert_(self.graph.store.is_open() == False)
示例#6
0
def mark():
    parser = argparse.ArgumentParser(description="""
Bookmarking utility
""")
    parser.add_argument("-c",
                        "--config",
                        default=os.path.join(os.environ.get("HOME", "/"),
                                             ".mark.ini"),
                        dest="config",
                        help="Config")
    parser.add_argument("-t", "--title", dest="title", help="Title")
    parser.add_argument("-m",
                        "--comment",
                        action="append",
                        help="Comment",
                        default=[])
    parser.add_argument("-d",
                        "--debug",
                        action="store_true",
                        dest="debug",
                        help="Debug")
    parser.add_argument("uri", help="URI")
    parser.add_argument("tags", nargs="*", help="Tags")
    args = parser.parse_args()

    logging.basicConfig(
        level=logging.DEBUG if args.debug else logging.INFO,
        format="%(asctime)s [%(levelname)s] %(name)s: %(message)s")
    log = logging.getLogger(__name__)

    try:
        fp = open(args.config)
        config.update(eval(fp.read()))
        fp.close()
    except IOError:
        pass

    S = get_plugin(config["store"], Store)
    store = S(config["store_args"])

    RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
    RDFS = Namespace("http://www.w3.org/2000/01/rdf-schema#")
    TAGGING = Namespace("http://tagora.ecs.soton.ac.uk/schemas/tagging#")
    TAG = Namespace(config["tag_ns"])

    graph = Graph(store, identifier=URIRef(config["graph"]))

    resource = URIRef(args.uri)

    post = BNode()
    graph.add((post, RDF["type"], TAGGING["Post"]))
    graph.add((post, TAGGING["taggedOn"], Literal(datetime.utcnow())))
    graph.add((post, TAGGING["taggedResource"], resource))

    if args.title:
        graph.add((resource, RDFS["label"], Literal(args.title)))

    for comment in args.comment:
        graph.add((post, RDFS["comment"], Literal(comment)))

    tagger = URIRef(config["tagger"])
    graph.add((tagger, RDF["type"], TAGGING["Tagger"]))
    graph.add((tagger, TAGGING["hasPost"], post))

    ntags = len(args.tags)
    if ntags > 0:
        tagseg = BNode()
        graph.add((post, TAGGING["hasTagSequence"], tagseg))
        for i in range(ntags):
            if i < (ntags - 1):
                graph.add((tagseg, RDF["type"], TAGGING["TagSegment"]))
            else:
                graph.add((tagseg, RDF["type"], TAGGING["FinalTagSegment"]))
            tag = TAG[slugify(args.tags[i])]
            graph.add((tagger, TAGGING["usesTag"], tag))
            graph.add((tagseg, TAGGING["tagUsed"], tag))
            graph.add((tag, RDF["type"], TAGGING["UserTag"]))
            graph.add((tag, RDFS["label"], Literal(args.tags[i])))
            if i < (ntags - 1):
                next = BNode()
                graph.add((tagseg, TAGGING["hasNextSegment"], next))
                tagseg = next

    graph.commit()
def ATS():
        default_graph_uri = "http://rdflib.net/rdfstore"
        # open existing store or create new one
        #store = getStore() # if store does not exist, then new store returned

        # RDF store section:
        configString = "/var/tmp/rdfstore"

        # Get the Sleepycat plugin.
        store = plugin.get('Sleepycat', Store)('rdfstore')

        # Open previously created store, or create it if it doesn't exist yet
        path = mkdtemp()
        rt = store.open('rdfstore', create=False)
        print rt
        print path

        if rt == NO_STORE:
                        print "Creating new store"
                        # There is no underlying Sleepycat infrastructure, create it
                        store.open('rdfstore', create=True)        
        else:
                        print "store exists "
                        #assert rt == VALID_STORE, "The underlying store is corrupt"

        graph = Graph(store,identifier = URIRef(default_graph_uri))

        #define namespaces here
        blog = Namespace('http://rdflib.net/blog/')
        graph.bind("blog", "http://rdflib.net/blog/")
        #game = Namespace('http://rdflib.net/games/')
        #graph.bind("game", "http://rdflib.net/games/")

        blogger_id = Namespace('http://rdflib.net/blog/blogger_id/')
        graph.bind("blogger_id", "http://rdflib.net/blog/blogger_id/")

        blog_url = Namespace('http://rdflib.net/blog/blog_url/')
        graph.bind("blog_url", "http://rdflib.net/blog/blog_url/")

        dbpprop = Namespace('http://dbpedia.org/property/')
        graph.bind("dbpprop", "http://dbpedia.org/property/")
        
        foaf = Namespace('http://xmlns.com/foaf/0.1/')
        graph.bind("foaf", "http://xmlns.com/foaf/0.1/")
        
        owl = Namespace('http://www.w3.org/2002/07/owl#')
        graph.bind("owl", "http://www.w3.org/2002/07/owl#")
        
        dcterms = Namespace('http://purl.org/dc/terms/')
        graph.bind("dcterms", "http://purl.org/dc/terms/")
        
        dbpowl = Namespace('http://dbpedia.org/ontology/')
        graph.bind("dbpowl", "http://dbpedia.org/ontology/")

        rdfs = Namespace('http://www.w3.org/2000/01/rdf-schema#')
        graph.bind("rdfs", "http://www.w3.org/2000/01/rdf-schema#")
        
        rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
        graph.bind("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#")    

                #Prabhjeet
        graph.add((blogger_id, rdf['type'], owl['DatatypeProperty']))
        graph.add((blog[blogger_id], foaf['name'], Literal('name')))
        graph.add((blog[blogger_id], rdf['type'], owl['DatatypeProperty']))
        graph.add((dbpowl['blog'], rdf['type'], owl['ObjectProperty']))
        
                
        xmldoc = open("/Users/prabhjeet/Desktop/WIS/myproject/Demo-Sample.xml", "rU")
        rss = parse(xmldoc)
        for place in rss.getElementsByTagName('place'):
                name1 = place.getElementsByTagName('name1')[0].firstChild.nodeValue
                blogger_id1 = place.getElementsByTagName('blogger-id')[0].firstChild.nodeValue
                title1 = place.getElementsByTagName('title')[0].firstChild.nodeValue
                url1 = place.getElementsByTagName('url')[0].firstChild.nodeValue
                date1 = place.getElementsByTagName('date')[0].firstChild.nodeValue
                expense = place.getElementsByTagName('expense')[0].firstChild.nodeValue
                
                graph.add((blog,blogger_id,Literal(blogger_id1)))
                graph.add((blog[blogger_id1],foaf['name'],Literal(name1)))
                graph.add((blog[blogger_id1],dcterms['title'],Literal(title1)))
                graph.add((blog[blogger_id1],dcterms['date'],Literal(date1)))
                
        
        '''
        for place in rss.getElementsByTagName('place'):
                   pprint (place)
                   print (place.getElementsByTagName('name1')[0].firstChild.nodeValue)
                   print (place.getElementsByTagName('blogger-id')[0].firstChild.nodeValue)
                   print (place.getElementsByTagName('title')[0].firstChild.nodeValue)
                   print (place.getElementsByTagName('url')[0].firstChild.nodeValue)
                   print (place.getElementsByTagName('date')[0].firstChild.nodeValue)
                   print (place.getElementsByTagName('expense')[0].firstChild.nodeValue)
                   #graph.add((   
        '''
        '''
                # Fill in ontology data here:    
                #graph.add((rdflib['game:1'], rdflib['name'], Literal('Half-Life')))
                graph.add((game[gameObject.id], rdf['type'], dbpowl['VideoGame']))
                graph.add((dbpowl['abstract'], rdf['type'], owl['DatatypeProperty']))
                graph.add((foaf['name'], rdf['type'], owl['DatatypeProperty']))
                graph.add((game['id'], rdf['type'], owl['DatatypeProperty']))
                graph.add((game['reviewer'], rdf['type'], owl['DatatypeProperty']))
                graph.add((game['rating'], rdf['type'], owl['DatatypeProperty']))

                graph.add((developer['devid'], rdf['type'], owl['DatatypeProperty']))
                graph.add((developer['devname'], rdf['type'], owl['DatatypeProperty']))
                graph.add((developer['devurl'], rdf['type'], owl['DatatypeProperty']))
                graph.add((dbpowl['developer'], rdf['type'], owl['ObjectProperty']))

                graph.add((publisher['pubid'], rdf['type'], owl['DatatypeProperty']))
                graph.add((publisher['pubname'], rdf['type'], owl['DatatypeProperty']))
                graph.add((publisher['puburl'], rdf['type'], owl['DatatypeProperty']))
                graph.add((dbpowl['publisher'], rdf['type'], owl['ObjectProperty']))

                graph.add((game[gameObject.id], game['id'], Literal(gameObject.id)))
                graph.add((game[gameObject.id], foaf['name'], Literal(gameObject.name)))
                graph.add((game[gameObject.id], dbpowl['abstract'], Literal(gameObject.deck)))
                graph.add((game[gameObject.id], game['rating'], Literal(gameObject.reviewscore)))
                graph.add((game[gameObject.id], game['reviewer'], Literal(gameObject.reviewer)))

                #Adding all developers and publishers here:
                for dev in gameObject.devlist:
                                #graph.add((game[gameObject.id], dbpowl['developer'], Literal(developer.name)))
                                graph.add((developer[dev.id], rdf['type'], dbpowl['Company']))
                                
                                graph.add((game[gameObject.id], dbpowl['developer'], developer[dev.id]))
                                graph.add((developer[dev.id], developer['devid'], Literal(dev.id)))
                                graph.add((developer[dev.id], developer['devname'], Literal(dev.name)))
                                graph.add((developer[dev.id], developer['devurl'], Literal(dev.url)))


                for pub in gameObject.publisherlist:
                                #graph.add((game[gameObject.id], dbpowl['publisher'], Literal(publisher.name)))
                                graph.add((publisher[pub.id], rdf['type'], dbpowl['Company']))

                                graph.add((game[gameObject.id], dbpowl['publisher'], publisher[pub.id]))
                                graph.add((publisher[pub.id], publisher['pubid'], Literal(pub.id)))
                                graph.add((publisher[pub.id], publisher['pubname'], Literal(pub.name)))
                                graph.add((publisher[pub.id], publisher['puburl'], Literal(pub.url)))
        '''
        print_RDF_triples(graph)
        #print_RDF_XML(graph)
        graph.commit()
        #create_RDF_File(graph)
        graph.close(commit_pending_transaction=True)