Beispiel #1
0
    def __init__(self, path=None):
        self.__dict__ = self.__shared_state
        if (self.data == None):
            if (path == None):
                raise ValueError("djubby's configuration MUST be initialized a first time, read http://code.google.com/p/djubby/wiki/GettingStarted")
            else:
                self.path = os.path.abspath(path)
                logging.debug("Reading djubby's configuration from %s..." % self.path)
                if (not os.path.exists(self.path)):
                    raise ValueError("Not found a proper file at '%s' with a configuration for djubby. Please, provide a right path" % self.path)

                data = ConjunctiveGraph()
                data.bind("conf", ns.config) 
                try:
                    data.load(path, format='n3') 
                except Exception, e:
                    raise ValueError("Not found a proper N3 file at '%s' with a configuration for djubby. Please, provide a valid N3 file" % self.path)

                self.data = data
                try:
                    self.graph = self.get_value("sparqlDefaultGraph")
                    self.endpoint = self.get_value("sparqlEndpoint")
                except Exception, e:
                    raise ValueError("Not found the graph not the endpoint that it's supposed djubby have to query. Please, provide a right donfiguration")

                logging.info("Using <%s> as default graph to query the endpoint <%s>" % (self.graph, self.endpoint))
                self.__class__.__dict__['_Configuration__shared_state']["data"] = data #FIXME
Beispiel #2
0
class RdfParser(object):
	"""A basic wrapper for RdfLib's RDF parser.
	This class aims to accomplish easier parsing, extraction of Models,
	etc."""

	def __init__(self, rdf, format='guess'):
		"""Init the parser with the graph string."""
		self.graph = Graph()
		if format == 'guess':
			format = self.__guess_format(rdf)
			print 'RdfParser guesses format to be: %s' % format
		try:
			self.graph.load(StringIO(rdf), format=format)
		except:
			print "Failed to parse RDF:"
			print rdf[0:100]

	def extract(self, datatype):
		"""Extract all of the data of a given datatype."""
		data = []
		ns = RdfSerializer.NAMESPACES['sylph'] # TODO: Awkward.
		for sub in self.graph.subjects(RDF.type, ns[datatype]):
			idx = str(sub)
			item = {'uri': idx}
			for pred, obj in self.graph.predicate_objects(sub):
				if pred == RDF.type:
					continue
				if obj == ns['None']:
					obj = None
				elif type(obj) == URIRef:
					obj = unicode(obj)
				elif type(obj) == Literal:
					obj = obj.toPython()
					if type(obj) == Literal: # Don't be silly, RdfLib!
						obj = unicode(obj)

				predstr = str(pred).rpartition('#')[2].rpartition('/')[2]
				item[predstr] = obj
			data.append(item)
		return data

	@staticmethod
	def __guess_format(st):
		"""Guess the format of the input string."""
		# TODO: At present, it can only guess between XML and n3, even
		# then this is a vague heuristic.
		if st.startswith('<'):
			return 'xml'
		return 'n3'
Beispiel #3
0
def extendGraphFromFile(inGraph, graphFile, format='n3'):
    """
    Add all the triples in graphFile to inGraph

    This is done as if the loaded graph is the same context as this
    database's graph, which means <> from the loaded graph will be
    modified to mean <> in the new context
    """
    g2 = Graph()

    # Generate a random publicID, then later throw it away, by
    # replacing references to it with URIRef('').  extendGraphFromFile thus
    # treats the inserted file as if it were part of the original file
    publicID = randomPublicID()
    g2.load(graphFile, format=format, publicID=publicID)

    # add each triple
    # FIXME - this should use addN
    for s,v,o in g2:
        if s == URIRef(publicID):
            inGraph.add((URIRef(''), v, o))
        else:
            inGraph.add((s,v,o))
Beispiel #4
0
    def resolveURI(self, uri):
        return _urljoin(self.baseuri or '', uri)

    def _popStacks(self, event, node):
        # check abouts
        if len(self.abouts) <> 0:
            about, aboutnode = self.abouts[-1]
            if aboutnode == node:
                self.abouts.pop()

        # keep track of nodes going out of scope
        self.elementStack.pop()

        # track xml:base and xml:lang going out of scope
        if self.xmlbases:
            self.xmlbases.pop()
            if self.xmlbases and self.xmlbases[-1]:
                self.baseuri = self.xmlbases[-1]

        if self.langs:
            self.langs.pop()
            if self.langs and self.langs[-1]:
                self.lang = self.langs[-1]


if __name__ == "__main__":
    store = ConjunctiveGraph()
    store.load(sys.argv[1], format="rdfa")
    print store.serialize(format="pretty-xml")
    def resolveURI(self, uri):
        return _urljoin(self.baseuri or "", uri)

    def _popStacks(self, event, node):
        # check abouts
        if len(self.abouts) <> 0:
            about, aboutnode = self.abouts[-1]
            if aboutnode == node:
                self.abouts.pop()

        # keep track of nodes going out of scope
        self.elementStack.pop()

        # track xml:base and xml:lang going out of scope
        if self.xmlbases:
            self.xmlbases.pop()
            if self.xmlbases and self.xmlbases[-1]:
                self.baseuri = self.xmlbases[-1]

        if self.langs:
            self.langs.pop()
            if self.langs and self.langs[-1]:
                self.lang = self.langs[-1]


if __name__ == "__main__":
    store = ConjunctiveGraph()
    store.load(sys.argv[1], format="rdfa")
    print store.serialize(format="pretty-xml")
Beispiel #6
0
Further information about Construct can be obtained from
http://www.construct-infrastructure.org
"""
 
from construct.proxy import proxy
from construct.constructservice import ServiceError
from rdflib.Graph import ConjunctiveGraph
	
# Create a new proxy object.
proxy = proxy()
print "Executing Script"
try:
    # Generate a piece of FOAF RDF
    store = ConjunctiveGraph()
    store.load("joebloggs_foaf.rdf")
    data = store.serialize(format="nt")
    # Send the FOAF RDF to the data store
    if(proxy.insert(data)):
        # Now query for joebloggs web address
        query = """SELECT ?nickname WHERE{
        ?subject <http://xmlns.com/foaf/0.1/name> "Joe Bloggs".
        ?subject <http://xmlns.com/foaf/0.1/nick> ?nickname.}
        """
        results = proxy.query(query)
        print "Here is the N3 form of the QueryResults Object:"		
        print results
except ServiceError, e:
    print e
# Close the proxy.
proxy.close()