Java Code Examples for org.openrdf.query.TupleQuery

The following examples show how to use org.openrdf.query.TupleQuery. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Get total number of distinct objects for a predicate
 * @param pred Predicate
 * @param m model
 * @return triples
 */
public static long getDistinctSbj(String pred, String endpoint) throws Exception {
	String strQuery = "SELECT  (COUNT(DISTINCT ?s) AS ?subjs) " + // 
			"WHERE " +
			"{" +
       		"?s <" + pred + "> ?o " +
       		"} " ;
	SPARQLRepository repo = new SPARQLRepository(endpoint);
	repo.initialize();
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult rs = query.evaluate();
		return Long.parseLong(rs.next().getValue("subjs").stringValue());
	} finally {
		conn.close();
		repo.shutDown();
	}
}
 
Example 2
/**
 * Get total number of distinct subjects of a dataset
 * @return count 
 */
public static long getSubjectCount(String endpoint) throws Exception {
	String strQuery = "SELECT  (COUNT(DISTINCT ?s) AS ?sbjts) " + // 
			"WHERE " +
			"{" +
       		"?s ?p ?o " +
       		"} " ;
	SPARQLRepository repo = new SPARQLRepository(endpoint);
	repo.initialize();
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult rs = query.evaluate();
		return Long.parseLong(rs.next().getValue("sbjts").stringValue());
	} finally {
		conn.close();
		repo.shutDown();
	}
}
 
Example 3
/**
 * Get total number of distinct objects of a dataset
 * @return count
 */
public static long getObjectCount(String endpoint) throws Exception {
	String strQuery = "SELECT  (COUNT(DISTINCT ?o) AS ?objts) " + // 
			"WHERE " +
			"{" +
       		"?s ?p ?o " +
       		"} " ;
	SPARQLRepository repo = new SPARQLRepository(endpoint);
	repo.initialize();
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult rs = query.evaluate();
		return Long.parseLong(rs.next().getValue("objts").stringValue());
	} finally {
		conn.close();
		repo.shutDown();
	}
}
 
Example 4
/**
 * Get total number of triple for a predicate
 * @param pred Predicate
 * @param m model
 * @return triples
 */
public static Long getTripleCount(String pred, String endpoint) throws Exception {
	String strQuery = "SELECT  (COUNT(?s) AS ?triples) " + // 
			"WHERE " +
			"{" +
       		"?s <"+pred+"> ?o " +
       		"} " ;
	SPARQLRepository repo = new SPARQLRepository(endpoint);
	repo.initialize();
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult rs = query.evaluate();
		return Long.parseLong(rs.next().getValue("triples").stringValue());
	} finally {
		conn.close();
		repo.shutDown();
	}
}
 
Example 5
/**
 * Get Predicate List
 * @param endPointUrl SPARQL endPoint Url
 * @param graph Named graph
 * @return  predLst Predicates List
 */
private static List<String> getPredicates(String endPointUrl, String graph) throws Exception
{
	List<String>  predLst = new ArrayList<String>();
	String strQuery = getPredQuery(graph);
	SPARQLRepository repo = new SPARQLRepository(endPointUrl);
	repo.initialize();
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult res = query.evaluate();
		while (res.hasNext()) 
		{
			String pred = res.next().getValue("p").toString();
			predLst.add(pred);	  		
		}
	} finally {
		conn.close();
		repo.shutDown();
	}
	return predLst;
}
 
Example 6
public static TupleQueryResult executeSelectQuery(final Repository repo, final String query,
		final QueryLanguage ql) throws OpenRDFException  {

	RepositoryConnection cxn;
	if (repo instanceof BigdataSailRepository) {
		cxn = ((BigdataSailRepository) repo).getReadOnlyConnection();
	} else {
		cxn = repo.getConnection();
	}

	try {

		final TupleQuery tupleQuery = cxn.prepareTupleQuery(ql, query);
		tupleQuery.setIncludeInferred(true /* includeInferred */);
		return tupleQuery.evaluate();
		
	} finally {
		// close the repository connection
		cxn.close();
	}
}
 
Example 7
Source Project: trainbenchmark   Source File: SesameDriver.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public Collection<? extends SesameMatch> runQuery(final RailwayQuery query, final String queryDefinition)
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	final Collection<SesameMatch> results = new ArrayList<>();

	final TupleQuery tupleQuery = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryDefinition);
	final TupleQueryResult queryResults = tupleQuery.evaluate();
	try {
		while (queryResults.hasNext()) {
			final BindingSet bs = queryResults.next();
			final SesameMatch match = SesameMatch.createMatch(query, bs);
			results.add(match);
		}
	} finally {
		queryResults.close();
	}

	return results;
}
 
Example 8
Source Project: anno4j   Source File: RDFSContainer.java    License: Apache License 2.0 6 votes vote down vote up
private TupleQuery createBlockQuery(int b) throws RepositoryException {
	StringBuilder sb = new StringBuilder();
	sb.append("SELECT ?pred ?value ?value_class\n");
	sb.append("WHERE { $self ?pred ?value\n");
	sb.append("OPTIONAL { ?value a ?value_class }\n");
	sb.append("FILTER (");
	for (int i = b * BSIZE, n = b * BSIZE + BSIZE; i < n; i++) {
		sb.append("?pred = <");
		sb.append(RDF.NAMESPACE);
		sb.append("_");
		sb.append((i + 1));
		sb.append(">");
		if (i + 1 < n) {
			sb.append(" || ");
		}
	}
	sb.append(")}\n");
	ObjectConnection con = getObjectConnection();
	try {
		TupleQuery query = con.prepareTupleQuery(SPARQL, sb.toString());
		query.setBinding("self", getResource());
		return query;
	} catch (MalformedQueryException e) {
		throw new RepositoryException(e);
	}
}
 
Example 9
Source Project: anno4j   Source File: ObjectQueryFactory.java    License: Apache License 2.0 6 votes vote down vote up
public ObjectQuery createQuery(PropertySetFactory factory)
		throws RepositoryException {
	synchronized (queries) {
		ObjectQuery query = queries.remove(factory);
		if (query != null)
			return query;
	}
	Class<?> type = factory.getPropertyType();
	Map<String, String> properties = mapper.findEagerProperties(type);
	if (properties == null)
		return null;
	// TODO this should be a static string
	String sparql = buildQuery(properties, factory);
	try {
		TupleQuery tuples = connection.prepareTupleQuery(SPARQL, sparql);
		return new ObjectQuery(connection, tuples);
	} catch (MalformedQueryException e) {
		throw new RepositoryException(e);
	}
}
 
Example 10
Source Project: anno4j   Source File: FieldPredicateTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testReadAccess() throws Exception {
	ValueFactory vf = con.getValueFactory();
	URI graph = vf.createURI("urn:test:graph");
	con.setAddContexts(graph);
	Company c = new Company();
	c = (Company) con.getObject(con.addObject(c));
	c.setName("My Company");
	assertEquals("My Company", c.getName());
	TupleQuery query = con.prepareTupleQuery("SELECT ?g WHERE {GRAPH ?g {?o <urn:test:name> ?name}}");
	query.setBinding("name", vf.createLiteral("My Company"));
	TupleQueryResult results = query.evaluate();
	Value g = results.next().getValue("g");
	results.close();
	assertEquals(graph, g);
	con.setAddContexts();
	assertEquals("My Company", c.getName());
	query = con.prepareTupleQuery("SELECT ?g WHERE {GRAPH ?g {?o <urn:test:name> ?name}}");
	query.setBinding("name", vf.createLiteral("My Company"));
	results = query.evaluate();
	g = results.next().getValue("g");
	results.close();
	assertEquals(graph, g);
}
 
Example 11
Source Project: database   Source File: Test_Ticket_789.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void test_ticket_1326_dataset() throws Exception {
	populate();
	
	BigdataSailRemoteRepository sailRepo = m_repo.getBigdataSailRemoteRepository();
	BigdataSailRemoteRepositoryConnection con = sailRepo.getConnection();
	final TupleQuery tq = con.prepareTupleQuery(QueryLanguage.SPARQL, "select * where {?s ?p ?o}");

	final DatasetImpl dataset = new DatasetImpl();
	dataset.addDefaultGraph(defaultGraph1);

	tq.setDataset(dataset);
	{
		TupleQueryResult tqr = tq.evaluate();
		try {
			int count = 0;
			while (tqr.hasNext()) {
				tqr.next();
				count++;
			}
			// there is only 1 statement in defaultGraph1 
			assertEquals(1, count);
		} finally {
			tqr.close();
		}
	}
}
 
Example 12
Source Project: database   Source File: Concurrency.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Issue the query.
 * 
 * @throws Exception
 */
private void doQuery() throws Exception {
   
    RepositoryConnection cxn = repo.getReadOnlyConnection();
    try {

        final TupleQuery tupleQuery = 
            cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);
        tupleQuery.setIncludeInferred(true /* includeInferred */);
        TupleQueryResult result = tupleQuery.evaluate();
        // do something with the results
        int resultCount = 0;
        while (result.hasNext()) {
            BindingSet bindingSet = result.next();
            // log.info(bindingSet);
            resultCount++;
        }
        log.info(resultCount + " results");
        
    } finally {
        // close the repository connection
        cxn.close();
    }
        
}
 
Example 13
Source Project: database   Source File: LoadPdb.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void executeSelectQuery(Repository repo, String query) throws Exception {

		RepositoryConnection cxn = repo.getConnection();
		int counter = 0;
		try {

			final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);
			tupleQuery.setIncludeInferred(true /* includeInferred */);
			TupleQueryResult result = tupleQuery.evaluate();
			// do something with the results
			while (result.hasNext()) {
				BindingSet bindingSet = result.next();
				LOG.info(bindingSet);
				counter++;
			}

		} finally {
			// close the repository connection
			cxn.close();
//			LOG.info
            System.err.println
            ("Number of results: " + counter);
		}

	}
 
Example 14
@Before
public void before()
		throws RepositoryException, IOException, RDFParseException,
		       MalformedQueryException, QueryResultParseException,
			   QueryResultHandlerException {
	repo = new SailRepository(new MemoryStore());
	repo.initialize();
	conn = repo.getConnection();
	vf = conn.getValueFactory();
	conn.add(getResource(data), "file://", RDFFormat.TURTLE);
	SPARQLResultsXMLParserFactory factory =
			new SPARQLResultsXMLParserFactory();
	parser = factory.getParser();
	parser.setValueFactory(vf);
	List<Rule> rules;
	rules = Rules.fromOntology(getResource(data));
	QueryRewriter rewriter = new QueryRewriter(conn, rules);
	query = (TupleQuery) rewriter.rewrite(QueryLanguage.SPARQL, queryString);
	nonInfQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
	System.out.println("== QUERY (" + this.name + ") ==");
	System.out.println(nonInfQuery);
	System.out.println("== REWRITTEN QUERY (" + this.name + ") ==");
	System.out.println(query);
}
 
Example 15
Source Project: database   Source File: TestTicket1755.java    License: GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
	private void testQuery(final BigdataSailRepositoryConnection conn,
			final String query, final int expectedIVs) throws MalformedQueryException, RepositoryException, QueryEvaluationException {
		TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
		TupleQueryResult tqr = tq.evaluate();
		try {
			int cnt = 0;
			while (tqr.hasNext()) {
				tqr.next();
				cnt++;
			}
//			assertEquals("Expected 1 row in resultset", 1, cnt);
			QueryRoot queryRoot = ((BigdataSailTupleQuery)tq).getASTContainer().getOriginalAST();
			cnt = 0;
			for (Object filterNode: queryRoot.getWhereClause().getChildren(FilterNode.class)) {
				cnt += checkNode((BOp)filterNode);
			}
			assertEquals("Expected inlined IV for date literal", expectedIVs, cnt);
		} finally {
			tqr.close();
		}
	}
 
Example 16
Source Project: database   Source File: TestTicket4249.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final RepositoryConnection conn, final Literal string, final int start, final Literal expected)
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	final ValueFactory vf = conn.getValueFactory();
	final String query = "select ?substring WHERE { BIND ( SUBSTR(?string, ?start) as ?substring ) . }";
	final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
	q.setBinding("string", string);
	q.setBinding("start", vf.createLiteral(start));
	final TupleQueryResult tqr = q.evaluate();
	try {
		while (tqr.hasNext()) {
			final BindingSet bindings = tqr.next();
			// assert expected value
			assertEquals(expected, bindings.getBinding("substring").getValue());
		}
	} finally {
		tqr.close();
	}
}
 
Example 17
Source Project: database   Source File: TestTicket632.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final URI serviceUri, final SailRepository repo) throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFParseException, IOException, RDFHandlerException {
    try {
        repo.initialize();
        final RepositoryConnection conn = repo.getConnection();
        final ValueFactory vf = conn.getValueFactory();
        conn.setAutoCommit(false);
        try {
            final String query = "SELECT ?x { SERVICE <" + serviceUri.stringValue() + "> { ?x <u:1> ?bool1 } }";
            final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
            q.setBinding("bool1", vf.createLiteral(true));
            final TupleQueryResult tqr = q.evaluate();
            try {
                tqr.hasNext();
            } finally {
                tqr.close();
            }
        } finally {
            conn.close();
        }
    } finally {
        repo.shutDown();
    }
}
 
Example 18
@Test
public void testInComparison3()
	throws Exception
{
	loadTestData("/testdata-query/dataset-ses1913.trig");
	StringBuilder query = new StringBuilder();
	query.append(" PREFIX : <http://example.org/>\n");
	query.append(" SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1, 1/0)) } ");

	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString());

	TupleQueryResult result = tq.evaluate();
	assertNotNull(result);
	assertTrue(result.hasNext());

	BindingSet bs = result.next();
	Value y = bs.getValue("y");
	assertNotNull(y);
	assertTrue(y instanceof Literal);
	assertEquals(f.createLiteral("1", XMLSchema.INTEGER), y);
}
 
Example 19
@Test
public void testSES1991STRUUIDEvaluation()
	throws Exception
{
	loadTestData("/testdata-query/defaultgraph.ttl");
	String query = "SELECT ?uid WHERE {?s ?p ?o . BIND(STRUUID() as ?uid) } LIMIT 2";

	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);

	try {
		TupleQueryResult result = tq.evaluate();
		assertNotNull(result);

		Literal uid1 = (Literal)result.next().getValue("uid");
		Literal uid2 = (Literal)result.next().getValue("uid");

		assertNotNull(uid1);
		assertFalse(uid1.equals(uid2));

		result.close();
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example 20
Source Project: database   Source File: SPARQLQueryTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected static String getManifestName(Repository manifestRep, RepositoryConnection con,
		String manifestFileURL)
	throws QueryEvaluationException, RepositoryException, MalformedQueryException
{
	// Try to extract suite name from manifest file
	TupleQuery manifestNameQuery = con.prepareTupleQuery(QueryLanguage.SERQL,
			"SELECT ManifestName FROM {ManifestURL} rdfs:label {ManifestName}");
	manifestNameQuery.setBinding("ManifestURL", manifestRep.getValueFactory().createURI(manifestFileURL));
	TupleQueryResult manifestNames = manifestNameQuery.evaluate();
	try {
		if (manifestNames.hasNext()) {
			return manifestNames.next().getValue("ManifestName").stringValue();
		}
	}
	finally {
		manifestNames.close();
	}

	// Derive name from manifest URL
	int lastSlashIdx = manifestFileURL.lastIndexOf('/');
	int secLastSlashIdx = manifestFileURL.lastIndexOf('/', lastSlashIdx - 1);
	return manifestFileURL.substring(secLastSlashIdx + 1, lastSlashIdx);
}
 
Example 21
@Test
public void testOptionalFilter()
	throws Exception
{
	String optional = "{ ?s :p1 ?v1 OPTIONAL {?s :p2 ?v2 FILTER(?v1<3) } }";
	URI s = vf.createURI("urn:test:s");
	URI p1 = vf.createURI(URN_TEST_P1);
	URI p2 = vf.createURI(URN_TEST_P2);
	Value v1 = vf.createLiteral(1);
	Value v2 = vf.createLiteral(2);
	Value v3 = vf.createLiteral(3);
	testCon.add(s, p1, v1);
	testCon.add(s, p2, v2);
	testCon.add(s, p1, v3);
	String qry = "PREFIX :<urn:test:> SELECT ?s ?v1 ?v2 WHERE " + optional;
	TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SPARQL, qry);
	TupleQueryResult result = query.evaluate();
	Set<List<Value>> set = new HashSet<List<Value>>();
	while (result.hasNext()) {
		BindingSet bindings = result.next();
		set.add(Arrays.asList(bindings.getValue("v1"), bindings.getValue("v2")));
	}
	result.close();
	assertThat(set, hasItem(Arrays.asList(v1, v2)));
	assertThat(set, hasItem(Arrays.asList(v3, null)));
}
 
Example 22
@Test
public void testOrPredicate()
	throws Exception
{
	String union = "{ :s ?p :o FILTER (?p = :p1 || ?p = :p2) }";
	URI s = vf.createURI("urn:test:s");
	URI p1 = vf.createURI(URN_TEST_P1);
	URI p2 = vf.createURI(URN_TEST_P2);
	URI o = vf.createURI("urn:test:o");
	testCon.add(s, p1, o);
	testCon.add(s, p2, o);
	String qry = "PREFIX :<urn:test:> SELECT ?p WHERE " + union;
	TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SPARQL, qry);
	TupleQueryResult result = query.evaluate();
	List<Value> list = new ArrayList<Value>();
	while (result.hasNext()) {
		BindingSet bindings = result.next();
		list.add(bindings.getValue("p"));
	}
	result.close();
	assertThat(list, hasItem(p1));
	assertThat(list, hasItem(p2));
}
 
Example 23
private int size(URI defaultGraph)
	throws RepositoryException, MalformedQueryException, QueryEvaluationException
{
	TupleQuery qry = testCon.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { ?s ?p ?o }");
	DatasetImpl dataset = new DatasetImpl();
	dataset.addDefaultGraph(defaultGraph);
	qry.setDataset(dataset);
	TupleQueryResult result = qry.evaluate();
	try {
		int count = 0;
		while (result.hasNext()) {
			result.next();
			count++;
		}
		return count;
	}
	finally {
		result.close();
	}
}
 
Example 24
Source Project: database   Source File: TestTicket967.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void addDuringQueryExec(final RepositoryConnection conn,
	final Resource subj, final URI pred, final Value obj,
	final Resource... ctx) throws RepositoryException,
	MalformedQueryException, QueryEvaluationException {
final TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL,
      		"select distinct ?s ?p ?o where{?s ?p ?t . ?t <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?o }"
      		);
      tq.setBinding("s", subj);
      tq.setBinding("p", pred);
      tq.setBinding("o", obj);
      final TupleQueryResult tqr = tq.evaluate();
      try {
          if (!tqr.hasNext()) {
              conn.add(subj, pred, obj, ctx);
          }
      } finally {
          tqr.close();
      }
  }
 
Example 25
@Override
  protected void doInsertWithBodyTest(final String method, final int ntriples,
          /*final String servlet,*/ final RDFFormat format) throws Exception {

      final Graph g = genNTRIPLES2(ntriples);
      cxn.add(g);
      assertEquals(ntriples, getExactSize());
      
// Verify the expected #of statements in the store.
{
	final String queryStr = "select * where {?s ?p ?o}";
	final TupleQuery query = cxn.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
	assertEquals(ntriples, countResults(query.evaluate()));
}

  }
 
Example 26
public void test_INSERT_triples_with_BODY_and_defaultContext()
        throws Exception {

    if(TestMode.quads != getTestMode())
        return;

    final String resource = packagePath
            + "insert_triples_with_defaultContext.ttl";

    final Graph g = loadGraphFromResource(resource);

    // Load the resource into the KB.
    doInsertByBody("POST", RDFFormat.TURTLE, g, new URIImpl(
            "http://example.org"));
    
    // Verify that the data were inserted into the appropriate context.
    {
    	final String queryStr = "select * { GRAPH <http://example.org> {?s ?p ?p} }";
    	final TupleQuery query = cxn.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
		assertEquals(7, countResults(query.evaluate()));
    }

}
 
Example 27
Source Project: database   Source File: Test_Ticket_1717.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test supposed to check if constants in BIND expressions will be resolved
 */
public void test_ticket_1717() throws Exception {

   {
     // Clear DB per task description (Executing the query over the empty database)
     m_repo.remove(new RemoveOp(null, null, null));
     String query = "SELECT ?z ?s1 {  ?s ?p ?o .   BIND(?o+1 AS ?z)  BIND(?z+1 AS ?z2) }";
     final TupleQuery tq = m_repo.getBigdataSailRemoteRepository().getConnection().prepareTupleQuery(QueryLanguage.SPARQL, query, null);
       final TupleQueryResult tqr = tq.evaluate();
       try {
           int count = 0;
           while (tqr.hasNext()) {
               System.out.println(tqr.next());
               count++;
            }
           assertEquals(0,count); // asserting successful execution of the query, as it was failing while parsing
       } finally {
            tqr.close();
       }
   }
}
 
Example 28
public List<List<Object>> evaluate(String queries) throws Exception {
	List<List<Object>> report = new ArrayList<List<Object>>();
			
	List<String> qnames = Arrays.asList(queries.split(" "));
	for (String curQueryName : qnames)
	{
		List<Object> reportRow = new ArrayList<Object>();
		report.add(reportRow);
		String curQuery = qp.getQuery(curQueryName);
		reportRow.add(curQueryName);
		
		long startTime = System.currentTimeMillis();
		//ParsedOperation pO = QueryParserUtil.parseOperation(QueryLanguage.SPARQL, curQuery, null);
		RepositoryConnection repCon = this.repository.getConnection();
		try {
			Query tempq = repCon.prepareQuery(QueryLanguage.SPARQL, curQuery);
			TupleQuery q = (TupleQuery)tempq;
			
			SyncTupleQueryResultHandler rhandler = new SyncTupleQueryResultHandler();
            q.evaluate(rhandler);
            		
		    long runTime = System.currentTimeMillis() - startTime;
		    reportRow.add((Long)rhandler.resultCount); reportRow.add((Long)runTime);

		    log.info(curQueryName + ": Query exection time (msec): "+ runTime + ", Total Number of Records: " + rhandler.resultCount);
		} catch (Exception e) {
			reportRow.add(null); reportRow.add(null);
		} finally {
			repCon.close();
        }
	}
	return report;
}
 
Example 29
Source Project: anno4j   Source File: ObjectQueryTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testTupleQueryBinding() throws Exception {
	Person jamie = con.addDesignation(con.getObjectFactory().createObject(),
			Person.class);
	jamie.getFoafNames().add("Jamie");
	jamie.getFoafFamily_names().add("Leigh");
	String q = PREFIX + "Select ?name where { ?person foaf:name ?name }";
	TupleQuery query = con.prepareTupleQuery(q);
	query.setBinding("person", ((RDFObject)jamie).getResource());
	TupleQueryResult result = query.evaluate();
	assertTrue(result.hasNext());
	assertEquals("Jamie", result.next().getValue("name").stringValue());
	result.close();
}
 
Example 30
Source Project: database   Source File: SampleCode.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Execute a "select" query.
 * 
 * @param repo
 * @param query
 * @param ql
 * @throws Exception
 */
public void executeSelectQuery(Repository repo, String query, 
    QueryLanguage ql) throws Exception {
    
    /*
     * With MVCC, you read from a historical state to avoid blocking and
     * being blocked by writers.  BigdataSailRepository.getQueryConnection
     * gives you a view of the repository at the last commit point.
     */
    RepositoryConnection cxn;
    if (repo instanceof BigdataSailRepository) { 
        cxn = ((BigdataSailRepository) repo).getReadOnlyConnection();
    } else {
        cxn = repo.getConnection();
    }
    
    try {

        final TupleQuery tupleQuery = cxn.prepareTupleQuery(ql, query);
        tupleQuery.setIncludeInferred(true /* includeInferred */);
        TupleQueryResult result = tupleQuery.evaluate();
        // do something with the results
        while (result.hasNext()) {
            BindingSet bindingSet = result.next();
            log.info(bindingSet);
        }
        
    } finally {
        // close the repository connection
        cxn.close();
    }
    
}