Examples

From Info216
Jump to: navigation, search

Here are the code examples we have used in the live sessions during the lectures - along with a few additional ones.

Contents

Lecture 1: Java, Jena, and Eclipse

Hello Jena

package no.uib.sinoa.info216;

import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.vocabulary.FOAF;

public class HelloJena {

	public static void main(String[] args) {
		
		Model model = ModelFactory.createDefaultModel();
		
		Resource andreas = model.createResource("http://no.uib.infomedia.info216.ex/CadeTracy");
		andreas.addLiteral(FOAF.name, "Cade Tracy");
		
		model.write(System.out, "TURTLE");
	}	
}

Lecture 2: RDF

Resource objects

package no.uib.infomedia.info216;

...

public class HelloJena {
	public static void main(String[] args) {
		String iriBase = "http://no.uib.infomedia.info216/";
		String iriDbpedia = "http://dbpedia.org/resource/";
		
		Model model = ModelFactory.createDefaultModel();
		
		Resource resCadeTracy = model.createResource(iriBase + "Cade_Tracy");
		resCadeTracy.addLiteral(FOAF.name, "Cade Tracy");
		
		Resource resCanada = model.createResource(iriDbpedia + "Canada");
		Resource resFrance = model.createResource(iriDbpedia + "France");
		Property propVisited = model.createProperty(iriBase + "visited");
		resCadeTracy.addProperty(propVisited, resCanada);
		resCadeTracy.addProperty(propVisited, resFrance);

		model.write(System.out, "TURTLE");
	}
}

Language-tagged literals

		resFrance.addProperty(RDFS.label, "Frankrike", "no");
		resFrance.addProperty(RDFS.label, "France", "en");
		resFrance.addProperty(RDFS.label, "Francia", "es");

Typed literals

		Property propPopEst = model.createProperty(iriDbpedia + "ontology/populationEstimate");
		resFrance.addProperty(propPopEst, "66644000", XSDDatatype.XSDinteger);

Looping through statements

		for (Statement stmt : model.listStatements().toList()) {
			System.out.println(stmt.toString());
		}

Selecting statements

		for (Statement stmt : model
				.listStatements((Resource)null, RDFS.label, (RDFNode)null)
				.toList()) {
			System.out.println("Subject:   " + stmt.getSubject().toString());
			System.out.println("Predicate: " + stmt.getPredicate().toString());
			System.out.println("Object:    " + stmt.getObject().toString());
		}

Using a selector

		for (Statement stmt : model
				.listStatements(new SimpleSelector() {
					public boolean test(Statement s) { 
						return (s.getPredicate().equals(FOAF.name)); 
					}
				})
				.toList()) {
			System.out.println(stmt.getObject().toString());
		}

Writing to file

		try {
			model.write(new FileOutputStream("test.ttl"), "TURTLE");
		} catch (Exception e) {
			// TODO: handle exception
		}

Contents of test.ttl

<http://no.uib.infomedia.info216/Cade_Tracy>
        <http://no.uib.infomedia.info216/visited>
                <http://dbpedia.org/resource/France> , <http://dbpedia.org/resource/Canada> ;
        <http://xmlns.com/foaf/0.1/name>
                "Cade Tracy" .

<http://dbpedia.org/resource/France>
        <http://www.w3.org/2000/01/rdf-schema#label>
                "Francia"@es , "France"@en , "Frankrike"@no ;
        <http://dbpedia.org/resource/ontology/populationEstimate>
                66644000 .

Reading from file

package no.uib.infomedia.sinoa.info216;

import java.io.FileInputStream;

import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;

public class ReadJena {

	public static void main(String[] args) {
		Model model = ModelFactory.createDefaultModel();
		
		try {
			model.read(new FileInputStream("test.ttl"), "http://ex.org/", "TURTLE");
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		model.write(System.out);
	}
}

Reading from web resource

package no.uib.infomedia.sinoa.info216;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;

public class HttpTest {

	public static void main(String[] args) {
		Model model = ModelFactory.createDefaultModel();
		
		try {
			URL url = new URL("http://people.uib.no/sinoa/test.ttl");   
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();  
			InputStream is = urlConnection.getInputStream();
			model.read(is, "http://ex.org/", "TURTLE");
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		model.write(System.out);
	}
}

(There are many other ways to download web resources from Java, but HttpUrlConnection is a straightforward and built-in way to get started.)

Lecture 3: RDFS

Creating an RDFS model

		Model rdfModel = ModelFactory.createDefaultModel();
		InfModel rdfsModel = ModelFactory.createRDFSModel(rdfModel);

RDFS entailment: subClassOf

		String iriBase = "http://no.uib.infomedia.info216/";

		Resource resUCB = rdfsModel.createResource(iriBase + "UCB");
		Resource resUniversity = rdfsModel.createResource(iriBase + "University");
		resUCB.addProperty(RDF.type, resUniversity);

		Resource resHEI = rdfsModel.createResource(iriBase + "HEI");
		resUniversity.addProperty(RDFS.subClassOf, resHEI);

		rdfsModel.write(System.out, "TURTLE");

The output will show that University of Califoria, Berkeley (UCB) is a Higher-Education Institution (HEI), even though we did not assert that explicitly.

Adding namespace prefixes

		rdfsModel.setNsPrefix("", iriBase);
		rdfsModel.setNsPrefix("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
		rdfsModel.setNsPrefix("rdfs", "http://www.w3.org/2000/01/rdf-schema#");

We can do this in a single call too, by first creating a map:

		rdfsModel.setNsPrefixes(new HashMap() {{
			put("", iriBase);
			put("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
			put("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
		}});

(The "double-brace notation" {{ ... }} lets us add code to initialise the new HashMap object at construction, before we pass it as a parameter to setNsPrefixes.)

Instead of

		Resource resUCB = rdfsModel.createResource(iriBase + "UCB");

we can now write

		Resource resUCB = rdfsModel.createResource(rdfsModel.getNsPrefixURI("") + "UCB");

to reduce the need for global strings in large programs and to eliminate inconsistencies by keeping all prefixes in the same place.

Outputting the RDFS axioms

		ModelFactory
			.createRDFSModel(ModelFactory.createDefaultModel())
			.write(System.out, "TURTLE");

Removing axioms from RDFS outputs

Here, we write the triples in rdfsModel to the console, after eliminating all triples that are axioms:

		InfModel axiomModel = ModelFactory.createRDFSModel(ModelFactory.createDefaultModel());
		ModelFactory
			.createDefaultModel()
			.add(rdfsModel.listStatements().toList())
			.remove(axiomModel.listStatements().toList())
			.write(System.out, "TURTLE");

RDFS entailment: subPropertyOf

		Resource resCadeTracy = rdfsModel.createResource(rdfsModel.getNsPrefixURI("") + "Cade_Tracy");
		Property propHasBScFrom = rdfsModel.createProperty(rdfsModel.getNsPrefixURI("") + "hasBScFrom");
		resCadeTracy.addProperty(propHasBScFrom, resUCB);

		Property propGraduatedFrom = rdfsModel.createProperty(rdfsModel.getNsPrefixURI("") + "graduatedFrom");
		propHasBScFrom.addProperty(RDFS.subPropertyOf, propGraduatedFrom);

		rdfsModel.write(System.out, "TURTLE");

The output will show that Cade graduated from University of Califoria, Berkeley (UCB), even though we did not assert that explicitly.

Chained RDFS entailment: subPropertyOf and domain

		propGraduatedFrom.addProperty(RDFS.domain, FOAF.Person);
		
		rdfsModel.write(System.out, "TURTLE");

The output will show that Cade is a FOAF person, even though we did not assert that explicitly.

The Reasoner object

This outputs the name of the Reasoner's class:

		System.out.println(rdfsModel.getReasoner().getClass().toString());

Lifting data from a spreadsheet

This code reads the CSV file from Lab 2, stored in a file called "people.csv" in the Eclipse project root directory.

 "Name","Gender","Country","Town","Expertise","Interests"
 "Regina Catherine Hall","F","Great Britain","Manchester","Ecology, zoology","Football, music travelling"
 "Achille Blaise","M","France","Nancy","","Chess, computer games"
 "Nyarai Awotwi Ihejirika","F","Kenya","Nairobi","Computers, semantic networks","Hiking, botany"
 "Xun He Zhang","M","China","Chengdu","Internet, mathematics, logistics","Dancing, music, trombone"

Simple attempt, using literal objects:

public class HelloCSVv1 {
	public static void main(String[] args) throws FileNotFoundException, IOException {
		
		Model model = ModelFactory.createDefaultModel();
		model.setNsPrefix("", "http://no.uib.infomedia.sinoa.info216#");
		
		addFile("people.csv", model);
		
	 	model.write(System.out, "TURTLE");
	}
	
	private static void addFile (String fileName, Model model) throws FileNotFoundException, IOException {
		File csvFile = new File(fileName);
		BufferedReader reader = new BufferedReader(new FileReader(csvFile));
		
		String[] headers = reader.readLine().replaceAll("^\"|\"$", "").split("\",\"");
		Property[] properties = new Property[headers.length];
		for (int i=0; i<headers.length; i++)
			properties[i] = model.createProperty(model.getNsPrefixURI("") + headers[i].toLowerCase());
		
		String line = null;
		while ((line = reader.readLine()) != null) {
			addPerson(line, model, properties);
		}
	 	reader.close();
	}
	
	private static void addPerson(String line, Model model, Property[] properties) {
		Resource person = model.createResource();
		person.addProperty(RDF.type, FOAF.Person);
		
		String[] values = line.replaceAll("^\"|\"$", "").split("\",\"");
		for (int i=0; i<values.length; i++) {
			person.addProperty(properties[i], values[i]);
		}	
	}

More advanced variant of the addPerson method, that treats the properties differently and uses some resource objects:

	
	private static void addPerson(String[] headers, Property[] properties, String line, Model model) {
		Resource person = model.createResource();
		person.addProperty(RDF.type, FOAF.Person);
		
		String[] values = line.replaceAll("^\"|\"$", "").split("\",\"");
		for (int i=0; i<values.length; i++) 
			switch (headers[i]) {

			case "Country":
			case "Town":
				person.addProperty(properties[i], 
					model.createResource(model.getNsPrefixURI("") + values[i].replaceAll(" ",  "_")));
				break;
			
			case "Expertise":
			case "Interests":
				if (! values[i].isEmpty())
					for (String val : values[i].split(", *"))
						person.addProperty(properties[i], val.toLowerCase());
				break;
			
			case "Gender":
				switch (values[i]) {
				
				case "M":
					person.addProperty(properties[i], 
						model.createResource(model.getNsPrefixURI("") + "Male"));
					break;
					
				case "F":
					person.addProperty(properties[i], 
						model.createResource(model.getNsPrefixURI("") + "Female"));
					break;				
				}
				break;
			
			default: 
				if (! values[i].isEmpty())
					person.addProperty(properties[i], values[i]);
				break;
			}
	}

Lecture 4: TDB and Fuseki

Creating a dataset

        Dataset dataset = TDBFactory.createDataset();
        Model defaultModel = dataset.getDefaultModel();

        ...

        dataset.close()

This creates an in-memory dataset, which is not persistent.

Creating/loading a TDB-backed dataset

        Dataset dataset = TDBFactory.createDataset("TDBTest");
        Model defaultModel = dataset.getDefaultModel();

        ...

        dataset.close()

The first time it is run, this creates a persistent dataset, backed by a TDB triple store located in the directory "TDBTest" inside your Eclipse project. Refresh the project to see it (or F5).

When re-run later, this loads the dataset from the TDB store.

It is important to close a dataset before the program terminates.

Named models

        Model namedModel = ModelFactory.createDefaultModel();
        Resource resFrance2 = namedModel.createResource(iriDbpedia + "France");

        resFrance2.addProperty(RDFS.label, "Frankrike", "no");
        resFrance2.addProperty(RDFS.label, "France", "en");
        resFrance2.addProperty(RDFS.label, "Francia", "es");
       
        Property propPopEst = namedModel.createProperty(iriDbpedia + "ontology/populationEstimate");
        resFrance2.addProperty(propPopEst, "66644000", XSDDatatype.XSDinteger);
       
        namedModel.write(System.out, "TURTLE");
        dataset.addNamedModel("http://example.org/nm", namedModel);

        RDFDataMgr.write(System.out, dataset, Lang.TRIG);

This creates a new model and adds it as a named model to the dataset. We must use RDFDataMgr two write out datasets containing named graphs in formats such as TRIG, TRIX and NQ.

Fuseki

When you get started, it is easiest to run Fuseki from the directory where you unpacked it along with the other Jena downloads, for example:

 cd C:\Programs\Jena\apache-jena-fuseki-2.4.1

or

 cd /opt/Jena/apache-jena-fuseki-2.4.1

Start the Fuseki server with this command on Windows:

 fuseki-server --localhost --loc=C:\...\your\Eclipse\workspace\INFO216\TDBTest /tdb

On Linux:

 sh fuseki-server --localhost --loc=C:\...\your\Eclipse\workspace\INFO216\TDBTest /tdb

Here, TDBTest is the name of the triple store, INFO216 is the name of the Eclipse project, located inside your Eclipse workspace. Use the --help option to see what the other options do.

Open a web browser and go to localhost:3030 to run queries/updates and otherwise explore and use the TDB-backed dataset.

Lecture 5: JSON and JSON-LD

Web API to String

A fairly simple and straightforward way to call a web API and return the results as a String. (There are many libraries that do this in more advanced ways, but it will get you started.)

	// calls a Web API and returns the result as a string
	// this method is not necessary, but included because it may be useful for some of you
	static String getResponseBody(URL serverAddress) {
		String responseBody = null;

		HttpURLConnection connection = null;

		BufferedReader rd  = null;
		StringBuilder sb = null;
		String line = null;

		try {
			// send GET request
			connection = null;
			connection = (HttpURLConnection)serverAddress.openConnection();
			connection.setRequestMethod("GET");
			// connection.setDoOutput(true);
			connection.setReadTimeout(10000);
			connection.connect();

			// receive response
			rd  = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			sb = new StringBuilder();

			// turn response into a string
			while ((line = rd.readLine()) != null)
			{
				sb.append(line + '\n');
			}
			responseBody = sb.toString();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// close the connection
			connection.disconnect();
			rd = null;
			sb = null;
			connection = null;
		}
		
		return responseBody;
	}

Web API to JSON Object (new way)

(After upgrading to apache-jena-3.2.0 and jsonld-java-0.9.0 the following simple approach seems to work. The downside is that you have no corresponding proxy call (see below).)

	String callIRL = "http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&country=ES&username=demo";
	URL url = new URL(callIRL);
	Object jsonObj = JsonUtils.fromURL(url, JsonUtils.getDefaultHttpClient());

(You may need to register your own username at api.geonames.org to run this repeatedly.)

Web API to JSON Object (old way)

Similar to the above, but assumes the result is JSON and parses it.

	static Object getJsonBody(URL serverAddress) {
		Object jsonObject = null;
		HttpURLConnection connection = null;

		try {
			// send GET request
			connection = null;
			connection = (HttpURLConnection)serverAddress.openConnection();
			connection.setRequestMethod("GET");
			// connection.setDoOutput(true);
			connection.setReadTimeout(10000);
			connection.connect();

			// parse JSON reponse
			jsonObject = JsonUtils.fromInputStream(connection.getInputStream());

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			//close the connection
			connection.disconnect();
			connection = null;
		}

		return jsonObject;		
	}

You call this like above, but with the call-line changed:

	String callIRL = "http://api.geonames.org/postalCodeLookupJSON"
			+ "?postalcode=46020&country=ES&username=demo";
	URL url = new URL(callIRL);
	Object jsonObj = getJsonBody(url);

Web API proxy (for the old way)

This method seems to behave like the previous getJsonBody method, but it does nto make an actual API call and instead returns a fixed JSON object. Use it while you are debugging so you do not go above your daily limit.

	static Object getJsonBodyProxy(URL url) {
		
		String jsonBody = "{\"postalcodes\":[{\"adminCode2\":\"V\",\"adminCode1\":\"VC\","
				+ "\"adminName2\":\"Valencia\",\"lng\":-0.377386808395386,"
				+ "\"countryCode\":\"ES\",\"postalcode\":\"46020\","
				+ "\"adminName1\":\"Comunidad Valenciana\",\"placeName\":\"Valencia\","
				+ "\"lat\":39.4697524227712}]}";
		try { 
			return JsonUtils.fromString(jsonBody);
		} catch(Exception ex) {
			return null;
		}
	}

Prettyprint a JSON Object

	System.out.println(JsonUtils.toPrettyString(jsonObj));

Expand a JSON Object

You can run the code below on the following proxy string, or you can use it on the outputs from a regular JSON web API.

	// we pretend this string comes from a regular JSON web API call
	String proxyJsonReponse = ""
			+ "{"
			+ "    \"name\" : \"Markus Lanthaler\", "
			+ "    \"workplaceHomepage\" : \"http://www.homepage.com/ML\", "
			+ "    \"address\" : {"
			+ "        \"streetAddress\" : \"Somestreet 123\", "
			+ "        \"cityAddress\" : \"ZIP-4567 Acity\" "
			+ "    }"
			+ "}";

	// parse the string into a JSON object
	Object jsonObj = JsonUtils.fromString(proxyJsonReponse);
	System.out.println(JsonUtils.toPrettyString(jsonObj));

First create a context object:

	// create a context object
	String baseIRI = "http://ex.org/base#";
	Map contextObj = new HashMap() {{
		put("@context", new HashMap() {{
			put("name", FOAF.name.getURI());
			put("workplaceHomepage", "@id");
			put("address", baseIRI + "address");
			put("streetAddress", baseIRI + "streetAddress");
			put("cityAddress", baseIRI + "cityAddress");
		}});
	}};

Note that without a mapping for "address" in the context, expansion will not work for "street-" and "cityAdress", because they are nested inside "address" in the JSON object.

We have two ways to expand a JSON object: either with or without an explicit options object. We first look at expansion with an explicit options object, which can give more control:

	// create and set an options object
	JsonLdOptions expandOptions = new JsonLdOptions(baseIRI);
	expandOptions.setExpandContext(contextObj);
	
	// expand the JSON object
	Object expandedObj = JsonLdProcessor.expand(jsonObj, expandOptions);
	System.out.println(JsonUtils.toPrettyString(expandedObj));

Afterwards, you can read the expanded object, which is now a JSON-LD object, into a Jena Model:

	Model model = ModelFactory.createDefaultModel();
	model.read(IOUtils.toInputStream(JsonUtils.toPrettyString(expandedObj), "UTF-8"), baseIRI, "JSON-LD");
	model.write(System.out, "JSON-LD");

We now return to expansion without an explicit options object, where we first combine the context object and the JSON object directly:

	contextObj.put("@graph", jsonObj);		
	Object expandedObj = JsonLdProcessor.expand(contextObj);
	System.out.println(JsonUtils.toPrettyString(expandedObj));

Here are two other ways to combine the context object and JSON object:

	((Map) jsonObj).put("@context", contextObj.get("@context"));
	Object expandedObj = JsonLdProcessor.expand(jsonObj);
	System.out.println(JsonUtils.toPrettyString(expandedObj));

and

	
	((Map) jsonObj).putAll(contextObj);
	Object expandedObj = JsonLdProcessor.expand(jsonObj);
	System.out.println(JsonUtils.toPrettyString(expandedObj));

Flatten an expanded JSON-LD object

	Object flattenedExpandedObj = JsonLdProcessor.flatten(expandedObj, new JsonLdOptions());
	System.out.println(JsonUtils.toPrettyString(flattenedExpandedObj));

Compact a JSON-LD Object

You can run the code below on the following proxy string, or you can use it on the outputs from a semantic JSON-LD web API.

	// we pretend this string comes from a semantic JSON-LD web API call
	String proxyJsonLdReponse = ""
			+ "{"
			+ "    \"@id\" : \"http://www.homepage.com/ML\", "
			+ "    \"http://xmlns.com/foaf/0.1/name\" : [ { "
			+ "        \"@value\" : \"Markus Lanthaler\" "
			+ "    } ], "
			+ "    \"http://ex.org/base#address\" : [ { "
			+ "        \"http://ex.org/base#cityAddress\" : [ { "
			+ "            \"@value\" : \"ZIP-4567 Acity\" "
			+ "        } ], "
			+ "        \"http://ex.org/base#streetAddress\" : [ { "
			+ "            \"@value\" : \"Somestreet 123\" "
			+ "        } ] "
			+ "    } ] "
			+ "}";

	// create a JSON object
	Object jsonObj = JsonUtils.fromString(proxyJsonLdReponse);
	System.out.println(JsonUtils.toPrettyString(jsonObj));

First create a context object:

		
	// create a context object
	String baseIRI = "http://ex.org/base#";
	Map contextObj = new HashMap() {{
		put("@context", new HashMap() {{
			put("name", FOAF.name.getURI());
			put("workplaceHomepage", "@id");
			put("address", baseIRI + "address");
			put("streetAddress", baseIRI + "streetAddress");
			put("cityAddress", baseIRI + "cityAddress");
		}});
	}};

Then compact the JSON-LD object using the context object:

	Object compactedObj = JsonLdProcessor.compact(jsonObj, contextObj, new JsonLdOptions());
	System.out.println(JsonUtils.toPrettyString(compactedObj));

	// finally remove the context object
	((Map) compactedObj).remove("@context");

Flatten a compacted JSON object

Flatten the compacted JSON object:

	Object flattenedCompactedObj = JsonLdProcessor.flatten(compactedObj, defaultOptions);
	System.out.println(JsonUtils.toPrettyString(flattenedCompactedObj));

JSON-LD web API to Dataset

The following code loads the output from a JSON-LD web API call straight into a Jena dataset:

	String uri = "http://www.europeana.eu/api/v2/record/92065/"
			+ "BibliographicResource_1000056084136.jsonld?wskey=tX3Zstfo2";	
	Dataset dataset = RDFDataMgr.loadDataset(uri, Lang.JSONLD);
	dataset.getDefaultModel().write(System.out, "TURTLE");

Please register to get your own API key instead of tX3Zstfo2 if you are going to run this more than once. You can find more JSON-LD web APIs at [1].

Lecture 6: SPARQL Query and Update

Load a simple test database

public class TDBLoadTestDataset {
	public static void main(String[] args) {
		String iriBase = "http://no.uib.infomedia.info216/";
		String iriDbpedia = "http://dbpedia.org/resource/";

		Dataset dataset = TDBFactory.createDataset("TDBTest");
		dataset.getDefaultModel().removeAll();
				
		Model defaultModel = dataset.getDefaultModel();
		
		Resource resCadeTracy = defaultModel.createResource(iriBase + "Cade_Tracy");
		resCadeTracy.addLiteral(FOAF.name, "Cade Tracy");

		Resource resNorway = defaultModel.createResource(iriDbpedia + "Norway");
		Resource resFrance = defaultModel.createResource(iriDbpedia + "France");
		Property propVisited = defaultModel.createProperty(iriBase + "visited");
		resCadeTracy.addProperty(propVisited, resNorway);
		resCadeTracy.addProperty(propVisited, resFrance);
		
		System.out.println("Default model:");
		defaultModel.write(System.out, "TURTLE");
	    
		Model namedModel = ModelFactory.createDefaultModel();
		Resource resFrance2 = namedModel.createResource(iriDbpedia + "France");

		resFrance2.addProperty(RDFS.label, "Frankrike", "no");
		resFrance2.addProperty(RDFS.label, "France", "en");
		resFrance2.addProperty(RDFS.label, "Francia", "es");
		
		Property propPopEst = namedModel.createProperty(iriDbpedia + "ontology/populationEstimate");
		resFrance2.addProperty(propPopEst, "66644000", XSDDatatype.XSDinteger);
		
		System.out.println();
		System.out.println("Named model:");
		namedModel.write(System.out, "TURTLE");
		dataset.addNamedModel(iriBase + "France", namedModel);

		System.out.println();
		System.out.println("Dataset:");
		RDFDataMgr.write(System.out, dataset, Lang.TRIX);
				
		dataset.close();
	}
}

Basic INSERT DATA update

	UpdateAction.parseExecute(""
			+ "INSERT DATA {"
			+ "    <http://ex.org/aSubject> <http://ex.org/aPredicate> <http://ex.org/anObject> . "
			+ "}", dataset);

Basic SELECT query

	ResultSet resultSet = QueryExecutionFactory
		.create(""
			+ "SELECT ?s ?p ?o WHERE {"
			+ "    ?s ?p ?o ."
			+ "}", dataset)
		.execSelect();

	while (resultSet.hasNext()) {
		QuerySolution qsol = resultSet.nextSolution();
		System.out.println(qsol.toString());
	}

Convert the ResultSet into a JSON object

	List<Map> jsonList = new Vector<Map>();
	while (resultSet.hasNext()) {
		QuerySolution qsol = resultSet.nextSolution();
		Iterator<String> varNames = qsol.varNames();
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		while (varNames.hasNext()) {
			String varName = varNames.next();
			jsonMap.put(varName, qsol.get(varName).toString());
		}
		jsonList.add(jsonMap);
	}
	System.out.println(JsonUtils.toPrettyString(jsonList));

SELECT query with Query object

	// select example
	Query query = QueryFactory.create(""
			+ "SELECT ?s ?p ?o WHERE {"
			+ "    ?s ?p ?o ."
			+ "}");
	QueryExecution queryExecution = QueryExecutionFactory.create(query, dataset);	
	ResultSet resultSet = queryExecution.execSelect();

SELECT query from SPARQL endpoint

	ResultSet resultSet = QueryExecutionFactory.create(""
					+ "SELECT ?s ?p ?o WHERE {"
					+ "    GRAPH ?g { ?s ?p2 ?o2 . } "
					+ "	   SERVICE <http://dbpedia.org/sparql> {"
					+ "        ?s ?p ?o ."
					+ "    }"
					+ "}", dataset).execSelect();
		
	while (resultSet.hasNext()) {
		QuerySolution qs = resultSet.nextSolution();
		System.out.println(qs.toString());
	}

Basic ASK query

	QueryExecution queryExecution = QueryExecutionFactory.create(""
			+ "ASK { GRAPH ?g { ?s ?p ?o } }"
			+ "", dataset);
	boolean res = queryExecution.execAsk();
	System.out.println("The result is " + res);

ASK query from IRL

	QueryExecution queryExecution = QueryExecutionFactory.create(""
			+ "ASK "
			+ "    FROM <http://people.uib.no/sinoa/european-populations.ttl> { "
			+ "	   <" + iriDbpedia + "Vatican_City> ?p ?o . "
			+ "    }"
			+ "");
	boolean res = queryExecution.execAsk();
	System.out.println("The result is " + res);

Basic DESCRIBE query

	Model franceModel = QueryExecutionFactory.create(""
			+ "DESCRIBE <" + iriDbpedia + "France>"
			+ "", dataset).execDescribe();
	franceModel.write(System.out, "TURTLE");

Basic CONSTRUCT query

	Model franceModel = QueryExecutionFactory.create(""
			+ "CONSTRUCT { ?s ?p ?o . } WHERE { "
			+ "    GRAPH ?g { ?s ?p ?o . } "
			+ "}", dataset).execConstruct();
	franceModel.write(System.out, "TURTLE");

CONSTRUCT query from IRL

	Model franceModel = QueryExecutionFactory.create(""
			+ "CONSTRUCT { ?s ?p ?o . } "
			+ "    FROM <http://people.uib.no/sinoa/european-populations.ttl> "
			+ "WHERE { "
			+ "    ?s ?p ?o . "
			+ "}").execConstruct();
	franceModel.write(System.out, "TURTLE");

Complex SPARQL predicates (Fuseki)

In the apache-jena-fuseki-version folder:

fuseki-server --localhost --update --mem /mem

In your web browser, goto http://localhost:3030/ . Use SPARQL ENDPOINT http://localhost:3030/mem/update for the INSERT updates and http://localhost:3030/mem/query for the SELECT queries below.

PREFIX x: <http://example.org/myex#>

INSERT DATA {
    x:IngridAlexandra x:father x:HaakonMagnus ;
                      x:mother x:MetteMarit .
    x:HaakonMagnus x:sister x:MarthaLouise .
}

Keep the PREFIX line in all the following queries:

SELECT ?s ?o WHERE {
    ?s (x:father | x:mother) ?o .
}
SELECT ?s ?o WHERE {
    ?s (x:father / x:sister) ?o .
}
SELECT ?s ?o WHERE {
    ?s ^(x:father / x:sister) ?o .
}
SELECT ?s ?o WHERE {
    ?s (^x:sister / ^x:father) ?o .
}
SELECT ?s ?o WHERE {
    ?s !x:sister ?o .
}

Add some mothere triples:

INSERT DATA {
    x:HaakonMagnus x:father x:Harald .
    x:Harald x:father x:Olav .
    x:Olav x:father x:Haakon .
}
SELECT ?o WHERE
{
    x:IngridAlexandra x:father+ ?o .
}
SELECT ?o WHERE
{
    x:IngridAlexandra x:father* ?o .
}
SELECT ?o WHERE
{
    x:IngridAlexandra x:father? ?o .
}
SELECT ?o WHERE
{
    x:IngridAlexandra x:father{2} ?o .
}
SELECT ?o WHERE
{
    x:IngridAlexandra x:father{2,4} ?o .
}

Lecture 7: Sgvizler

See the guidelines for the corresponding lab: Start Fuseki with a dataset called eupop and load the data set available at http://people.uib.no/sinoa/european-populations.ttl .

Here is a HTML page that works with this data set. It is a minimal adaption from Martin Skjævelands minimal running example at http://mgskjaeveland.github.io/sgvizler/example/quick-start.html (note: we have added http: to the first JavaScript src.):

<html>
  <head>
    <title>MWE</title>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.js"></script>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://mgskjaeveland.github.io/sgvizler/v/0.6/sgvizler.js"></script>
    <script>
      $(document).ready(
          function (){ sgvizler.containerDrawAll(); }
      );
    </script>
  </head>
  <body>
    <h1>Sgvizler MWE</h1>
    <p>Please allow the page to load for a few seconds.</p>
    <div id="example"
         data-sgvizler-endpoint="http://localhost:3030/eupop/sparql"
         data-sgvizler-query="
                  PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> 

                  SELECT DISTINCT ?l (SAMPLE(?p) AS ?p2)
                  WHERE {
                    ?c <http://www.w3.org/2000/01/rdf-schema#label> ?ltl ;	
                  	 <http://dbpedia.org/ontology/populationTotal> ?p .
                    BIND( STR(?ltl) AS ?l )  
                  }
                  GROUP BY ?l
                  LIMIT 25" 
         data-sgvizler-chart="google.visualization.PieChart"
         style="width:800px; height:400px;"></div>
  </body>
</html>

Lecture 8: RDFS Plus (Basic OWL)

Create an ontology with individuals and object properties

	public HelloOWL() {
		String base = "http://ex.org/fam#";
		
		OntModel ont = ModelFactory.createOntologyModel();
		
		ObjectProperty ancestorProp = ont.createObjectProperty(base + "hasAncestor");
	
		Individual iaInd = ont.createIndividual(base + "IngridAlexandra", FOAF.Person);
		Individual hmInd = ont.createIndividual(base + "HaakonMagnus", FOAF.Person);
		Individual haInd = ont.createIndividual(base + "Harald", FOAF.Person);
	
		iaInd.addProperty(ancestorProp, hmInd);
		hmInd.addProperty(ancestorProp, haInd);
		
		ont.write(System.out, "TURTLE");
	}
	
	public static void main(String[] args) {
		new HelloOWL();
	}

Print axioms and entailments too

	ont.writeAll(System.out, "TURTLE");

Make a property transitive

	// must create an OntModel with an associated reasoner
	OntModel ont = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF);
		
	ObjectProperty ancestorProp = ont.createObjectProperty(base + "hasAncestor");
	// must make the property transitive
	ancestorProp.addRDFType(OWL.TransitiveProperty);

	...

	// iaInd now has haInd as an entailed ancestor
	ont.writeAll(System.out, "TURTLE");
INFO216, UiB, Spring 2017, Prof. Andreas L. Opdahl (c). All code examples are CC0.