- From: Dave Reynolds <der@hplb.hpl.hp.com>
- Date: Fri, 22 Apr 2005 13:13:08 +0100
- To: Max Voelkel <max@xam.de>
- CC: semantic-web@w3.org
Max Voelkel wrote:
> 1. Is there a nicer way (shorter, more readdable) to do this in Jena?
I realize your overall msg is directed to the wider community but
jena-dev@yahoogroups.com is a good place to get support for use of jena.
> [3] Source code in Jena
> -------------------------------------------------
> jenaDataModel = ModelFactory.createDefaultModel();
>
> // create RDF [1] according to Schema [2]
> Property name = jenaDataModel.createProperty("schema://hasName");
> Property knows = jenaDataModel.createProperty("schema://hasFriend");
You can use schemagen[a] to convert your schema to a set of predefined
constants. This both shortens the code slightly and avoids typing mistakes.
> Resource p1 = jenaDataModel.createResource("data://p1");
> Resource p2 = jenaDataModel.createResource("data://p2");
> p1.addProperty( RDF.type, "schema://Person");
> p2.addProperty( RDF.type, "schema://Person");
Some people find the cascading style more readable:
model.createResource(..).addProperty(..).addProperty(..);
a matter of taste.
> System.out.println(s.getSubject().getProperty(name).getLiteral()
> .getLexicalForm()
For plain literals you don't need getLexicalForm.
Personally I generally have a getPropertyValue(resource, property)
operation lying around for dereferencing statements and coping with nulls.
OntResource has that convenience method built in.
> + jenaDataModel.createResource(
> s.getObject().asNode().getURI()).getProperty(name)
> .getLiteral().getLexicalForm());
The object is already a resource you don't need to create a new one.
With those minor tweaks (and assuming you call the schemagen'ed class FOAF)
the code would look like:
[[[
Model jenaDataModel = ModelFactory.createDefaultModel();
Resource p1 = jenaDataModel.createResource("data://p1")
.addProperty( RDF.type, FOAF.Person)
.addProperty( FOAF.hasName, "Rudi Studer");
Resource p2 = jenaDataModel.createResource("data://p2")
.addProperty( RDF.type, FOAF.Person)
.addProperty( FOAF.hasName, "York sure");
p1.addProperty(FOAF.knows, p2);
// query model and render output
StmtIterator it = p1.listProperties(FOAF.knows);
while (it.hasNext()) {
Statement s = it.nextStatement();
System.out.println(
getPropertyValue(s.getSubject(), FOAF.hasName)
+ " knows " +
getPropertyValue((Resource)s.getObject(), FOAF.hasName) );
}
]]]
where getPropertyValue [b] is
[[[
public static RDFNode getPropertyValue(Resource r, Property p) {
Statement s = r.getProperty(p);
return (s == null) ? null : s.getObject();
}
]]]
We should probably do any follow ups off-list or, better, over on jena-dev,
to avoid cluttering this list with API specific details.
Dave
[a] http://jena.sourceforge.net/how-to/schemagen.html
[b] Alterantively use getRequiredPropertyValue and let any exceptions
propagate. Use of nulls for empty returns is controversial.
Received on Friday, 22 April 2005 12:13:32 UTC