Skip to content

Instantly share code, notes, and snippets.

@AlBaker
Created July 13, 2011 07:30
Show Gist options
  • Save AlBaker/1079881 to your computer and use it in GitHub Desktop.
Save AlBaker/1079881 to your computer and use it in GitHub Desktop.
Groovy SPARQL RDFBuilder DSL
@Grab('org.codehaus.groovy.sparql:groovy-sparql:0.2')
import groovy.sparql.*
/**
Can be constructed with:
- Outputstream
- PrintWriter
- Model (all statements built will be copied into the input model
via model.add(List<Statement>)
Can register other output hooks
builder.registerOutputHook(closure)
If more than one output hook is registered, they're executed in parallel via GPars
First closure in the builder is the output type, here are the format types (mapped to Jena):
[xml:"RDF/XML", xmlabbrev:"RDF/XML-ABBREV", ntriple:"N-TRIPLE", n3:"N3", turtle:"TURTLE"]
All other root closure names are ignored, and you just get the model returned
Vocab in the DSL is:
defaultNamespace "namespace"
namespace prefix:"namespace"
subject("uri or fragment) {
property "predicate":object"
property "predicate" {
subject("uri or fragment") {
....
}
}
}
You can nest subjects and properties per above, see the JUnit test for example
**/
def builder = new RDFBuilder(System.out)
// model is a Jena Model
def model = builder.n3 {
defaultNamespace "http://www.example.org"
namespace foaf:"http://xmlns.com/foaf/0.1"
subject("#clarkkent") {
property "foaf:gender":"male"
property "foaf:title":"Mr"
property "foaf:givenname":"Clark"
property "foaf:family_name":"Kent"
}
}
/**
As N3
<http://www.example.org#clarkkent>
<http://xmlns.com/foaf/0.1/family_name>
"Kent" ;
<http://xmlns.com/foaf/0.1/gender>
"male" ;
<http://xmlns.com/foaf/0.1/givenname>
"Clark" ;
<http://xmlns.com/foaf/0.1/title>
"Mr" .
**/
model = builder.xml {
defaultNamespace "http://www.example.org"
namespace foaf:"http://xmlns.com/foaf/0.1"
subject("#clarkkent") {
property "foaf:gender":"male"
property "foaf:title":"Mr"
property "foaf:givenname":"Clark"
property "foaf:family_name":"Kent"
}
}
/**
As XML
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:j.0="http://xmlns.com/foaf/0.1/" >
<rdf:Description rdf:about="http://www.example.org#clarkkent">
<j.0:family_name>Kent</j.0:family_name>
<j.0:givenname>Clark</j.0:givenname>
<j.0:title>Mr</j.0:title>
<j.0:gender>male</j.0:gender>
</rdf:Description>
</rdf:RDF>
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment