Java Code Examples for org.eclipse.rdf4j.query.TupleQuery#evaluate()

The following examples show how to use org.eclipse.rdf4j.query.TupleQuery#evaluate() . 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
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSES2373SubselectOptional() throws Exception {
	conn.prepareUpdate(QueryLanguage.SPARQL,
			"insert data {" + "<u:1> <u:r> <u:subject> ." + "<u:1> <u:v> 1 ." + "<u:1> <u:x> <u:x1> ."
					+ "<u:2> <u:r> <u:subject> ." + "<u:2> <u:v> 2 ." + "<u:2> <u:x> <u:x2> ."
					+ "<u:3> <u:r> <u:subject> ." + "<u:3> <u:v> 3 ." + "<u:3> <u:x> <u:x3> ."
					+ "<u:4> <u:r> <u:subject> ." + "<u:4> <u:v> 4 ." + "<u:4> <u:x> <u:x4> ."
					+ "<u:5> <u:r> <u:subject> ." + "<u:5> <u:v> 5 ." + "<u:5> <u:x> <u:x5> ." + "}")
			.execute();

	StringBuilder qb = new StringBuilder();
	qb.append("select ?x { \n");
	qb.append(" { select ?v { ?v <u:r> <u:subject> filter (?v = <u:1>) } }.\n");
	qb.append("  optional {  select ?val { ?v <u:v> ?val .} }\n");
	qb.append("  ?v <u:x> ?x \n");
	qb.append("}\n");

	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb.toString());
	try (TupleQueryResult result = tq.evaluate();) {
		assertTrue("The query should return a result", result.hasNext());
		BindingSet b = result.next();
		assertTrue("?x is from the mandatory part of the query and should be bound", b.hasBinding("x"));
	}
}
 
Example 2
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSES1685propPathSameVar() throws Exception {
	final String queryStr = "PREFIX : <urn:> SELECT ?x WHERE {?x :p+ ?x}";

	conn.add(new StringReader("@prefix : <urn:> . :a :p :b . :b :p :a ."), "", RDFFormat.TURTLE);

	TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
	try (TupleQueryResult result = query.evaluate();) {
		assertNotNull(result);

		int count = 0;
		while (result.hasNext()) {
			result.next();
			count++;
		}
		// result should be both a and b.
		assertEquals(2, count);
	}
}
 
Example 3
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSES2250BindErrors() throws Exception {
	StringBuilder ub = new StringBuilder();
	ub.append("insert data { <urn:test:subj> <urn:test:pred> _:blank }");

	conn.prepareUpdate(QueryLanguage.SPARQL, ub.toString()).execute();

	StringBuilder qb = new StringBuilder();
	qb.append("SELECT * {\n" + "    ?s1 ?p1 ?blank . " + "    FILTER(isBlank(?blank))"
			+ "    BIND (iri(?blank) as ?biri)" + "    ?biri ?p2 ?o2 ." + "}");

	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb.toString());
	try (TupleQueryResult evaluate = tq.evaluate();) {
		assertFalse("The query should not return a result", evaluate.hasNext());
	}
}
 
Example 4
Source File: AbstractGenericLuceneTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testUnionQuery() throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	String queryStr = "";
	queryStr += "PREFIX search: <http://www.openrdf.org/contrib/lucenesail#> ";
	queryStr += "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> ";
	queryStr += "SELECT DISTINCT ?result { ";
	queryStr += "{ ?result search:matches ?match1 . ";
	queryStr += "  ?match1 search:query 'one' ; ";
	queryStr += "          search:property <urn:predicate1> . }";
	queryStr += " UNION ";
	queryStr += "{ ?result search:matches ?match2 . ";
	queryStr += "  ?match2 search:query 'one' ; ";
	queryStr += "          search:property <urn:predicate2> . } ";
	queryStr += "} ";

	// fire a query with the subject pre-specified
	TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
	try (TupleQueryResult result = query.evaluate()) {
		while (result.hasNext()) {
			System.out.println(result.next());
		}
	}
}
 
Example 5
Source File: SpifSailTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void runTests() throws Exception {
	loadRDF("/schema/owl.ttl");
	loadRDF("/schema/spif.ttl");
	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, "prefix spin: <http://spinrdf.org/spin#> "
			+ "prefix spl: <http://spinrdf.org/spl#> "
			+ "select ?testCase ?expected ?actual where {?testCase a spl:TestCase. ?testCase spl:testResult ?expected. ?testCase spl:testExpression ?expr. "
			+ "BIND(spin:eval(?expr) as ?actual) " + "FILTER(?expected != ?actual) "
			+ "FILTER(strstarts(str(?testCase), 'http://spinrdf.org/spif#'))}");
	try ( // returns failed tests
			TupleQueryResult tqr = tq.evaluate()) {
		while (tqr.hasNext()) {
			BindingSet bs = tqr.next();
			Value testCase = bs.getValue("testCase");
			Value expected = bs.getValue("expected");
			Value actual = bs.getValue("actual");
			assertEquals(testCase.stringValue(), expected, actual);
		}
	}
}
 
Example 6
Source File: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
public void testPOPredRange() throws Exception {
    RepositoryConnection conn = repository.getConnection();
    IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc1");
    IRI loadPerc2 = VF.createIRI(litdupsNS, "loadPerc2");
    IRI loadPerc3 = VF.createIRI(litdupsNS, "loadPerc3");
    IRI loadPerc4 = VF.createIRI(litdupsNS, "loadPerc4");
    Literal six = VF.createLiteral("6");
    Literal sev = VF.createLiteral("7");
    Literal ten = VF.createLiteral("10");
    conn.add(cpu, loadPerc, six);
    conn.add(cpu, loadPerc2, sev);
    conn.add(cpu, loadPerc4, ten);
    conn.commit();

    String query = "PREFIX org.apache: <" + NAMESPACE + ">\n" +
            "select * where {" +
            "?x ?p ?o.\n" +
            "FILTER(org.apache:range(?p, <" + loadPerc.stringValue() + ">, <" + loadPerc3.stringValue() + ">))." +
            "}";
    TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
    CountTupleHandler cth = new CountTupleHandler();
    tupleQuery.evaluate(cth);
    conn.close();
    assertEquals(cth.getCount(), 2);
}
 
Example 7
Source File: SPARQLUpdateConformanceTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 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().createIRI(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 8
Source File: SpifSailTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testConcat() throws Exception {
	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL,
			"prefix apf: <http://jena.hpl.hp.com/ARQ/property#>\n" + "\n" + "select ?text where {\n"
					+ "   ?text apf:concat (\"very\" \"sour\" \"berry\") . }");
	TupleQueryResult tqresult = tq.evaluate();

	Assert.assertEquals("verysourberry", tqresult.next().getValue("text").stringValue());
}
 
Example 9
Source File: TupleQueryResultTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testNotClosingResult() {
	ValueFactory vf = con.getValueFactory();
	int subjectIndex = 0;
	int predicateIndex = 100;
	int objectIndex = 1000;
	int testStatementCount = 1000;
	int count = 0;
	con.begin();
	while (count < testStatementCount) {
		con.add(vf.createIRI("urn:test:" + subjectIndex), vf.createIRI("urn:test:" + predicateIndex),
				vf.createIRI("urn:test:" + objectIndex));
		if (Math.round(Math.random()) > 0) {
			subjectIndex++;
		}
		if (Math.round(Math.random()) > 0) {
			predicateIndex++;
		}
		if (Math.round(Math.random()) > 0) {
			objectIndex++;
		}
		count++;
	}
	con.commit();

	logger.info("Open lots of TupleQueryResults without closing them");
	for (int i = 0; i < 100; i++) {
		try (RepositoryConnection repCon = rep.getConnection()) {
			String queryString = "select * where {?s ?p ?o}";
			TupleQuery tupleQuery = repCon.prepareTupleQuery(QueryLanguage.SPARQL, queryString);

			// see if open results hangs test
			try (TupleQueryResult result = tupleQuery.evaluate()) {
			}
		}
	}
}
 
Example 10
Source File: PCJOptionalTestIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testEvaluateSingeIndexExactMatch()
        throws TupleQueryResultHandlerException, QueryEvaluationException,
        MalformedQueryException, RepositoryException, AccumuloException,
        AccumuloSecurityException, TableExistsException, RyaDAOException,
        SailException, TableNotFoundException, PcjException, InferenceEngineException {

    final String indexSparqlString = ""//
            + "SELECT ?e ?c ?l ?o" //
            + "{" //
            + "  ?e a ?c . "//
            + "  ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l "//
            + "  OPTIONAL{?e <uri:talksTo> ?o } . "//
            + "}";//

    PcjIntegrationTestingUtil.createAndPopulatePcj(conn, accCon, tablePrefix
            + "INDEX_1", indexSparqlString, new String[] { "e", "c", "l", "o" },
            Optional.absent());
    final String queryString = ""//
            + "SELECT ?e ?c ?l ?o " //
            + "{" //
            + "  ?e a ?c . "//
            + "  ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l . "//
            + "  OPTIONAL {?e <uri:talksTo> ?o } . "//
            + "}";//
    final CountingResultHandler crh = new CountingResultHandler();
    PcjIntegrationTestingUtil.deleteCoreRyaTables(accCon, tablePrefix);
    PcjIntegrationTestingUtil.closeAndShutdown(conn, repo);
    final TupleQuery tupQuery = pcjConn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
    tupQuery.evaluate(crh);

    Assert.assertEquals(3, crh.getCount());

}
 
Example 11
Source File: RepositoryConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSES713() throws Exception {
	String queryString = "SELECT * { ?sub ?pred ?obj . FILTER ( 'not a number' + 1 = ?obj )}";

	TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
	try (TupleQueryResult tqr = query.evaluate();) {
		assertFalse("Query should not return any results", tqr.hasNext());
	}
}
 
Example 12
Source File: RyaDirectExample.java    From rya with Apache License 2.0 5 votes vote down vote up
private static void testDeleteTemporalData(
		final SailRepositoryConnection conn) throws Exception {
	// Delete all stored dates
	final String sparqlDelete = "PREFIX time: <http://www.w3.org/2006/time#>\n"
			+ "PREFIX tempo: <tag:rya-rdf.org,2015:temporal#> \n"//
			+ "DELETE {\n" //
			+ "  ?event time:inXSDDateTime ?time . \n"
			+ "}\n"
			+ "WHERE { \n" + "  ?event time:inXSDDateTime ?time . \n"//
			+ "}";//

	final Update deleteUpdate = conn.prepareUpdate(QueryLanguage.SPARQL,
			sparqlDelete);
	deleteUpdate.execute();

	// Find all stored dates.
	final String queryString = "PREFIX time: <http://www.w3.org/2006/time#> \n"//
			+ "PREFIX tempo: <tag:rya-rdf.org,2015:temporal#> \n"//
			+ "SELECT ?event ?time \n" //
			+ "WHERE { \n"
			+ "  ?event time:inXSDDateTime ?time . \n"//
			+ "  FILTER(tempo:after(?time, '2001-01-01T01:01:03-08:00') ) \n"// after
																				// 3
																				// seconds
			+ "}";//

	final CountingResultHandler tupleHandler = new CountingResultHandler();
	final TupleQuery tupleQuery = conn.prepareTupleQuery(
			QueryLanguage.SPARQL, queryString);
	tupleQuery.evaluate(tupleHandler);
	log.info("Result count : " + tupleHandler.getCount());
	Validate.isTrue(tupleHandler.getCount() == 0);
}
 
Example 13
Source File: CascadeValueExceptionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testValueExceptionLessThanTyped() throws Exception {
	TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStrAltLT);
	try (TupleQueryResult evaluate = query.evaluate()) {
		assertFalse(evaluate.hasNext());
	}
}
 
Example 14
Source File: TripleSourceBase.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public CloseableIteration<BindingSet, QueryEvaluationException> getStatements(
		String preparedQuery, RepositoryConnection conn, QueryType queryType)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException
{
	switch (queryType)
	{
	case SELECT:
		monitorRemoteRequest();
		TupleQuery tQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, preparedQuery);
		disableInference(tQuery);
		return tQuery.evaluate();
	case CONSTRUCT:
		monitorRemoteRequest();
		GraphQuery gQuery = conn.prepareGraphQuery(QueryLanguage.SPARQL, preparedQuery);
		disableInference(gQuery);
		return new GraphToBindingSetConversionIteration(gQuery.evaluate());
	case ASK:
		monitorRemoteRequest();
		BooleanQuery bQuery = conn.prepareBooleanQuery(QueryLanguage.SPARQL, preparedQuery);
		disableInference(bQuery);
		return booleanToBindingSetIteration(bQuery.evaluate());
	default:
		throw new UnsupportedOperationException(
				"Operation not supported for query type " + queryType);
	}
}
 
Example 15
Source File: Demo3.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

		List<Endpoint> endpoints = new ArrayList<>();
		endpoints.add(EndpointFactory.loadSPARQLEndpoint("http://dbpedia", "http://dbpedia.org/sparql"));
		endpoints.add(EndpointFactory.loadSPARQLEndpoint("http://swdf", "http://data.semanticweb.org/sparql"));

		FedXRepository repo = FedXFactory.createFederation(endpoints);
		repo.init();

		String q = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
				+ "PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>\n"
				+ "SELECT ?President ?Party WHERE {\n"
				+ "?President rdf:type dbpedia-owl:President .\n"
				+ "?President dbpedia-owl:party ?Party . }";

		TupleQuery query = repo.getQueryManager().prepareTupleQuery(q);
		try (TupleQueryResult res = query.evaluate()) {

			while (res.hasNext()) {
				System.out.println(res.next());
			}
		}

		repo.shutDown();
		System.out.println("Done.");
		System.exit(0);

	}
 
Example 16
Source File: HalyardBulkLoadTest.java    From Halyard with Apache License 2.0 5 votes vote down vote up
private void assertCount(SailRepository rep, String query, int count) {
    TupleQuery q = rep.getConnection().prepareTupleQuery(QueryLanguage.SPARQL, query);
    TupleQueryResult res = q.evaluate();
    assertTrue(query, res.hasNext());
    Value c = res.next().getValue("c");
    assertNotNull(query, c);
    assertTrue(query, c instanceof Literal);
    assertEquals(query, count, ((Literal)c).intValue());
}
 
Example 17
Source File: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 4 votes vote down vote up
public void testUpdateData() throws Exception {
    RepositoryConnection conn = repository.getConnection();

    String insert = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" +
            "PREFIX ex: <http://example/addresses#>\n" +
            "INSERT DATA\n" +
            "{ GRAPH ex:G1 {\n" +
            "<http://example/book3> dc:title    \"A new book\" ;\n" +
            "                         dc:creator  \"A.N.Other\" .\n" +
            "}\n" +
            "}";
    Update update = conn.prepareUpdate(QueryLanguage.SPARQL, insert);
    update.execute();

    String query = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" +
            "select * where { <http://example/book3> ?p ?o. }";
    TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
    CountTupleHandler tupleHandler = new CountTupleHandler();
    tupleQuery.evaluate(tupleHandler);
    assertEquals(2, tupleHandler.getCount());

    String insdel = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" +
            "\n" +
            "WITH <http://example/addresses#G1>\n" +
            "DELETE { ?book dc:title ?title }\n" +
            "INSERT { ?book dc:title \"A newer book\"." +
            "         ?book dc:add \"Additional Info\" }\n" +
            "WHERE\n" +
            "  { ?book dc:creator \"A.N.Other\" ;\n" +
            "        dc:title ?title .\n" +
            "  }";
    update = conn.prepareUpdate(QueryLanguage.SPARQL, insdel);
    update.execute();

    query = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" +
            "PREFIX ex: <http://example/addresses#>\n" +
            "select * where { GRAPH ex:G1 {<http://example/book3> ?p ?o. } }";
    tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
    tupleHandler = new CountTupleHandler();
    tupleQuery.evaluate(tupleHandler);
    assertEquals(3, tupleHandler.getCount());

    conn.close();
}
 
Example 18
Source File: RyaDirectExample.java    From rya with Apache License 2.0 4 votes vote down vote up
private static void testAddAndTemporalSearchWithPCJ(
		final SailRepositoryConnection conn) throws Exception {

	// create some resources and literals to make statements out of

	final String sparqlInsert = "PREFIX time: <http://www.w3.org/2006/time#>\n"
			+ "INSERT DATA {\n" //
			+ "_:eventz       a       time:Instant ;\n"
			+ "     time:inXSDDateTime '2001-01-01T01:01:01-08:00' ;\n" // one
																		// second
			+ "     time:inXSDDateTime '2001-01-01T04:01:02.000-05:00'^^<http://www.w3.org/2001/XMLSchema#dateTime> ;\n" // 2
																															// seconds
			+ "     time:inXSDDateTime \"2001-01-01T01:01:03-08:00\" ;\n" // 3
																			// seconds
			+ "     time:inXSDDateTime '2001-01-01T01:01:04-08:00' ;\n" // 4
																		// seconds
			+ "     time:inXSDDateTime '2001-01-01T09:01:05Z' ;\n"
			+ "     time:inXSDDateTime '2006-01-01' ;\n"
			+ "     time:inXSDDateTime '2007-01-01' ;\n"
			+ "     time:inXSDDateTime '2008-01-01' ; .\n" + "}";

	final Update update = conn.prepareUpdate(QueryLanguage.SPARQL,
			sparqlInsert);
	update.execute();

	// Find all stored dates.
	String queryString = "PREFIX time: <http://www.w3.org/2006/time#> \n"//
			+ "PREFIX tempo: <tag:rya-rdf.org,2015:temporal#> \n"//
			+ "SELECT ?event ?time \n" //
			+ "WHERE { \n"
			+ "  ?event time:inXSDDateTime ?time . \n"//
			+ "  FILTER(tempo:after(?time, '2001-01-01T01:01:03-08:00') ) \n"// after
																				// 3
																				// seconds
			+ "}";//

	TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL,
			queryString);
	CountingResultHandler tupleHandler = new CountingResultHandler();
	tupleQuery.evaluate(tupleHandler);
	log.info("Result count : " + tupleHandler.getCount());
	Validate.isTrue(tupleHandler.getCount() == 5);

	// Find all stored dates.
	queryString = "PREFIX time: <http://www.w3.org/2006/time#> \n"//
			+ "PREFIX tempo: <tag:rya-rdf.org,2015:temporal#> \n"//
			+ "SELECT ?event ?time \n" //
			+ "WHERE { \n"
			+ "  ?event time:inXSDDateTime ?time . \n"//
			+ "  ?event a  time:Instant . \n"//
			+ "  FILTER(tempo:after(?time, '2001-01-01T01:01:03-08:00') ) \n"// after
																				// 3
																				// seconds
			+ "}";//

	tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
	tupleHandler = new CountingResultHandler();
	tupleQuery.evaluate(tupleHandler);
	log.info("Result count : " + tupleHandler.getCount());
	Validate.isTrue(tupleHandler.getCount() == 5);

	// Find all stored dates.
	queryString = "PREFIX time: <http://www.w3.org/2006/time#> \n"//
			+ "PREFIX tempo: <tag:rya-rdf.org,2015:temporal#> \n"//
			+ "SELECT ?event ?time ?e ?c ?l ?o \n" //
			+ "WHERE { \n"
			+ "  ?e a ?c . \n"//
			+ "  ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l . \n"//
			+ "  ?e <uri:talksTo> ?o . \n"//
			+ "  ?event a  time:Instant . \n"//
			+ "  ?event time:inXSDDateTime ?time . \n"//
			+ "  FILTER(tempo:after(?time, '2001-01-01T01:01:03-08:00') ) \n"// after
																				// 3
																				// seconds
			+ "}";//

	tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
	tupleHandler = new CountingResultHandler();
	tupleQuery.evaluate(tupleHandler);
	log.info("Result count : " + tupleHandler.getCount());
	Validate.isTrue(tupleHandler.getCount() == 5);
}
 
Example 19
Source File: MongoRyaDirectExample.java    From rya with Apache License 2.0 4 votes vote down vote up
public static void testAllValuesFromInference(final SailRepositoryConnection conn, final Sail sail) throws MalformedQueryException, RepositoryException,
UpdateExecutionException, QueryEvaluationException, TupleQueryResultHandlerException, InferenceEngineException {
    log.info("Adding Data");
    String insert = "INSERT DATA\n"
            + "{ GRAPH <http://updated/test> {\n"
            + "  <urn:Alice> a <urn:Person> .\n"
            + "  <urn:Alice> <urn:hasParent> <urn:Bob> .\n"
            + "  <urn:Carol> <urn:hasParent> <urn:Dan> .\n"
            + "}}";
    Update update = conn.prepareUpdate(QueryLanguage.SPARQL, insert);
    update.execute();
    final String inferQuery = "select distinct ?x { GRAPH <http://updated/test> { ?x a <urn:Person> }}";
    final String explicitQuery = "select distinct ?x { GRAPH <http://updated/test> {\n"
            + "  { ?x a <urn:Person> }\n"
            + "  UNION {\n"
            + "    ?y a <urn:Person> .\n"
            + "    ?y <urn:hasParent> ?x .\n"
            + "  }\n"
            + "}}";
    log.info("Running Explicit Query");
    final CountingResultHandler resultHandler = new CountingResultHandler();
    TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, explicitQuery);
    tupleQuery.evaluate(resultHandler);
    log.info("Result count : " + resultHandler.getCount());
    Validate.isTrue(resultHandler.getCount() == 2);
    log.info("Running Inference-dependent Query");
    resultHandler.resetCount();
    tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, inferQuery);
    tupleQuery.evaluate(resultHandler);
    log.info("Result count : " + resultHandler.getCount());
    Validate.isTrue(resultHandler.getCount() == 1);
    log.info("Adding owl:allValuesFrom Schema");
    insert = "PREFIX rdfs: <" + RDFS.NAMESPACE + ">\n"
            + "PREFIX owl: <" + OWL.NAMESPACE + ">\n"
            + "INSERT DATA\n"
            + "{ GRAPH <http://updated/test> {\n"
            + "  <urn:Person> rdfs:subClassOf [ owl:onProperty <urn:hasParent> ; owl:allValuesFrom <urn:Person> ] ."
            + "}}";
    update = conn.prepareUpdate(QueryLanguage.SPARQL, insert);
    update.execute();
    log.info("Refreshing InferenceEngine");
    ((RdfCloudTripleStore<?>) sail).getInferenceEngine().refreshGraph();
    log.info("Re-running Inference-dependent Query");
    resultHandler.resetCount();
    tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, inferQuery);
    tupleQuery.evaluate(resultHandler);
    log.info("Result count : " + resultHandler.getCount());
    Validate.isTrue(resultHandler.getCount() == 2);
}
 
Example 20
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testSameTermRepeatInUnionAndOptional() throws Exception {
	loadTestData("/testdata-query/dataset-query.trig");

	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("SELECT * {\n");
	query.append("    {\n");
	query.append("        ex:a ?p ?prop1\n");
	query.append("        FILTER (?p = ex:prop1)\n");
	query.append("    } UNION {\n");
	query.append("          ?s ex:p ex:A ; ");
	query.append("          { ");
	query.append("              { ");
	query.append("                 ?s ?p ?l .");
	query.append("                 FILTER(?p = rdfs:label) ");
	query.append("              } ");
	query.append("              OPTIONAL { ");
	query.append("                 ?s ?p ?opt1 . ");
	query.append("                 FILTER (?p = ex:prop1) ");
	query.append("              } ");
	query.append("              OPTIONAL { ");
	query.append("                 ?s ?p ?opt2 . ");
	query.append("                 FILTER (?p = ex:prop2) ");
	query.append("              } ");
	query.append("          }");
	query.append("    }\n");
	query.append("}");

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

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

		int count = 0;
		while (result.hasNext()) {
			BindingSet bs = result.next();
			count++;
			assertNotNull(bs);

			// System.out.println(bs);

			Value prop1 = bs.getValue("prop1");
			Value l = bs.getValue("l");

			assertTrue(prop1 instanceof Literal || l instanceof Literal);
			if (l instanceof Literal) {
				Value opt1 = bs.getValue("opt1");
				assertNull(opt1);

				Value opt2 = bs.getValue("opt2");
				assertNull(opt2);
			}
		}
		assertEquals(2, count);
	} catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

}