Simple Query on RDF file in Java

As you have already learned about controlling prefix, generating RDF files and about RDF Iterators in the previous examples, so in this section we are going to describe how to run simple query on the RDF graph model.

Simple Query on RDF file in Java

Simple Query on RDF file in Java

     

As you have already learned about controlling prefix, generating RDF files and about RDF Iterators in the previous examples, so in this section we are going to describe how to run simple query on the RDF graph model. Now lets see the example that can fires a simple query. The example is going to list the subject with property name "VCARD.FN".

To do this we have taken an object of Model interface. By the use of listSubjectsWithProperty() method we have queried about VCARD.FN . It returns an object of ResIterator (i.e ResourceIterator).

"Resource res = iter.nextResource();" 

Above line of code gets all the resources of that particular Subject. Now we can get property and other information's of that resource.

getProperty() gets property of that resource.

getURI() will gets URI of that resource.

RDFQuery.java

import java.io.*;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.vocabulary.*;

public class RDFQuery extends Object {
  public static void main (String args[]) {
  String personURI  = "http://amitKumar";
  String givenName  = "Amit";
  String familyName = "Kumar";
  String fullName = givenName +" "+ familyName;
  Model model = ModelFactory.createDefaultModel();
  Resource node = model.createResource(personURI)
 .addProperty(VCARD.FN, fullName)
 .addProperty(VCARD.N,
  model.createResource()
 .addProperty(VCARD.Given, givenName)
 .addProperty(VCARD.Family, familyName));
  ResIterator iter= model.listSubjectsWithProperty(VCARD.FN);
  while(iter.hasNext()){
  Resource res=iter.nextResource();
  System.out.println("Property  "+
  res.getProperty
(VCARD.FN).getString());
  System.out.println("Resource URI  "+res.getURI());  
  }
  }
}

To run this example follow these steps:

  • Create and Save RDFQuery.java
  • Compile RDFQuery.java
  • Run RDFQuery.class file and you will get the following output:

Output:

Download Source Code