Пример #1
0
 def validate(self, uri_fingerprint, require_hex_fpr=1):
     """validate the format of the document"""
     
     FOAF = Namespace("http://xmlns.com/foaf/0.1/")
     TRUST = Namespace("http://www.konfidi.org/ns/trust/1.2#")
     WOT = Namespace("http://xmlns.com/wot/0.1/")
     RDF = Namespace("http://www.w3.org/2000/01/rdf-schema#")
     store = TripleStore()
 
     # TODO: verify all <truster>s have fingerprints
     # and that they're all the same
     try:
         store.parse(StringInputSource(self.content))
     except SAXParseException:
         raise FOAFServerError, "invalid XML: " + str(sys.exc_info()[1])
     
     fingerprint = last_fingerprint = None
     for (relationship, truster) in store.subject_objects(TRUST["truster"]):
         for (key) in store.objects(truster, WOT["hasKey"]):
             fingerprint = store.objects(key, WOT["fingerprint"]).next()
             if last_fingerprint:
                 if fingerprint != last_fingerprint:
                     raise FOAFServerError, "All wot:fingerprint's from trust:truster's PubKeys must be the same.  Found '%s' and '%s'" % (fingerprint, last_fingerprint)
             last_fingerprint = fingerprint
     
     # per http://xmlns.com/wot/0.1/, we really shouldn't replace these
     fingerprint = fingerprint.replace(" ", "")
     fingerprint = fingerprint.replace(":", "")
     if require_hex_fpr and not(ishex(fingerprint)):
         raise FOAFServerError, "Invalid fingerprint format; must be hex"
     
     if uri_fingerprint and uri_fingerprint != fingerprint:
         raise FOAFServerError, "URI fingerprint doesn't match FOAF fingerprint"
         
     return fingerprint
Пример #2
0
	def load(self, source):	
		# TODO:  don't let duplicate trust levels on certain subjects be entered!	
		print "Update Listener: parsing input"
		# this is the main object we're concerned with
		store = TripleStore()
		store.load(source)			
		# For each foaf:Person in the store print out its mbox property.
		truster = store.subjects(self.TRUST["trusts"]).next()
		f = store.objects(truster, self.WOT["fingerprint"]).next()
		p = self.server.getPerson(f)
		for trustee in store.objects(truster, self.TRUST["trusts"]):
			f2 = store.objects(trustee, self.WOT["fingerprint"]).next()
			# we do this to make sure they exist.
			p2 = self.server.getPerson(f2)
			for value, resource in store.predicate_objects(trustee):
				if value in self.trustValues:
					p.addTrustLink(f2, resource.split("#")[1], resource, TrustValue.TrustValue(value.split("#")[1]))
	def load(self, source):	
		print "Update Listener: parsing input: %s" % source
		# this is the main object we're concerned with
		store = TripleStore()
		store.load(source)			
		# For each foaf:Person in the store print out its mbox property.
		truster = store.subjects(self.TRUST["trusts"]).next()
		f = store.objects(truster, self.WOT["fingerprint"]).next()
		p = self.server.getPerson(f)
		for trustee in store.objects(truster, self.TRUST["trusts"]):
			f2 = store.objects(trustee, self.WOT["fingerprint"]).next()
			# we do this to make sure they exist.
			p2 = self.server.getPerson(f2)
			for value, resource in store.predicate_objects(trustee):
				if value in self.trustValues:
					self.server.lock.acquire_write()
					#time.sleep(15)
					p.addTrustLink(f2, resource.split("#")[1], resource, BasicTrustValue(value.split("#")[1]))
					self.server.lock.release_write()
Пример #4
0
	def load(self, source):	
		print "Update Listener: parsing input: %s" % source
		# this is the main object we're concerned with
		trust = TripleStore()
		trust.load(source)	
		# new version
		count = 0
		for (relationship, truster) in trust.subject_objects(self.TRUST["truster"]):
			# clean up the fingerprints
			source_fingerprint = trust.objects(truster, self.WOT["fingerprint"]).next()
			sink_fingerprint = trust.objects(trust.objects(relationship, self.TRUST["trusted"]).next(), self.WOT["fingerprint"]).next()
			# turn these off for now, for our test cases.  figure a better solution later
			source_fingerprint = re.sub(r'[^0-9A-Z]', r'', source_fingerprint.upper())
			sink_fingerprint = re.sub(r'[^0-9A-Z]', r'', sink_fingerprint.upper())
			source = self.server.getPerson(source_fingerprint)
			sink = self.server.getPerson(sink_fingerprint)
			for item in trust.objects(relationship, self.TRUST["about"]):
				topic = trust.objects(item, self.TRUST["topic"]).next().split("#")[1]
				rating = float(trust.objects(item, self.TRUST["rating"]).next())
				if rating >= 0.0 and rating <= 1.0:
					source.addTrustLink(sink.getFingerprint(), topic, rating)
					count += 1
		return "Added %d trust links." % count
Пример #5
0
"""
read XMP xml files

"""
# see http://www.xml.com/lpt/a/1107
# see also raptor-utls
# rapper -o ntriples http://planetrdf.com/guide/rss.rdf
# rapper -o ntriples ../tests/fixture/xmp/sample_xmp.rdf
from rdflib.TripleStore import TripleStore
from rdflib.Namespace import Namespace

ns_dc = Namespace("http://purl.org/dc/elements/1.1/")
ns_pr = Namespace("http://prismstandard.org/1.0#")
store = TripleStore()
store.load("../tests/fixture/xmp/sample_xmp.rdf")

# print dir(store)

quit()
# For all triples that have prism:publicationTime as their predicate,
for s, o in store.subject_objects(ns_pr["publicationTime"]):
    # if the triples' object is greater than the cutoff date,
    if o > cutOffDate:
        # print the date, author name, and title.
        print o,
        for object in store.objects(s, ns_dc["creator"]):
            print object + ": ",
        for object in store.objects(s, ns_dc["title"]):
            print object
                   'turtle',
                   'ntriples',
                   infile=tmpfile)

    graph = TripleStore()
    graph.parse(StringIO(data), format='nt')

    thisURI = URIRef('http://%s%s' %
                     (os.environ['HTTP_HOST'], os.environ['REQUEST_URI']))

    graphNode = URIRef('file://%s' % tmpfile)

    FOAF = Namespace("http://xmlns.com/foaf/0.1/")

    try:
        bnode = graph.objects(graphNode, FOAF["primaryTopic"]).next()
    except StopIteration:
        print 'Content-Type: text/plain\r'
        print '\r'
        print 'no primary topic given'

    graph2 = TripleStore()

    for (s, p, o) in graph.triples((None, None, None)):
        if (s, p, o) == (graphNode, FOAF["primaryTopic"], bnode): continue

        if s == bnode: s = thisURI
        if o == bnode: o = thisURI

        graph2.add((s, p, o))
Пример #7
0
from rdflib.constants import DATATYPE

# Add triples using store's add method.
store.add((donna, TYPE, FOAF["Person"]))
store.add((donna, FOAF["nick"], Literal("donna")))
store.add((donna, FOAF["name"], Literal("Donna Fales")))

# Iterate over triples in store and print them out.
print "--- printing raw triples ---"
for s, p, o in store:
    print s, p, o
    
# For each foaf:Person in the store print out its mbox property.
print "--- printing mboxes ---"
for person in store.subjects(TYPE, FOAF["Person"]):
    for mbox in store.objects(person, FOAF["mbox"]):
        print mbox

# Serialize the store as RDF/XML to the file foaf.rdf.
store.save("foaf.rdf")

# Let's show off the serializers

print "RDF Serializations:"

# Serialize as XML
print "--- start: rdf-xml ---"
print store.serialize()
print "--- end: rdf-xml ---\n"

# Serialize as NTriples
Пример #8
0
class rdfDict:
    """
    Provides a dictionary-like wrapper around a set of RDF triples with a
    common subject.  In addition to the standard dictionary interface
    provides convenience methods for manipulating the triples.
    """
    def __init__(self, subject, rdfStore=None):
        """
        Creates a new rdfDict given the particular subject and an optional
        TripleStore (rdfStore).  If no TripleStore is provided, creates a
        new one.
        """

        # store the subject
        self.subject = subject

        # store or create the triple store
        if rdfStore is None:
            self.store = TripleStore()
        else:
            self.store = rdfStore

    def __str__(self):
        """
        Return the string representation of this instance using an algorithm
        inspired by the Dublic Core dumb-down method.
        """

	output_str = ''
        pairs = []
	type_item = None
        
        for key in self:
	    if (key.find("#type") != -1): 
	      type_item = key
	    else:
	      pairs.append((key, self.getAll(key)))

	output_str = str(self.getFirst(type_item)) + ": "

	for pair in pairs:
	   output_str = '%s %s: %s;' % (output_str,
                                        str(pair[0]),
                                        ", ".join([str(n) for n in pair[1]]) ) 

	return output_str

    def about(self):
        """
        Return the subject used to create the instance (usually equivalent
        to rdf:about.
        """
        return self.subject

    def __getvalues(self, key):
        """
        Returns a list of values for a particular key; coerces BNodes to
        rdfDicts and mangles Literals with language attributes (if available).
        """

        values = [ n for n in self.store.objects(subject=self.subject,
                                                 predicate=key)
                   ]

        result = []
        
        for value in values:
            if (isinstance(value, BNode)):
                # coerce to rdfDict
                result.append(rdfDict(value, self.store))
            else:
                result.append(value)

        return result
                            
    def __getitem__(self, key):
        """
        Return the object described in RDF with a subject of self.subject
        and a predicate of key.  If more than one match is found, raises
        an AmbiguousKeyError.
        """

        result = self.__getvalues(key)

        if (len(result) == 0):
            # no item was found, throw an exception
            raise KeyError()
        elif (len(result) > 1):
            # check if there is more than one option
            raise AmbiguousKeyError()
        else:
            # otherwise return object value
            return result[0]

    def getFirst(self, key):
        """
        Returns the first object having the predicate key.  If no match is
        found returns None.
        """

        if ( (self.subject, URIRef(key), None) in self.store):
            return self.__getvalues(key)[0]
        else:
            return None
        
    def getAll(self, key):
        """
        Returns a list of objects which have a predicate of key.  The list
        may be empty or contain only a single element.
        """

	return self.__getvalues(key)

    def __setitem__(self, key, value):
        """
        Adds an RDF triple of the values (self.subject, key, value); any
        objects with the same subject/predicate are replaced.
        """

        if (self.subject, key, none) in self.store:
            del self[key]

        self.store.add( (self.subject, key, value) )
        
    def add (self, key, value):
        """
        Adds an RDF triple consisting of the subject, key and value.
        """
        
        self.store.add( (self.subject, key, value) )
        
    def addAll (self, key, values):
        """
        Adds the list of objects in values with the same subject and predicate.
        """
        
        for value in values:
            self.add (key, value)
            
    def __len__(self):
        """
        Returns the number of predicate-object pairs associated with the
        subject self.subject.
        """

        return len(self.store)

    def __delitem__(self, key):
        """
        Removes all items with the given key.
        """

        if (self.subject, key, None) in self.store:
            self.store.remove( (self.subject, key, None) )
        else:
            raise KeyError()

    def remove (self, key, value):
        """
        Removes a specific key-value pair.
        """
        
        self.store.remove( (self.subject, key, value) )

    def __iter__(self):
        """
        Returns an iterator over the unique keys (predicates)
        for the given subject.
        """

        return iter(sets.Set(self.store.predicates(subject=self.subject)))

    iterkeys = __iter__

    def __contains__(self, key):
        """
        Returns true if the given key appears as a predicate of the subject.
        """

        return ( (self.subject, key, None) in self.store )
Пример #9
0
# master dictionary containing all the people
# will a plain old dictionary suffice, or do I need a hashtable?
people = {}

# load trust values into list for later
trust = TripleStore()
trust.load("http://www.abundantplunder.com/trust/owl/trust.owl#")
trustValues = []
for s in trust.subjects(RDF["subPropertyOf"], TRUST["trustValue"]):
	trustValues.append(s)

# For each foaf:Person in the store print out its mbox property.
print "--- printing trust: ---"
truster = store.subjects(TRUST["trusts"]).next()
f = store.objects(truster, WOT["fingerprint"]).next()
p = Person.Person(f)
people[f] = p

for trustee in store.objects(truster, TRUST["trusts"]):
	f2 = store.objects(trustee, WOT["fingerprint"]).next()
	p2 = Person.Person(f2)
	people[f2] = p2
	for value, subject in store.predicate_objects(trustee):
		if value in trustValues:
			name = subject.split("#")[1]
			resource = subject
			value = value.split("#")[1]
			tc = TrustConnection.TrustConnection()
			tc.setFingerprint(f2)
			tv = TrustValue.TrustValue(value)