Skip to content

RDF Input and Output

Matthias Fisch edited this page Dec 9, 2017 · 2 revisions

To improve the usability of the library, a small extension to the "ORM" (Object-RDF-Mapping) has been implemented. Users can parse their RDF triples formulated in various RDF serialisations to create the respective Java objects, as well as write their Java objects to serialised RDF triples. Among the available serialisations are rdf/xml, ntriples, turtle, n3, jsonld, rdf/json, etc.

In order to read a given RDF document (available as Java String), an ObjectParser object is needed. Its parse(Class<?> type, String content, String uri, RDFFormat format, boolean clear) method can be used to get the resources from the document as objects. The type parameter specifies the type of the objects that should be returned (use ResourceObject.class to get all resources). The method also expects the content of the RDF document as String, a uri for namespacing, and the supported format (The Java Class RDFFormat holds constant for all supported serialisations). It will then return a Java List of parsed Annotations. The ObjectParser holds all parsed annotations in a local temporary memory store. For performance reasons, this local memory store should be cleared from time to time. This can be done by setting the clear parameter of the above method. In order to persist the objects to your respective database, they have to be read from the parser and be persisted "by hand" then. The following shows an example of how to read an annotation from a turtle document.

String TURTLE = "@prefix oa: <http://www.w3.org/ns/oa#> ." +
            "@prefix ex: <http://www.example.com/ns#> ." +
            "@prefix dctypes: <http://purl.org/dc/dcmitype/> ." +
            "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> ." +

            "ex:anno1 a oa:Annotation ;" +
            "   oa:hasBody ex:body1 ;" +
            "   oa:hasTarget ex:target1 .";
            
URL url = new URL("http://example.com/");

ObjectParser objectParser = new ObjectParser();
List<Annotation> annotations = objectParser.parse(Annotation.class, TURTLE, url, RDFFormat.TURTLE, true);

objectParser.shutdown();

To write a given Anno4j Java object to respective RDF serialisations, the ResourceObject interface (which every Anno4j object descends from) supports a .getTriples(RDFFormat format) method, which returns the representation of the object as a Java String in the supported format. The following shows an example that writes a given annotation as turtle triples.

Annotation annotation = anno4j.createObject(Annotation.class);

// Add something to the Annotation

String annotationAsTurtle = annotation.getTriples(RDFFormat.TURTLE);
Clone this wiki locally