Skip to content

Instantly share code, notes, and snippets.

@nilsnh
Created October 17, 2011 14:06
Show Gist options
  • Select an option

  • Save nilsnh/1292665 to your computer and use it in GitHub Desktop.

Select an option

Save nilsnh/1292665 to your computer and use it in GitHub Desktop.

Revisions

  1. Nils renamed this gist Oct 17, 2011. 1 changed file with 0 additions and 0 deletions.
  2. Nils created this gist Oct 17, 2011.
    62 changes: 62 additions & 0 deletions Simple Jena Jython Example
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,62 @@
    from com.hp.hpl.jena.rdf.model import ModelFactory, Resource
    from com.hp.hpl.jena.vocabulary import VCARD
    from javax.servlet.http import HttpServlet

    #Inspired by: http://www.openvest.com/trac/wiki/JenaJython

    class HelloSemanticWeb(HttpServlet):

    def testSemantic(self):

    personURI = "http:#somewhere/JohnSmith"
    givenName = "John"
    familyName = "Smith"
    fullName = givenName + " " + familyName
    # create an empty model
    model = ModelFactory.createDefaultModel()

    # create the resource
    # and add the properties cascading style
    johnSmith = model.createResource(personURI)
    johnSmith.addProperty(VCARD.FN, fullName)\
    .addProperty(VCARD.N, \
    model.createResource().addProperty(VCARD.Given, givenName)\
    .addProperty(VCARD.Family, familyName))

    # list the statements in the graph
    iter_ = model.listStatements()

    # collect the predicate, subject and object of each statement
    strCollect = ""
    while iter_.hasNext():
    stmt = iter_.nextStatement() # get next statement
    sub = stmt.getSubject() # get the subject
    pred = stmt.getPredicate() # get the predicate
    obj = stmt.getObject() # get the object

    strCollect += "<p>"
    strCollect += sub.toString() + " "
    strCollect += pred.toString() + " "

    if isinstance(obj, Resource):
    strCollect += obj.toString()
    else:
    # object is a literal
    strCollect += " \"" + obj.toString() + "\""
    strCollect += "." + "</p>"

    return strCollect

    def testFunc(self):
    return "Function tested"

    def doGet(self, request, response):

    semanticresult = self.testSemantic()

    response.setContentType("text/html")
    response.getWriter().println("<p><b>Heisann verden!! (Dette er den andre Jython Servlet'en)</b></p>")
    response.getWriter().println("<p><b>Stuff I found in the database:</b></p>")
    response.getWriter().println(semanticresult)