class TestDataAccess(unittest.TestCase): def setUp(self): self.da = DataAccess() def test_get_space(self): self.assertIsNotNone( self.da.get_space( self.da._defaultSpace ) ) self.assertRaises( Exception, self.da.get_space, "http://unexisting.space.com" ) def test_join_space(self): self.da.join_space( "http://www.space1.tk" ) self.assertIsNotNone( self.da.get_space("http://www.space1.tk") ) def test_leave_space(self): self.da.leave_space( self.da._defaultSpace ) self.assertRaises( Exception, self.da.get_space, self.da._defaultSpace ) def test_get_spaces(self): self.da.join_space( "http://www.space1.tk" ) spaces = self.da.get_spaces() self.assertEquals( 2, len(spaces) ) self.assertTrue( self.da._defaultSpace in spaces ) self.assertTrue( "http://www.space1.tk" in spaces )
class CoordinationSpace(Space): GRAPH_LEVEL = 0 SPACE_LEVEL = 1 def __init__(self, space_name): self._da = DataAccess( defaultSpace = space_name ) self._subscriptions = [] # tuple: (subscription template, callback, level) self._observers = [] def write(self, triples, ignore_subscriptions = False): ret = self._da.write(triples) if not ignore_subscriptions: # only used to shorten the evaluation initialization process # TODO do it in another thread! activated = self._get_activated_subscriptions( triples ) if activated: for ac in activated: ac.call() return ret def _get_activated_subscriptions(self, graph): ret = [] for template, callback, level in self._subscriptions: if level == CoordinationSpace.GRAPH_LEVEL: if template.matches( graph ): ret.append( callback ) elif level == CoordinationSpace.SPACE_LEVEL: # over all the space! if template.matches( self._da.get_space(None).graphs ): ret.append( callback ) else: raise Exception( "Level %d does not exist" % level ) return ret def read_by_wildcard(self, template): return self._da.read_wildcard( *template ) def read_by_sparql(self, query): return self._da.read_sparql( query ) def take_by_wildcard(self, template): return self._da.take_wildcard( *template ) def take_by_sparql(self, query): return self._da.take_sparql( query ) def take_by_uri(self, graph_uri): return self._da.take_uri( graph_uri ) def query_by_sparql(self, query): return self._da.query_sparql( query ) def subscribe(self, template, callback, level = 0 ): self._subscriptions.append( (template, callback, level) ) # warn to the observers if any for observer in self._observers: if level == CoordinationSpace.SPACE_LEVEL: # not necessarily, but to filter in this scenario... observer.notify_subscription( template ) def add_subscription_observer(self, observer): self._observers.append( observer )