Jena - RDF Schema

From XennisWiki
Jump to: navigation, search

Jena supports creating RDFS models. RDF Schema (Resource Description Framework Schema [...]) is a set of classes with certain properties using the RDF extensible knowledge representation language, providing basic elements for the description of ontologies, otherwise called RDF vocabularies, intended to structure RDF resources. These resources can be saved in a triplestore to reach them with the query language SPARQL. (Wikipedia)

Create RDFS model from file(s)

Interference.java

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.util.FileManager;
import com.hp.hpl.jena.util.FileUtils;

public class Inference {
	
	/** RDFS default model */
	public static Model RDFS = ModelFactory.createRDFSModel(ModelFactory.createDefaultModel());
	
	/**
	 * Creates RDFS model from given model.
	 * 
	 * @param model
	 *            Model
	 * @return RDFS model
	 */
	public Model inferStuff(Model model) {
		Model rdfsModel = ModelFactory.createRDFSModel(model).difference(RDFS);
		rdfsModel.setNsPrefixes(model);
		return rdfsModel;
	}
	
	/**
	 * Create RDFS model from given schema and model.
	 * 
	 * @param schema
	 *            Schema
	 * @param model
	 *            Model
	 * @return RDFS model
	 */
	public Model inferStuff(Model schema, Model model) {
		Model rdfsModel = ModelFactory.createRDFSModel(schema, model).difference(RDFS);
		rdfsModel.setNsPrefixes(schema);
		rdfsModel.setNsPrefixes(model);
		return rdfsModel;
	}

	public static void main(String[] args) {
		/*
		 * Handle arguments
		 */
		if (args.length < 1) {
			System.err.println("Less arguments");
			System.out.println("Usage: <schema_or_model_file> [<model_file>]");
			System.out.println("Example: schema.ttl model.ttl");
			System.exit(0);
		}
		
		Inference inf = new Inference();
		FileManager fm = FileManager.get();
		Model m;
		if (args.length > 1) {
			m = inf.inferStuff(fm.loadModel(args[0]), fm.loadModel(args[1]));
		} else {
			m = inf.inferStuff(fm.loadModel(args[0]));
		}
		m.write(System.out, FileUtils.guessLang(args[0]));
	}

}

schema.ttl

@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix : <http://example.com/> .
@base <http://example.com/> .

:Person a rdfs:Class .
:Man a rdfs:Class ;
	rdfs:subClassOf :Person .
:Parent a rdfs:Class ;
	rdfs:subClassOf :Person .
:Father a rdfs:Class ;
	rdfs:subClassOf :Parent , :Man .
:hasParent a rdf:Property ;
	rdfs:domain :Person ;
	rdfs:range :Parent .
:hasFather a rdf:Property ;
	rdfs:range :Father ;
	rdfs:subPropertyOf :hasParent .

model.ttl

@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix : <http://example.com/> .
@base <http://example.com/> .

:Ann a :Person ;
	:hasFather :Carl .
:Carl a :Man .

See also