7.16 Example Queries Using RDF Graph Support for Apache Jena

This section includes example queries using the support for Apache Jena. Each example is self-contained: it typically creates a model, creates triples, performs a query that may involve inference, displays the result, and drops the RDF graph.

The example queries perform the following:

  • Count asserted triples and asserted plus inferred triples in an example "university" ontology, both by referencing the ontology by a URL and by bulk loading the ontology from a local file.
  • Run several SPARQL queries using a "family" ontology, including features such as LIMIT, OFFSET, TIMEOUT, DOP (degree of parallelism), ASK, DESCRIBE, CONSTRUCT, GRAPH, ALLOW_DUP (duplicate triples with multiple models), SPARUL (inserting data)
  • Use the ARQ built-in function
  • Use a SELECT cast query
  • Instantiate Oracle Database using OracleConnection
  • Use Oracle Database connection pooling

To run a query, you must do the following:

  1. Include the code in a Java source file. The examples used in this section are supplied in files in the examples directory of the support for Apache Jena download.

  2. Compile the Java source file. For example:

    > javac -classpath ../jar/'*' Test.java
    

    Note:

    The javac and java commands must each be on a single command line.

  3. Run the compiled file. For example:

    java -classpath ./:../jar/'*' Test jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> TestModel NET1

7.16.1 Query Family Relationships

Example 7-17 Query Family Relationships

The following example specifies that John is the father of Mary, and it selects and displays the subject and object in each fatherOf relationship

import oracle.spatial.rdf.client.jena.*;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.graph.*;
import org.apache.jena.query.*;

public class Test_privnet {

  public static void main(String[] args) throws Exception
  {
  
    String szJdbcURL = args[0];
    String szUser    = args[1];
    String szPasswd  = args[2];

    String szModelName = args[3];    
    String szNetworkName = args[4];
	  
    Oracle oracle = new Oracle(szJdbcURL, szUser, szPasswd);
    Model model = ModelOracleSem.createOracleSemModel(oracle, szModelName, szUser, szNetworkName);

    model.getGraph().add(Triple.create(
          NodeFactory.createURI("http://example.com/John"),
          NodeFactory.createURI("http://example.com/fatherOf"),
          NodeFactory.createURI("http://example.com/Mary")));

    Query query = QueryFactory.create(
        "select ?f ?k WHERE {?f <http://example.com/fatherOf> ?k .}");
    QueryExecution qexec = QueryExecutionFactory.create(query, model);
    ResultSet results = qexec.execSelect();
    ResultSetFormatter.out(System.out, results, query);

    model.close();
    oracle.dispose();
  }
}

The following are the commands to compile and run the preceding code along with the expected output of the java command.

javac -classpath ../jar/'*' Test_privnet.java
java -classpath ./:../jar/'*'  Test_privnet jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> M1 NET1
 
---------------------------------------------------------
| f                         | k                         |
=========================================================
| <http://example.com/John> | <http://example.com/Mary> |
---------------------------------------------------------

7.16.2 Load OWL Ontology and Perform OWLPrime Inference

The following example loads an OWL ontology and performs OWLPrime inference. Note that the OWL ontology is in RDF/XML format, and after it is loaded into Oracle it will be serialized out in N-TRIPLE form. The example also queries for the number of asserted and inferred triples.

The ontology in this example can be retrieved from http://swat.cse.lehigh.edu/onto/univ-bench.owl, and it describes roles, resources, and relationships in a university environment.

Example 7-18 Load OWL Ontology and Perform OWLPrime inference

import java.io.*;
import org.apache.jena.query.*;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.util.FileManager;
import oracle.spatial.rdf.client.jena.*;

public class Test6_privnet 
{
  public static void main(String[] args) throws Exception
  {
    String szJdbcURL = args[0];
    String szUser    = args[1];
    String szPasswd  = args[2];

    String szModelName = args[3];    
    String szNetworkName = args[4];
    
    Oracle oracle = new Oracle(szJdbcURL, szUser, szPasswd);
    
    Model model = ModelOracleSem.createOracleSemModel(oracle, szModelName, szUser, szNetworkName);
        
    // load UNIV ontology
    InputStream in = FileManager.get().open("./univ-bench.owl" );

    model.read(in, null);
   
    OutputStream os = new FileOutputStream("./univ-bench.nt");
    model.write(os, "N-TRIPLE");
    os.close();

    String queryString =
      " SELECT ?subject ?prop ?object WHERE { ?subject ?prop ?object } ";

    Query query = QueryFactory.create(queryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, model) ;

    try {
      int iTriplesCount = 0;
      ResultSet results = qexec.execSelect() ;
      for ( ; results.hasNext() ; ) {
        QuerySolution soln = results.nextSolution() ;
        iTriplesCount++;
      }
      System.out.println("Asserted  triples count: " + iTriplesCount);
    } 
    finally { 
      qexec.close() ; 
    }
    
    Attachment attachment = Attachment.createInstance(
        new String[] {}, "OWLPRIME",
        InferenceMaintenanceMode.NO_UPDATE,
        QueryOptions.DEFAULT);

    GraphOracleSem graph = new GraphOracleSem(oracle, szModelName, attachment, szUser, szNetworkName);
    graph.analyze();
    graph.performInference();


    query = QueryFactory.create(queryString) ;
    qexec = QueryExecutionFactory.create(query,new ModelOracleSem(graph)) ;

    try {
      int iTriplesCount = 0;
      ResultSet results = qexec.execSelect() ;
      for ( ; results.hasNext() ; ) {
        QuerySolution soln = results.nextSolution() ;
        iTriplesCount++;
      }
      System.out.println("Asserted + Infered triples count: " + iTriplesCount);
    } 
    finally { 
      qexec.close() ; 
    }

    OracleUtils.dropSemanticModel(oracle, szModelName, szUser, szNetworkName);
    
    model.close();    
    oracle.dispose();
  }
}

The following are the commands to compile and run the preceding code along with the expected output of the java command.

javac -classpath ../jar/'*' Test6_privnet.java
java -classpath ./:../jar/'*'  Test6_privnet jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> M1 NET1
Asserted  triples count: 293
Asserted + Infered triples count: 340

Note that this output reflects an older version of the LUBM ontology. The latest version of the ontology has more triples.

7.16.3 Bulk Load OWL Ontology and Perform OWLPrime Inference

The following example loads the same OWL ontology as in Example 7-18, but stored in a local file using Bulk Loader. Ontologies can also be loaded using an incremental and batch loader; these two methods are also listed in the example for completeness.

Example 7-19 Bulk Load OWL Ontology and Perform OWLPrime inference

import java.io.*;
import org.apache.jena.query.*;
import org.apache.jena.graph.*;
import org.apache.jena.rdf.model.*;
import org.apache.jena.util.*;
import oracle.spatial.rdf.client.jena.*;

public class Test7_privnet 
{
  public static void main(String[] args) throws Exception
  {
    String szJdbcURL = args[0];
    String szUser    = args[1];
    String szPasswd  = args[2];

    String szModelName = args[3];
    String szNetworkName = args[4];
    
    // in memory Jena Model
    Model model = ModelFactory.createDefaultModel();
    InputStream is = FileManager.get().open("./univ-bench.owl");
    model.read(is, "", "RDF/XML");
    is.close();

    Oracle oracle = new Oracle(szJdbcURL, szUser, szPasswd);
    
    ModelOracleSem modelDest = ModelOracleSem.createOracleSemModel(oracle, szModelName, szUser, szNetworkName);

    GraphOracleSem g = modelDest.getGraph();
    g.dropApplicationTableIndex();

    int method = 2; // try bulk loader
    String tbs = "SYSAUX"; // can be customized
    if (method == 0) {
      System.out.println("start incremental");
      modelDest.add(model);
      System.out.println("end size " + modelDest.size());
    }
    else if (method == 1) {
      System.out.println("start batch load");
      g.getBulkUpdateHandler().addInBatch(
          GraphUtil.findAll(model.getGraph()), tbs);
      System.out.println("end size " + modelDest.size());
    }
    else {
      System.out.println("start bulk load");
      g.getBulkUpdateHandler().addInBulk(
          GraphUtil.findAll(model.getGraph()), tbs);
      System.out.println("end size " + modelDest.size());
    }
    g.rebuildApplicationTableIndex();
   

    long lCount = g.getCount(Triple.ANY);
    System.out.println("Asserted  triples count: " + lCount);
    
    model.close();    
    oracle.dispose();
  }
}

The following are the commands to compile and run the preceding code along with the expected output of the java command.

javac -classpath ../jar/'*' Test7_privnet.java
java -classpath ./:../jar/'*'  Test7_privnet jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> M1 NET1
start bulk load
end size 293
Asserted  triples count: 293

Note that this output reflects an older version of the LUBM ontology. The latest version of the ontology has more triples.

7.16.4 SPARQL OPTIONAL Query

The following example shows a SPARQL OPTIONAL query. It inserts triples that postulate the following:

  • John is a parent of Mary.
  • John is a parent of Jack.
  • Mary is a parent of Jill.

It then finds parent-child relationships, optionally including any grandchild (gkid) relationships.

Example 7-20 SPARQL OPTIONAL Query

import java.io.*;
import org.apache.jena.query.*;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.util.FileManager;
import oracle.spatial.rdf.client.jena.*;
import org.apache.jena.graph.*;

public class Test8_privnet 
{
  public static void main(String[] args) throws Exception
  {
    String szJdbcURL = args[0];
    String szUser    = args[1];
    String szPasswd  = args[2];

    String szModelName = args[3];
    String networkName = args[4];
    
    Oracle oracle = new Oracle(szJdbcURL, szUser, szPasswd);
    
    ModelOracleSem model = ModelOracleSem.createOracleSemModel(oracle, szModelName, szUser, networkName);
    GraphOracleSem g = model.getGraph();

    g.add(Triple.create(
          NodeFactory.createURI("u:John"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Mary")));
    g.add(Triple.create(
          NodeFactory.createURI("u:John"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Jack")));
    g.add(Triple.create(
          NodeFactory.createURI("u:Mary"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Jill")));
        
    String queryString =
      " SELECT ?s ?o ?gkid WHERE { ?s <u:parentOf> ?o . OPTIONAL {?o <u:parentOf> ?gkid }} ";

    Query query = QueryFactory.create(queryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, model) ;

    try {
      ResultSet results = qexec.execSelect() ;
      ResultSetFormatter.out(System.out, results, query);
    } 
    finally { 
      qexec.close() ; 
    }
    
    OracleUtils.dropSemanticModel(oracle, szModelName, szUser, networkName);
    
    model.close();    
    oracle.dispose();
  }
}

The following are the commands to compile and run the preceding code along with the expected output of the java command.

javac -classpath ../jar/'*' Test8_privnet.java
java -classpath ./:../jar/'*'  Test8_privnet jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> M1 NET1
----------------------------------
| s        | o        | gkid     |
==================================
| <u:John> | <u:Mary> | <u:Jill> |
| <u:Mary> | <u:Jill> |          |
| <u:John> | <u:Jack> |          |
---------------------------------- 

7.16.5 SPARQL Query with LIMIT and OFFSET

The following example shows a SPARQL query with LIMIT and OFFSET. It inserts triples that postulate the following:

  • John is a parent of Mary.
  • John is a parent of Jack.
  • Mary is a parent of Jill.

It then finds one parent-child relationship (LIMIT 1), skipping the first two parent-child relationships encountered (OFFSET 2), and optionally includes any grandchild (gkid) relationships for the one found.

Example 7-21 SPARQL Query with LIMIT and OFFSET

import java.io.*;
import org.apache.jena.query.*;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.util.FileManager;
import oracle.spatial.rdf.client.jena.*;
import org.apache.jena.graph.*;

public class Test9_privnet 
{
  public static void main(String[] args) throws Exception
  {
    String szJdbcURL = args[0];
    String szUser    = args[1];
    String szPasswd  = args[2];

    String szModelName = args[3];
    String szNetworkName = args[4];
    
    Oracle oracle = new Oracle(szJdbcURL, szUser, szPasswd);
    
    ModelOracleSem model = ModelOracleSem.createOracleSemModel(oracle, szModelName, szUser, szNetworkName);
    GraphOracleSem g = model.getGraph();

    g.add(Triple.create(
          NodeFactory.createURI("u:John"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Mary")));
    g.add(Triple.create(
          NodeFactory.createURI("u:John"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Jack")));
    g.add(Triple.create(
          NodeFactory.createURI("u:Mary"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Jill")));
        
    String queryString =
      " SELECT ?s ?o ?gkid WHERE { ?s <u:parentOf> ?o . OPTIONAL {?o <u:parentOf> ?gkid }} "
      + " LIMIT 1 OFFSET 2";

    Query query = QueryFactory.create(queryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, model) ;

    try {
      ResultSet results = qexec.execSelect() ;
      ResultSetFormatter.out(System.out, results, query);
    } 
    finally { 
      qexec.close() ; 
    }
    
    OracleUtils.dropSemanticModel(oracle, szModelName, szUser, szNetworkName);
    
    model.close();    
    oracle.dispose();
  }
}

The following are the commands to compile and run the preceding code along with the expected output of the java command.

javac -classpath ../jar/'*' Test9_privnet.java
java -classpath ./:../jar/'*'  Test9_privnet jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> M1 NET1
------------------------------
| s        | o        | gkid |
==============================
| <u:John> | <u:Jack> |      |
------------------------------ 

7.16.6 SPARQL Query with TIMEOUT and DOP

The following example shows the SPARQL query from Example 7-21 with additional features, including a timeout setting (TIMEOUT=1, in seconds) and parallel execution setting (DOP=4).

Example 7-22 SPARQL Query with TIMEOUT and DOP

import org.apache.jena.query.*;
import oracle.spatial.rdf.client.jena.*;
import org.apache.jena.graph.*;

public class Test10_privnet
{
  public static void main(String[] args) throws Exception
  {
    String szJdbcURL = args[0];
    String szUser    = args[1];
    String szPasswd  = args[2];

    String szModelName = args[3];
    String szNetworkName = args[4];
    
    Oracle oracle = new Oracle(szJdbcURL, szUser, szPasswd);
    
    ModelOracleSem model = ModelOracleSem.createOracleSemModel(oracle, szModelName, szUser, szNetworkName);
    GraphOracleSem g = model.getGraph();

    g.add(Triple.create(
          NodeFactory.createURI("u:John"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Mary")));
    g.add(Triple.create(
          NodeFactory.createURI("u:John"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Jack")));
    g.add(Triple.create(
          NodeFactory.createURI("u:Mary"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Jill")));
        
    String queryString =
        " PREFIX ORACLE_SEM_FS_NS: <http://oracle.com/semtech#dop=4,timeout=1> " 
      + " SELECT ?s ?o ?gkid WHERE { ?s <u:parentOf> ?o . OPTIONAL {?o <u:parentOf> ?gkid }} "
      + " LIMIT 1 OFFSET 2";

    Query query = QueryFactory.create(queryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, model) ;

    try {
      ResultSet results = qexec.execSelect() ;
      ResultSetFormatter.out(System.out, results, query);
    } 
    finally { 
      qexec.close() ; 
    }
    
    OracleUtils.dropSemanticModel(oracle, szModelName, szUser, szNetworkName);
    
    model.close();    
    oracle.dispose();
  }
}

The following are the commands to compile and run the preceding code along with the expected output of the java command.

javac -classpath ../jar/'*' Test10_privnet.java
java -classpath ./:../jar/'*'  Test10_privnet jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> M1 NET1
------------------------------
| s        | o        | gkid |
==============================
| <u:John> | <u:Jack> |      |
------------------------------

7.16.7 Query Involving Named Graphs

The following example shows a query involving named graphs. It involves a default graph that has information about named graph URIs and their publishers. The query finds graph names, their publishers, and within each named graph finds the mailbox value using the foaf:mbox predicate.

Example 7-23 Named Graph Based Query

import org.apache.jena.query.*;
import oracle.spatial.rdf.client.jena.*;
import org.apache.jena.graph.*;

public class Test11_privnet
{
  public static void main(String[] args) throws Exception
  {
    String szJdbcURL = args[0];
    String szUser    = args[1];
    String szPasswd  = args[2];

    String szModelName = args[3];
    String szNetworkName = args[4];
    
    Oracle oracle = new Oracle(szJdbcURL, szUser, szPasswd);

    Dataset ds = DatasetFactory.create();

    ModelOracleSem model = ModelOracleSem.createOracleSemModel(oracle, szModelName, szUser, szNetworkName);
    model.getGraph().add(Triple.create(NodeFactory.createURI("http://example.org/bob"),
          NodeFactory.createURI("http://purl.org/dc/elements/1.1/publisher"),
          NodeFactory.createLiteral("Bob Hacker")));
    model.getGraph().add(Triple.create(NodeFactory.createURI("http://example.org/alice"),
          NodeFactory.createURI("http://purl.org/dc/elements/1.1/publisher"),
          NodeFactory.createLiteral("alice Hacker")));


    ModelOracleSem model1 = ModelOracleSem.createOracleSemModel(oracle, szModelName+"1", szUser, szNetworkName);

    model1.getGraph().add(Triple.create(NodeFactory.createURI("urn:bob"),
                                        NodeFactory.createURI("http://xmlns.com/foaf/0.1/name"),
                                        NodeFactory.createLiteral("Bob")
          ));
    model1.getGraph().add(Triple.create(NodeFactory.createURI("urn:bob"),
                                        NodeFactory.createURI("http://xmlns.com/foaf/0.1/mbox"),
                                        NodeFactory.createURI("mailto:bob@example")
          ));

    ModelOracleSem model2 = ModelOracleSem.createOracleSemModel(oracle, szModelName+"2", szUser, szNetworkName);
    model2.getGraph().add(Triple.create(NodeFactory.createURI("urn:alice"),
                                        NodeFactory.createURI("http://xmlns.com/foaf/0.1/name"),
                                        NodeFactory.createLiteral("Alice")
          ));
    model2.getGraph().add(Triple.create(NodeFactory.createURI("urn:alice"),
                                        NodeFactory.createURI("http://xmlns.com/foaf/0.1/mbox"),
                                        NodeFactory.createURI("mailto:alice@example")
          ));

    ds.setDefaultModel(model);
    ds.addNamedModel("http://example.org/bob",model1);
    ds.addNamedModel("http://example.org/alice",model2);

    String queryString =  
      " PREFIX foaf: <http://xmlns.com/foaf/0.1/> "
    + " PREFIX dc: <http://purl.org/dc/elements/1.1/> "
    + " SELECT ?who ?graph ?mbox "
    + " FROM NAMED <http://example.org/alice> "
    + " FROM NAMED <http://example.org/bob> "
    + " WHERE "
    + " { " 
    + "    ?graph dc:publisher ?who . "
    + "    GRAPH ?graph { ?x foaf:mbox ?mbox } "
    + " } ";

    Query query = QueryFactory.create(queryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, ds) ;

    ResultSet results = qexec.execSelect() ;
    ResultSetFormatter.out(System.out, results, query);
    
    qexec.close();
    model.close();    
    model1.close();    
    model2.close();    

    OracleUtils.dropSemanticModel(oracle, szModelName, szUser, szNetworkName);
    OracleUtils.dropSemanticModel(oracle, szModelName + "1", szUser, szNetworkName);
    OracleUtils.dropSemanticModel(oracle, szModelName + "2", szUser, szNetworkName);
    oracle.dispose();
  }
}

The following are the commands to compile and run the preceding code along with the expected output of the java command.

javac -classpath ./:./jena-2.6.4.jar:./sdordfclient.jar:./ojdbc6.jar:./slf4j-api-1.5.8.jar:./slf4j-log4j12-1.5.8.jar:./arq-2.8.8.jar:./xercesImpl-2.7.1.jar Test11_privnet.java
java -classpath ./:../jar/'*'  Test11_privnet jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> M1 NET1
------------------------------------------------------------------------
| who            | graph                      | mbox                   |
========================================================================
| "alice Hacker" | <http://example.org/alice> | <mailto:alice@example> |
| "Bob Hacker"   | <http://example.org/bob>   | <mailto:bob@example>   |
------------------------------------------------------------------------ 

7.16.8 SPARQL ASK Query

The following example shows a SPARQL ASK query. It inserts a triple that postulates that John is a parent of Mary. It then finds whether John is a parent of Mary.

Example 7-24 SPARQL ASK Query

import org.apache.jena.query.*;
import oracle.spatial.rdf.client.jena.*;
import org.apache.jena.graph.*;

public class Test12_privnet
{
  public static void main(String[] args) throws Exception
  {
    String szJdbcURL = args[0];
    String szUser    = args[1];
    String szPasswd  = args[2];

    String szModelName = args[3];
    String szNetworkName = args[4];
    
    Oracle oracle = new Oracle(szJdbcURL, szUser, szPasswd);
    
    ModelOracleSem model = ModelOracleSem.createOracleSemModel(oracle, szModelName, szUser, szNetworkName);
    GraphOracleSem g = model.getGraph();

    g.add(Triple.create(
          NodeFactory.createURI("u:John"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Mary")));
    String queryString = " ASK { <u:John> <u:parentOf> <u:Mary> } ";

    Query query = QueryFactory.create(queryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, model) ;
    boolean b = qexec.execAsk();
    System.out.println("ask result = " + ((b)?"TRUE":"FALSE"));
    qexec.close() ; 
    
    OracleUtils.dropSemanticModel(oracle, szModelName, szUser, szNetworkName);
    
    model.close();    
    oracle.dispose();
  }
}

The following are the commands to compile and run the preceding code along with the expected output of the java command.

javac -classpath ../jar/'*' Test12_privnet.java
java -classpath ./:../jar/'*'  Test12_privnet jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> M1 NET1
ask result = TRUE

7.16.9 SPARQL DESCRIBE Query

The following example shows a SPARQL DESCRIBE query. It inserts triples that postulate the following:

  • John is a parent of Mary.
  • John is a parent of Jack.
  • Amy is a parent of Jack.

It then finds all relationships that involve any parents of Jack.

Example 7-25 SPARQL DESCRIBE Query

The following are the commands to compile and run the preceding code along with the expected output of the java command.

import org.apache.jena.query.*;
import org.apache.jena.rdf.model.Model;
import oracle.spatial.rdf.client.jena.*;
import org.apache.jena.graph.*;

public class Test13_privnet
{
  public static void main(String[] args) throws Exception
  {
    String szJdbcURL = args[0];
    String szUser    = args[1];
    String szPasswd  = args[2];

    String szModelName = args[3];
    String szNetworkName = args[4];
    
    Oracle oracle = new Oracle(szJdbcURL, szUser, szPasswd);
    
    ModelOracleSem model = ModelOracleSem.createOracleSemModel(oracle, szModelName, szUser, szNetworkName);
    GraphOracleSem g = model.getGraph();

    g.add(Triple.create(
          NodeFactory.createURI("u:John"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Mary")));
    g.add(Triple.create(
          NodeFactory.createURI("u:John"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Jack")));
    g.add(Triple.create(
          NodeFactory.createURI("u:Amy"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Jack")));
    String queryString = " DESCRIBE ?x WHERE {?x <u:parentOf> <u:Jack>}";

    Query query = QueryFactory.create(queryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, model) ;
    Model m = qexec.execDescribe();
    System.out.println("describe result = " + m.toString());

    qexec.close() ; 
    OracleUtils.dropSemanticModel(oracle, szModelName, szUser, szNetworkName);
    model.close();    
    oracle.dispose();
  }
}

The following are the commands to compile and run the preceding code along with the expected output of the java command.

javac -classpath ../jar/'*' Test13_privnet.java
java -classpath ./:../jar/'*'  Test13_privnet jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> M1 NET1
describe result = <ModelCom   {u:Amy @u:parentOf u:Jack; 
     u:John @u:parentOf u:Jack; u:John @u:parentOf u:Mary} |  [u:Amy, u:parentOf, u:Jack] [u:John, u:parentOf,
       u:Jack] [u:John, u:parentOf, u:Mary]>

7.16.10 SPARQL CONSTRUCT Query

The following example shows a SPARQL CONSTRUCT query. It inserts triples that postulate the following:

  • John is a parent of Mary.
  • John is a parent of Jack.
  • Amy is a parent of Jack.
  • Each parent loves all of his or her children.

It then constructs an RDF graph with information about who loves whom.

Example 7-26 SPARQL CONSTRUCT Query

The following are the commands to compile and run the preceding code along with the expected output of the java command.

import org.apache.jena.query.*;
import org.apache.jena.rdf.model.Model;
import oracle.spatial.rdf.client.jena.*;
import org.apache.jena.graph.*;

public class Test14_privnet
{
  public static void main(String[] args) throws Exception
  {
    String szJdbcURL = args[0];
    String szUser    = args[1];
    String szPasswd  = args[2];

    String szModelName = args[3];
    String szNetworkName = args[4];
    
    Oracle oracle = new Oracle(szJdbcURL, szUser, szPasswd);
    
    ModelOracleSem model = ModelOracleSem.createOracleSemModel(oracle, szModelName, szUser, szNetworkName);
    GraphOracleSem g = model.getGraph();

    g.add(Triple.create(
          NodeFactory.createURI("u:John"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Mary")));
    g.add(Triple.create(
          NodeFactory.createURI("u:John"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Jack")));
    g.add(Triple.create(
          NodeFactory.createURI("u:Amy"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Jack")));
    String queryString = " CONSTRUCT { ?s <u:loves> ?o } WHERE {?s <u:parentOf> ?o}";

    Query query = QueryFactory.create(queryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, model) ;
    Model m = qexec.execConstruct();
    System.out.println("Construct result = " + m.toString());

    qexec.close() ; 
    OracleUtils.dropSemanticModel(oracle, szModelName, szUser, szNetworkName);
    model.close();    
    oracle.dispose();
  }
}

The following are the commands to compile and run the preceding code along with the expected output of the java command.

javac -classpath ../jar/'*' Test14_privnet.java
java -classpath ./:../jar/'*'  Test14_privnet jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> M1 NET1
Construct result = <ModelCom   {u:Amy @u:loves u:Jack; 
  u:John @u:loves u:Jack; u:John @u:loves u:Mary} |  [u:Amy, u:loves, u:Jack] [u:John, u:loves,
    u:Jack] [u:John, u:loves, u:Mary]>

7.16.11 Query Multiple Models and Specify "Allow Duplicates"

The following example queries multiple models and uses the "allow duplicates" option. It inserts triples that postulate the following:

  • John is a parent of Jack (in Model 1)
  • Mary is a parent of Jack (in Model 2)
  • Each parent loves all of his or her children

It then finds out who loves whom. It searches both models and allows for the possibility of duplicate triples in the models (although there are no duplicates in this example).

Example 7-27 Query Multiple Models and Specify "Allow Duplicates"

The following are the commands to compile and run the preceding code along with the expected output of the java command.

import org.apache.jena.query.*;
import org.apache.jena.rdf.model.Model;
import oracle.spatial.rdf.client.jena.*;
import org.apache.jena.graph.*;

public class Test15_privnet
{
  public static void main(String[] args) throws Exception
  {
    String szJdbcURL = args[0];
    String szUser    = args[1];
    String szPasswd  = args[2];

    String szModelName1 = args[3];
    String szModelName2 = args[4];
    String szNetworkName = args[5];
    
    Oracle oracle = new Oracle(szJdbcURL, szUser, szPasswd);
    
    ModelOracleSem model1 = ModelOracleSem.createOracleSemModel(oracle, szModelName1, szUser, szNetworkName);
    model1.getGraph().add(Triple.create(
          NodeFactory.createURI("u:John"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Jack")));
    model1.close();

    ModelOracleSem model2 = ModelOracleSem.createOracleSemModel(oracle, szModelName2, szUser, szNetworkName);
    model2.getGraph().add(Triple.create(
          NodeFactory.createURI("u:Mary"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Jack")));
    model2.close();


    String[] modelNamesList = {szModelName2};
    String[] rulebasesList  = {};

    Attachment attachment = Attachment.createInstance(modelNamesList, rulebasesList, 
              InferenceMaintenanceMode.NO_UPDATE, QueryOptions.ALLOW_QUERY_VALID_AND_DUP);

    GraphOracleSem graph = new GraphOracleSem(oracle, szModelName1, attachment, szUser, szNetworkName);
    ModelOracleSem model = new ModelOracleSem(graph);

    String queryString = " CONSTRUCT { ?s <u:loves> ?o } WHERE {?s <u:parentOf> ?o}";

    Query query = QueryFactory.create(queryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, model) ;
    Model m = qexec.execConstruct();
    System.out.println("Construct result = " + m.toString());

    qexec.close() ; 
    model.close();    

    OracleUtils.dropSemanticModel(oracle, szModelName1, szUser, szNetworkName);
    OracleUtils.dropSemanticModel(oracle, szModelName2, szUser, szNetworkName);
    oracle.dispose();
  }
}

The following are the commands to compile and run the preceding code along with the expected output of the java command.

javac -classpath ../jar/'*' Test15_privnet.java
java -classpath ./:../jar/'*'  Test15_privnet jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> M1 M2 NET1
Construct result = <ModelCom   {u:Mary @u:loves u:Jack; u:John @u:loves u:Jack} |  [u:Mary, u:loves, u:Jack] [u:John, u:loves, u:Jack]>

7.16.12 SPARQL Update

The following example inserts two triples into a model.

Example 7-28 SPARQL Update

import org.apache.jena.util.iterator.*;
import oracle.spatial.rdf.client.jena.*;
import org.apache.jena.graph.*;
import org.apache.jena.update.*;

public class Test16_privnet
{
  public static void main(String[] args) throws Exception
  {
    String szJdbcURL = args[0];
    String szUser    = args[1];
    String szPasswd  = args[2];

    String szModelName = args[3];
    String szNetworkName = args[4];
    
    Oracle oracle = new Oracle(szJdbcURL, szUser, szPasswd);
    
    ModelOracleSem model = ModelOracleSem.createOracleSemModel(oracle, szModelName, szUser, szNetworkName);
    GraphOracleSem g = model.getGraph();
    String insertString =  
      " PREFIX dc: <http://purl.org/dc/elements/1.1/> "         + 
      " INSERT DATA "                                           +
      " { <http://example/book3> dc:title    \"A new book\" ; " +
      "                         dc:creator  \"A.N.Other\" . "   + 
      " }   ";

    UpdateAction.parseExecute(insertString,  model);

    ExtendedIterator<Triple> ei = GraphUtil.findAll(g);
    while (ei.hasNext()) {
      System.out.println("Triple " + ei.next().toString());
    }
    OracleUtils.dropSemanticModel(oracle, szModelName, szUser, szNetworkName);
    model.close();    
    oracle.dispose();
  }
}

The following are the commands to compile and run the preceding code along with the expected output of the java command.

javac -classpath ../jar/'*' Test16_privnet.java
java -classpath ./:../jar/'*'  Test16_privnet jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> M1 NET1
Triple http://example/book3 @dc:title "A new book"
Triple http://example/book3 @dc:creator "A.N.Other"

7.16.13 SPARQL Query with ARQ Built-In Functions

The following example inserts data about two books, and it displays the book titles in all uppercase characters and the length of each title string.

Example 7-29 SPARQL Query with ARQ Built-In Functions

import org.apache.jena.query.*;
import oracle.spatial.rdf.client.jena.*;
import org.apache.jena.update.*;

public class Test17_privnet
{
  public static void main(String[] args) throws Exception
  {
    String szJdbcURL = args[0];
    String szUser    = args[1];
    String szPasswd  = args[2];

    String szModelName = args[3];
    String szNetworkName = args[4];
    
    Oracle oracle = new Oracle(szJdbcURL, szUser, szPasswd);
    
    ModelOracleSem model = ModelOracleSem.createOracleSemModel(oracle, szModelName, szUser, szNetworkName);
    GraphOracleSem g = model.getGraph();
    String insertString =  
      " PREFIX dc: <http://purl.org/dc/elements/1.1/> "         + 
      " INSERT DATA "                                           +
      " { <http://example/book3> dc:title    \"A new book\" ; " +
      "                         dc:creator  \"A.N.Other\" . "   + 
      "   <http://example/book4> dc:title    \"Semantic Web Rocks\" ; " +
      "                         dc:creator  \"TB\" . "   + 
      " }   ";

    UpdateAction.parseExecute(insertString,  model);

    String queryString = "PREFIX  dc:   <http://purl.org/dc/elements/1.1/> " +
      " PREFIX  fn: <http://www.w3.org/2005/xpath-functions#> " + 
      " SELECT ?subject (fn:upper-case(?object) as ?object1) (fn:string-length(?object) as ?strlen) " + 
      "WHERE { ?subject dc:title ?object } " 
      ;

    Query query = QueryFactory.create(queryString, Syntax.syntaxARQ);
    QueryExecution qexec = QueryExecutionFactory.create(query, model);
    ResultSet results = qexec.execSelect();

    ResultSetFormatter.out(System.out, results, query);

    model.close();    
    OracleUtils.dropSemanticModel(oracle, szModelName, szUser, szNetworkName);
    oracle.dispose();
  }
}

The following are the commands to compile and run the preceding code along with the expected output of the java command.

javac -classpath ../jar/'*' Test17_privnet.java
java -classpath ./:../jar/'*'  Test17_privnet jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> M1 NET1
----------------------------------------------------------
| subject                | object1              | strlen |
==========================================================
| <http://example/book3> | "A NEW BOOK"         | 10     |
| <http://example/book4> | "SEMANTIC WEB ROCKS" | 18     |
----------------------------------------------------------

7.16.14 SELECT Cast Query

The following example "converts" two Fahrenheit temperatures (18.1 and 32.0) to Celsius temperatures.

Example 7-30 SELECT Cast Query

import org.apache.jena.query.*;
import oracle.spatial.rdf.client.jena.*;
import org.apache.jena.update.*;

public class Test18_privnet
{
  public static void main(String[] args) throws Exception
  {
    String szJdbcURL = args[0];
    String szUser    = args[1];
    String szPasswd  = args[2];

    String szModelName = args[3];
    String szNetworkName = args[4];
    
    Oracle oracle = new Oracle(szJdbcURL, szUser, szPasswd);
    
    ModelOracleSem model = ModelOracleSem.createOracleSemModel(oracle, szModelName, szUser, szNetworkName);
    GraphOracleSem g = model.getGraph();
    String insertString =  
      " PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " +
      " INSERT DATA "                                     +
      " { <u:Object1> <u:temp>    \"18.1\"^^xsd:float ; " +
      "               <u:name>    \"Foo... \" . "         + 
      "   <u:Object2> <u:temp>    \"32.0\"^^xsd:float ; " +
      "               <u:name>    \"Bar... \" . "         + 
      " }   ";

    UpdateAction.parseExecute(insertString,  model);

    String queryString = 
      " PREFIX  fn: <http://www.w3.org/2005/xpath-functions#> " + 
      " SELECT ?subject ((?temp - 32.0)*5/9 as ?celsius_temp) " +
      "WHERE { ?subject <u:temp> ?temp } " 
      ;

    Query query = QueryFactory.create(queryString, Syntax.syntaxARQ);
    QueryExecution qexec = QueryExecutionFactory.create(query, model);
    ResultSet results = qexec.execSelect();

    ResultSetFormatter.out(System.out, results, query);

    model.close();    
    OracleUtils.dropSemanticModel(oracle, szModelName, szUser, szNetworkName);
    oracle.dispose();
  }
}

The following are the commands to compile and run the preceding code along with the expected output of the java command.

javac -classpath ../jar/'*' Test18_privnet.java
java -classpath ./:../jar/'*'  Test18_privnet jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> M1 NET1
------------------------------------------------------------------------
| subject     | celsius_temp                                           |
========================================================================
| <u:Object1> | "-7.7222223"^^<http://www.w3.org/2001/XMLSchema#float> |
| <u:Object2> | "0.0"^^<http://www.w3.org/2001/XMLSchema#float>        |
------------------------------------------------------------------------

7.16.15 Instantiate Oracle Database Using OracleConnection

The following example shows a different way to instantiate an Oracle object using a given OracleConnection object. (In a J2EE Web application, users can normally get an OracleConnection object from a J2EE data source.)

Example 7-31 Instantiate Oracle Database Using OracleConnection

The following are the commands to compile and run the preceding code along with the expected output of the java command.

import org.apache.jena.query.*;
import org.apache.jena.graph.*;
import oracle.spatial.rdf.client.jena.*;
import oracle.jdbc.pool.*;
import oracle.jdbc.*;

public class Test19_privnet
{
  public static void main(String[] args) throws Exception
  {
    String szJdbcURL = args[0];
    String szUser    = args[1];
    String szPasswd  = args[2];

    String szModelName = args[3];
    String szNetworkName = args[4];

    OracleDataSource ds = new OracleDataSource();
    ds.setURL(szJdbcURL);
    ds.setUser(szUser);
    ds.setPassword(szPasswd);

    OracleConnection conn = (OracleConnection) ds.getConnection();
    Oracle oracle = new Oracle(conn);

    ModelOracleSem model = ModelOracleSem.createOracleSemModel(oracle, szModelName, szUser, szNetworkName);
    GraphOracleSem g = model.getGraph();

    g.add(Triple.create(
          NodeFactory.createURI("u:John"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Mary")));
    g.add(Triple.create(
          NodeFactory.createURI("u:John"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Jack")));
    g.add(Triple.create(
          NodeFactory.createURI("u:Mary"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Jill")));
        
    String queryString =
       " SELECT ?s ?o  WHERE { ?s <u:parentOf> ?o .} ";

    Query query = QueryFactory.create(queryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, model) ;

    ResultSet results = qexec.execSelect() ;
    ResultSetFormatter.out(System.out, results, query);
    qexec.close() ; 
    
    OracleUtils.dropSemanticModel(oracle, szModelName, szUser, szNetworkName);
    
    model.close();    
    oracle.dispose();
  }
}

The following are the commands to compile and run the preceding code along with the expected output of the java command.

javac -classpath ../jar/'*' Test19_privnet.java
java -classpath ./:../jar/'*'  Test19_privnet jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> M1 NET1
-----------------------
| s        | o        |
=======================
| <u:John> | <u:Mary> |
| <u:John> | <u:Jack> |
| <u:Mary> | <u:Jill> |
-----------------------

7.16.16 Oracle Database Connection Pooling

The following example uses Oracle Database connection pooling.

Example 7-32 Oracle Database Connection Pooling

The following are the commands to compile and run the preceding code along with the expected output of the java command.

import org.apache.jena.graph.*;
import oracle.spatial.rdf.client.jena.*;

public class Test20_privnet
{
  public static void main(String[] args) throws Exception
  {
    String szJdbcURL = args[0];
    String szUser    = args[1];
    String szPasswd  = args[2];

    String szModelName = args[3];
    String szNetworkName = args[4];

    // test with connection properties (taken from some example)
    java.util.Properties prop = new java.util.Properties();
    prop.setProperty("MinLimit", "2");     // the cache size is 2 at least 
    prop.setProperty("MaxLimit", "10");
    prop.setProperty("InitialLimit", "2"); // create 2 connections at startup
    prop.setProperty("InactivityTimeout", "1800");    //  seconds
    prop.setProperty("AbandonedConnectionTimeout", "900");  //  seconds
    prop.setProperty("MaxStatementsLimit", "10");
    prop.setProperty("PropertyCheckInterval", "60"); // seconds

    System.out.println("Creating OraclePool");
    OraclePool op = new OraclePool(szJdbcURL, szUser, szPasswd, prop, "OracleSemConnPool");
    System.out.println("Done creating OraclePool");

    // grab an Oracle and do something with it
    System.out.println("Getting an Oracle from OraclePool");
    Oracle oracle = op.getOracle();
    System.out.println("Done");
    System.out.println("Is logical connection:" +
        oracle.getConnection().isLogicalConnection());
    GraphOracleSem g = new GraphOracleSem(oracle, szModelName, szUser, szNetworkName);
    g.add(Triple.create(
          NodeFactory.createURI("u:John"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Mary")));
    g.close();
    // return the Oracle back to the pool
    oracle.dispose();
    
    // grab another Oracle and do something else 
    System.out.println("Getting an Oracle from OraclePool");
    oracle = op.getOracle();
    System.out.println("Done");
    System.out.println("Is logical connection:" +
        oracle.getConnection().isLogicalConnection());
    g = new GraphOracleSem(oracle, szModelName, szUser, szNetworkName);
    g.add(Triple.create(
          NodeFactory.createURI("u:John"), NodeFactory.createURI("u:parentOf"), NodeFactory.createURI("u:Jack")));
    g.close();
    
    OracleUtils.dropSemanticModel(oracle, szModelName, szUser, szNetworkName); 
    
    // return the Oracle back to the pool
    oracle.dispose();
  }
}

The following are the commands to compile and run the preceding code along with the expected output of the java command.

javac -classpath ../jar/'*' Test20_privnet.java
java -classpath ./:../jar/'*'  Test20_privnet jdbc:oracle:thin:@localhost:1521:orcl scott <password-for-scott> M1 NET1
Creating OraclePool
Done creating OraclePool
Getting an Oracle from OraclePool
Done
Is logical connection:true
Getting an Oracle from OraclePool
Done
Is logical connection:true